Compare commits
1,014 commits
skip-depen
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a1820f1c3 |
||
|
|
06fee6d300 |
||
|
|
706f7d2695 |
||
|
|
1ac8fc6060 |
||
|
|
04f9971120 |
||
|
|
803da5319c |
||
|
|
9feb1f378b |
||
|
|
75fb116e36 |
||
|
|
6fb34e9383 |
||
|
|
c8b88b3a37 |
||
|
|
2bee9aeb58 |
||
|
|
875e8e18bd |
||
|
|
959daf2321 |
||
|
|
8661193411 |
||
|
|
e4d8ca648a |
||
|
|
2c2f98691f |
||
|
|
b9b7ea6914 |
||
|
|
4f28dceac8 |
||
|
|
db92d44ef5 |
||
|
|
886776f5fc |
||
|
|
d267792653 |
||
|
|
a7e9b70919 |
||
|
|
022547ad8c |
||
|
|
34bdd480c9 |
||
|
|
c428a08fea |
||
|
|
10b158baf3 |
||
|
|
9034a2eb4b |
||
|
|
40c3e122e8 |
||
|
|
bc07264529 |
||
|
|
bcef61d806 |
||
|
|
0f18a258d4 |
||
|
|
44c0907dda |
||
|
|
07f6eafd99 |
||
|
|
a22f778dbf |
||
|
|
0792ac812c |
||
|
|
7339936980 |
||
|
|
7a77805159 |
||
|
|
baced6281c |
||
|
|
5a98ceb5ca |
||
|
|
8b76710e66 |
||
|
|
81b1e818e5 |
||
|
|
a8b5da9770 |
||
|
|
0175bc9235 |
||
|
|
d6b9daecb1 |
||
|
|
78c61415b5 |
||
|
|
90ea26f337 |
||
|
|
f4ae8bb0af |
||
|
|
d382943012 |
||
|
|
7674645761 |
||
|
|
75b9f92504 |
||
|
|
c3cbe8b9a3 |
||
|
|
ffea4d6a3e |
||
|
|
794bfe9567 |
||
|
|
11ee46bf3b |
||
|
|
cc02df94c5 |
||
|
|
ea7fb8cb2e |
||
|
|
1550eea886 |
||
|
|
e4ccf06baf |
||
|
|
886c85e5f5 |
||
|
|
95edc1d2f3 |
||
|
|
4e136e60d6 |
||
|
|
27a5921bff |
||
|
|
920cb47778 |
||
|
|
0c1c42f151 |
||
|
|
6c4ba6b420 |
||
|
|
a42faab783 |
||
|
|
b1e0586d4e |
||
|
|
9ea5a40728 |
||
|
|
b2b2b0f918 |
||
|
|
a2bec08e76 |
||
|
|
62afdca775 |
||
|
|
c4dcf833ca |
||
|
|
0172e4c4d4 |
||
|
|
aaaca09a91 |
||
|
|
0e9cab86fd |
||
|
|
4a616d6e39 |
||
|
|
7fe3c1e8bd | ||
|
|
d5ff831602 |
||
|
|
cf7edc895c |
||
|
|
46c3b74346 |
||
|
|
98ac0402df |
||
|
|
dec25ba6be |
||
|
|
fecced2b5c |
||
|
|
5745323ecd |
||
|
|
46cd0c7933 |
||
|
|
f7eed91aa8 |
||
|
|
8768921fd9 |
||
|
|
2d3ad9ca0d |
||
|
|
4ef7d16419 |
||
|
|
7ca58583fd |
||
|
|
96e12569b1 |
||
|
|
a7248480e2 |
||
|
|
18aa6a09d6 |
||
|
|
66d842d6e9 |
||
|
|
681d5a7120 |
||
|
|
c4c72ac240 |
||
|
|
b9fcef1889 |
||
|
|
7699deb99c |
||
|
|
1593257f2a |
||
|
|
90f2e190d0 |
||
|
|
2a93404e8c |
||
|
|
1a43a3b8e9 |
||
|
|
fca339084b |
||
|
|
704b74b3ab |
||
|
|
e056a3946e |
||
|
|
b07f9ce9ae |
||
|
|
e4a87f2afe |
||
|
|
4ebb3fd5e6 |
||
|
|
c4cb1910a3 |
||
|
|
bc770c6fc0 |
||
|
|
ac83711ff8 |
||
|
|
4b09a040be |
||
|
|
387a063aec |
||
|
|
caadfe6413 |
||
|
|
2f992f71ea |
||
|
|
37fb0ad803 |
||
|
|
cb5f6abdd0 |
||
|
|
cf021d1a70 |
||
|
|
f896f5acb5 |
||
|
|
078c44d835 |
||
|
|
39148870af |
||
|
|
601903436b |
||
|
|
79ba8f180d |
||
|
|
76c6f1a64e |
||
|
|
856844cae7 |
||
|
|
cc3d1c18a3 |
||
|
|
d8ac6cbfde |
||
|
|
c556f07a66 |
||
|
|
1c57079b9b |
||
|
|
3f746b91fc |
||
|
|
cb4419ed02 |
||
|
|
8363ec4d26 |
||
|
|
53741dc9c7 |
||
|
|
95f766cb74 |
||
|
|
f81d6c07d8 |
||
|
|
c3ad5e9ecb |
||
|
|
a194acdc5f |
||
|
|
fbee629ed9 |
||
|
|
9019a7af70 |
||
|
|
f627170088 |
||
|
|
733801ed6c |
||
|
|
99327084d2 |
||
|
|
06aa84943c |
||
|
|
1d442ffa36 |
||
|
|
110943fc61 |
||
|
|
1c7ade215b |
||
|
|
edb54bddf3 |
||
|
|
b75dde3b5c |
||
|
|
19c5c507cc |
||
|
|
e5ca0269cb |
||
|
|
bb3ef39a89 |
||
|
|
74e01d5e08 |
||
|
|
8efa405833 |
||
|
|
d41ff5bcd8 |
||
|
|
ef29b731ea |
||
|
|
b0d3e653b9 |
||
|
|
bc22e517fd |
||
|
|
5fa2883670 |
||
|
|
6fce4e538f |
||
|
|
d756b99bf6 |
||
|
|
242850c0f3 |
||
|
|
094738f68a |
||
|
|
4402b48954 |
||
|
|
44d6d739ea |
||
|
|
36caaa6f56 |
||
|
|
30044c7864 |
||
|
|
d0f1468fce |
||
|
|
74b8f1bc1c |
||
|
|
16a09f0151 |
||
|
|
f038cf3be7 |
||
|
|
7417e974f4 |
||
|
|
611a35861d |
||
|
|
10af989563 |
||
|
|
7814d95990 |
||
|
|
e32a2098f9 |
||
|
|
07fa270652 |
||
|
|
2db431f5e5 |
||
|
|
18b898e42a |
||
|
|
9d9bf2b717 |
||
|
|
4ec2757b6d |
||
|
|
d927762003 |
||
|
|
2bcfae3412 |
||
|
|
afbe342587 |
||
|
|
e01c5932bf |
||
|
|
5f428aaced |
||
|
|
57bbc9859e |
||
|
|
52b37b9a0c |
||
|
|
d048c7e690 |
||
|
|
de14ed1b7c |
||
|
|
f2ccb6a32c |
||
|
|
bcf90d5ae7 |
||
|
|
ae43039d8e |
||
|
|
bf352d8a4a |
||
|
|
1e1882851d |
||
|
|
35c2b52652 |
||
|
|
0ba3db1a56 |
||
|
|
1a788cf349 |
||
|
|
effbc568ff |
||
|
|
dd803a0d7f |
||
|
|
c8b8911226 |
||
|
|
c33a3c3b29 |
||
|
|
b0e782a2ee |
||
|
|
7934124fb5 |
||
|
|
d2ac7ed3d2 |
||
|
|
33ed688a8f |
||
|
|
2676864163 |
||
|
|
c6e31a3be6 |
||
|
|
a3163bc275 |
||
|
|
3213776b25 |
||
|
|
cef327d0f2 |
||
|
|
1e529ee27d |
||
|
|
b9b1deacb6 |
||
|
|
eee5e91334 |
||
|
|
717f3535f6 |
||
|
|
0781e723c2 |
||
|
|
87fa361239 |
||
|
|
3041aa241e |
||
|
|
149a7aa2ce |
||
|
|
d3b7922615 |
||
|
|
67e8448389 |
||
|
|
252a29e5e6 |
||
|
|
2899ffb6f3 |
||
|
|
cee327d8f7 |
||
|
|
81fada4922 |
||
|
|
a57f1c8b20 |
||
|
|
654335607c |
||
|
|
62d32c6a90 |
||
|
|
2ebf19e5e1 |
||
|
|
83702a41f8 |
||
|
|
243f054f65 |
||
|
|
998b37f32b |
||
|
|
f018f68bbf |
||
|
|
7d76c9d055 |
||
|
|
3fdeedb567 |
||
|
|
c241cd4698 |
||
|
|
7e077186fc |
||
|
|
16383a64d6 |
||
|
|
00cab8ba8f |
||
|
|
d7eda92a2b |
||
|
|
981a69d839 |
||
|
|
18b5ab5852 |
||
|
|
66c0270bc1 |
||
|
|
bdb76ef4b2 |
||
|
|
a3ecd1edb1 |
||
|
|
d779414f8a |
||
|
|
918b85f9b2 |
||
|
|
ff2fc234b2 |
||
|
|
b623c23183 |
||
|
|
977f02347b |
||
|
|
6202008cf3 |
||
|
|
1fca15abe6 |
||
|
|
291fab8789 |
||
|
|
a04f6fd911 |
||
|
|
266c129b62 |
||
|
|
836ceac30e |
||
|
|
1d932cc778 |
||
|
|
9f251bad00 |
||
|
|
4ad78a60ef |
||
|
|
00a7745994 |
||
|
|
fd5d98bd13 |
||
|
|
8ba5b89918 |
||
|
|
3c43038860 |
||
|
|
515a2244a2 |
||
|
|
f30f847e1f |
||
|
|
f0e350942f |
||
|
|
7832f884c6 |
||
|
|
3cb34034d2 |
||
|
|
bf3a079f87 |
||
|
|
4a8852af10 |
||
|
|
7c2133a52f |
||
|
|
805ce96689 |
||
|
|
45475bd072 |
||
|
|
da5754671b |
||
|
|
7f032bb82e |
||
|
|
396fb876d3 |
||
|
|
508a08475f |
||
|
|
6a6fdcb2bb |
||
|
|
14373cc60b |
||
|
|
e5d9d1f17d |
||
|
|
be8aee3a96 |
||
|
|
ad02710e9b |
||
|
|
36cbef6813 |
||
|
|
d74f7b5996 |
||
|
|
d1c51ea4db |
||
|
|
9d95e34e19 |
||
|
|
497ed2ea00 |
||
|
|
e89763d709 |
||
|
|
6621024ce4 |
||
|
|
ac78e6f693 |
||
|
|
023a578279 |
||
|
|
13b9ab80ab |
||
|
|
77131edc00 |
||
|
|
05be554e85 |
||
|
|
b023aae51a |
||
|
|
389e3b78e7 |
||
|
|
17954f569d |
||
|
|
1966e619f7 |
||
|
|
3522a98766 |
||
|
|
1eedd1f6f1 |
||
|
|
3b1afe6cf1 |
||
|
|
874425a113 |
||
|
|
691766b5d0 |
||
|
|
47907e0767 |
||
|
|
c1b0396c0a |
||
|
|
522ed5bb30 |
||
|
|
67527c1f69 |
||
|
|
57a279928d |
||
|
|
cccb529f50 |
||
|
|
0d8844d5a7 |
||
|
|
de521e651d |
||
|
|
feaae683a4 |
||
|
|
5de15e0c21 |
||
|
|
a1dd8b12e1 |
||
|
|
6b2a2d507a |
||
|
|
a8bb1b08c2 |
||
|
|
0668eb7b80 |
||
|
|
4d5627ba5d |
||
|
|
7643480bd6 |
||
|
|
dc4b0e202d |
||
|
|
cccff4849e |
||
|
|
0cffe41115 |
||
|
|
a612846224 |
||
|
|
ade2b3ff46 |
||
|
|
094908042c |
||
|
|
a13e48ea6f |
||
|
|
7f2d034f4d |
||
|
|
ea63d06241 |
||
|
|
0d5667bed2 |
||
|
|
ba77e4626b |
||
|
|
222742a737 |
||
|
|
6429909f05 |
||
|
|
27a0720928 |
||
|
|
47101eeccd |
||
|
|
cf1d821129 |
||
|
|
ddcdf64813 |
||
|
|
5fa4f32cca |
||
|
|
0ca2c0d115 |
||
|
|
9b1a1a04e0 |
||
|
|
d7730788fa |
||
|
|
4ce8e2a5d0 |
||
|
|
257fe32556 |
||
|
|
3b8538e242 |
||
|
|
0445c31fef |
||
|
|
9261793ae0 |
||
|
|
e1b52d00fe |
||
|
|
e58f386bac |
||
|
|
3f09c683cc |
||
|
|
e124bde34e |
||
|
|
dae11bbc40 |
||
|
|
0f4f78c464 |
||
|
|
1a06130fcf |
||
|
|
58e0f5320b |
||
|
|
8e66b0a47a |
||
|
|
53b20168c8 |
||
|
|
989f6f8bde |
||
|
|
140d96aadd |
||
|
|
e9848d66a3 |
||
|
|
a25ca12a41 |
||
|
|
802ceaaa6b |
||
|
|
2bff3725bf |
||
|
|
986353f26b |
||
|
|
59223f6e89 |
||
|
|
70013c5a91 |
||
|
|
b8c9d58d61 |
||
|
|
9b5d402bf2 |
||
|
|
6acacf2191 |
||
|
|
292e9af087 |
||
|
|
44180d1e3d |
||
|
|
986af54afa |
||
|
|
7a82b57efb |
||
|
|
e242abee7d |
||
|
|
8382569027 |
||
|
|
0e5ec37597 |
||
|
|
fd4d24ff62 |
||
|
|
b194349983 |
||
|
|
2ac23a4de5 |
||
|
|
1222e8e47a |
||
|
|
b4c35027c2 |
||
|
|
dbf5ee24be |
||
|
|
81a16ed27f |
||
|
|
0022d8518f |
||
|
|
9d384ffa7f |
||
|
|
bdbef49383 |
||
|
|
2a262438fa |
||
|
|
1c4069efa3 |
||
|
|
b0fb2c3ae6 |
||
|
|
7cfcaf22b8 |
||
|
|
834f96d462 |
||
|
|
5c2627cb15 |
||
|
|
2d61d8a46b |
||
|
|
01b971d80d |
||
|
|
d6984f4719 |
||
|
|
7fddab52a9 |
||
|
|
344a4f81b5 |
||
|
|
11951585c0 |
||
|
|
24b594b1e3 |
||
|
|
d3ff774c78 |
||
|
|
d8dcc273ca |
||
|
|
255e3e4910 |
||
|
|
73df4dcaee |
||
|
|
ee48a0fd6e |
||
|
|
bb4894d215 |
||
|
|
8209093871 |
||
|
|
cf59a4511f |
||
|
|
89b99ecfb9 |
||
|
|
310314cf14 |
||
|
|
28722f846a |
||
|
|
567b832bca |
||
|
|
6b6db33c4a |
||
|
|
3d476ca01e |
||
|
|
aaff9243a3 |
||
|
|
b8597f941d |
||
|
|
4719f3055a |
||
|
|
61e56c683e |
||
|
|
074189265d |
||
|
|
a037bd8cc7 |
||
|
|
0b59af9489 |
||
|
|
44d3f8d858 |
||
|
|
20359de953 |
||
|
|
1cfd30840d |
||
|
|
73b7f2e44d |
||
|
|
51e339d8ed |
||
|
|
2ffe68cfa1 |
||
|
|
f5dea2a17c |
||
|
|
d0315974fa |
||
|
|
b96ce24e35 |
||
|
|
6f3ea0b929 |
||
|
|
a010927ea5 |
||
|
|
0fe01372f0 |
||
|
|
c740b6d70a |
||
|
|
4be46c6fa6 |
||
|
|
07c34acb12 |
||
|
|
e95efce988 |
||
|
|
74efa32edf |
||
|
|
485747353e |
||
|
|
008f91d84b |
||
|
|
eebdc8c031 |
||
|
|
2d6143c6d8 |
||
|
|
db6bc3e94c |
||
|
|
34f6e68826 |
||
|
|
5009d64465 |
||
|
|
a075b14432 |
||
|
|
801385df44 |
||
|
|
64fbc52e1d |
||
|
|
c759890d9e |
||
|
|
b4c4cfd3d5 |
||
|
|
37a46231fd |
||
|
|
97bff96ef1 |
||
|
|
1e67c53a17 |
||
|
|
ff8aa484ff |
||
|
|
e1ea695d68 |
||
|
|
789a298650 |
||
|
|
7fb037f20c |
||
|
|
eb1426251c |
||
|
|
98f69bdba0 |
||
|
|
e3f845f558 |
||
|
|
34313ea112 |
||
|
|
ac1416bd2e |
||
|
|
39b421a464 |
||
|
|
5593cf3e11 |
||
|
|
012f674ee4 |
||
|
|
7dd573980a |
||
|
|
970b92bb16 |
||
|
|
7184a4ca21 |
||
|
|
e4bb6666ab |
||
|
|
8c020adfc6 |
||
|
|
8d1b28958f |
||
|
|
4ea102b433 |
||
|
|
757678bc7e |
||
|
|
55f3cade10 |
||
|
|
7d7607473d |
||
|
|
b732a4a516 |
||
|
|
5c2ff1bd7b |
||
|
|
f4f2ec07fb |
||
|
|
338b80c3ae |
||
|
|
110cd3adcb |
||
|
|
3117846176 |
||
|
|
031c7e03b4 |
||
|
|
200d79e7d2 |
||
|
|
82f310fe61 |
||
|
|
c2dafc1c88 |
||
|
|
e66cce2538 |
||
|
|
db6d7a8a61 |
||
|
|
9a063963f4 |
||
|
|
a6bd66aca8 |
||
|
|
f21e51794c |
||
|
|
99bf81c64f |
||
|
|
279b601f80 |
||
|
|
74d09ee0f5 |
||
|
|
0a921f5372 |
||
|
|
e8f2fefb06 |
||
|
|
fa9ad6cb81 |
||
|
|
f23599283c |
||
|
|
9a447cb08d |
||
|
|
673e6bb0f7 |
||
|
|
57f1b1bced |
||
|
|
dfe9b307bd |
||
|
|
1d39e26025 |
||
|
|
7f80f78906 |
||
|
|
82253ad0f5 |
||
|
|
6a82eb3ead |
||
|
|
9264728330 |
||
|
|
06f58eb617 |
||
|
|
683ce919e3 |
||
|
|
56456cb188 |
||
|
|
f3c00ba1b7 |
||
|
|
fb03e85592 |
||
|
|
cae9333f4f |
||
|
|
d5a3d54662 |
||
|
|
f71680c427 |
||
|
|
73deedf3a4 |
||
|
|
901453902f |
||
|
|
d6b55c0b2f |
||
|
|
f26c8fad3e |
||
|
|
af957e773f |
||
|
|
671eaf0f03 |
||
|
|
74797c8cac |
||
|
|
9e2e602038 |
||
|
|
7825355b98 |
||
|
|
b99b050e80 |
||
|
|
95102c7d7c |
||
|
|
d0bcec979c |
||
|
|
790f0bcb47 |
||
|
|
4b59e0d94b |
||
|
|
468559978a |
||
|
|
eec52b1f02 |
||
|
|
c946664a16 |
||
|
|
db9e2685fb |
||
|
|
faf5f86e09 |
||
|
|
ce9c4bcd53 |
||
|
|
d1adb041ea |
||
|
|
0194c6e8ea |
||
|
|
6592aaa70e |
||
|
|
9f0d8d3d12 |
||
|
|
556fd8fa42 |
||
|
|
e064ba69de |
||
|
|
a3c5cc12d3 |
||
|
|
f5be772403 |
||
|
|
f14456d63a |
||
|
|
2b9d3eee0f |
||
|
|
e1ea133fb7 |
||
|
|
042db1d0e3 |
||
|
|
e5b96343d1 |
||
|
|
3ef9130269 |
||
|
|
3cb5579253 |
||
|
|
8ee81b3037 |
||
|
|
bbccc52b60 |
||
|
|
5587cb7c43 |
||
|
|
0212a718c7 |
||
|
|
c642d6a5cf |
||
|
|
07e950ec09 |
||
|
|
99eaeb8af4 |
||
|
|
eac646e744 |
||
|
|
4bbc4eec3b |
||
|
|
34e632db7f |
||
|
|
e2f72d863c |
||
|
|
d41bcb2c9e |
||
|
|
697426b39e |
||
|
|
75583a6b1f |
||
|
|
333aaddff5 |
||
|
|
927a03bee1 |
||
|
|
a52ab0e92d |
||
|
|
1cccdc2d27 |
||
|
|
c3c41b4402 |
||
|
|
4f7668807a |
||
|
|
61f3feec6a |
||
|
|
5be249ada3 |
||
|
|
665514e19a |
||
|
|
f189d1f7fb |
||
|
|
6faa2d61f8 |
||
|
|
dd8816c6cc |
||
|
|
d27495960a |
||
|
|
4a54be2d5f |
||
|
|
961dd50456 |
||
|
|
f01d0c581c |
||
|
|
85b7efd746 |
||
|
|
27abe3c3f0 |
||
|
|
493989f231 |
||
|
|
dd7d89aaae |
||
|
|
9b89eb192d |
||
|
|
60d2817245 |
||
|
|
57a7f121d4 |
||
|
|
d1f7195d7b |
||
|
|
596210c2ba |
||
|
|
79821c4eff |
||
|
|
3354c40992 |
||
|
|
7ed31e42d4 |
||
|
|
d4289b27c0 |
||
|
|
2c08edecec |
||
|
|
beb35a4ed8 |
||
|
|
8c10bb8881 |
||
|
|
923695bd9a |
||
|
|
5338629474 |
||
|
|
90bd4ffaa4 |
||
|
|
1d8a8bcf36 |
||
|
|
5879119de5 |
||
|
|
5683c0f495 |
||
|
|
16eb2ffcb0 |
||
|
|
2491993327 |
||
|
|
376a4a57e2 |
||
|
|
773f6586e0 |
||
|
|
3e1aadb282 |
||
|
|
c63be5d178 |
||
|
|
2a2f4c8e4d |
||
|
|
cd483a1432 |
||
|
|
8ff28c13fa |
||
|
|
b9ea53618d |
||
|
|
426572670e |
||
|
|
b7cb7cea81 |
||
|
|
77d8b3ae97 |
||
|
|
ce7758e9b3 |
||
|
|
59a126a0b6 |
||
|
|
b1505ba5d7 |
||
|
|
396bf1572a |
||
|
|
f5804f4761 |
||
|
|
65ea57963a |
||
|
|
6c76bea3e8 |
||
|
|
ec5de0d26f |
||
|
|
145dbbfb4c |
||
|
|
492db9972f |
||
|
|
00df243171 |
||
|
|
c3f0223bbb |
||
|
|
1eabe7f74a |
||
|
|
c04c9d0ce5 |
||
|
|
c397e68d39 |
||
|
|
ca76b82878 |
||
|
|
6f4df1eac4 |
||
|
|
7c98326d61 |
||
|
|
c04ce8972f |
||
|
|
39af26885f |
||
|
|
d23f553874 |
||
|
|
6f30e89dd1 |
||
|
|
b92f5662d7 |
||
|
|
352525c8e5 |
||
|
|
e5dce51286 |
||
|
|
204e566227 |
||
|
|
96497acd16 |
||
|
|
52feff6878 |
||
|
|
d27c26e0ff |
||
|
|
9d1a9cccd8 |
||
|
|
2d7bc4e73d |
||
|
|
718ed8b140 |
||
|
|
1be9b4d39c |
||
|
|
85faad59a1 |
||
|
|
faef74b374 |
||
|
|
196e2b48c5 |
||
|
|
f01c8fd7f4 |
||
|
|
55094fd49b |
||
|
|
27e65fc978 |
||
|
|
ff20c56c85 |
||
|
|
269c9c9f46 |
||
|
|
02d55dec32 |
||
|
|
734b93b999 |
||
|
|
9aa31d57f2 |
||
|
|
a50dcd8705 |
||
|
|
62dcea64c2 |
||
|
|
754fb01088 |
||
|
|
360c9c31e5 |
||
|
|
6bffb22c6c |
||
|
|
3407671ac2 |
||
|
|
25d550caf1 |
||
|
|
f9ed06176a |
||
|
|
bb37c3bb6b |
||
|
|
b0b3a6dd95 |
||
|
|
b2d4cc90e5 |
||
|
|
8fdb3cc27c |
||
|
|
93753e137e |
||
|
|
e0455fec95 |
||
|
|
00ed31f2cc |
||
|
|
943af98b0d |
||
|
|
32dfe50f39 |
||
|
|
b5a45034ab |
||
|
|
d1ed7cd24d |
||
|
|
226bfb49fa |
||
|
|
3bea192c8c |
||
|
|
b720fc5e38 |
||
|
|
ea529f6a49 |
||
|
|
abc89879a7 |
||
|
|
40bdfb6b1d |
||
|
|
c861862aed |
||
|
|
959ac2b111 |
||
|
|
9be42d9013 |
||
|
|
7017106c63 |
||
|
|
71ba030380 |
||
|
|
5ff64ce21b |
||
|
|
d5d5c45be3 |
||
|
|
ca8069cb86 |
||
|
|
01c57a9e04 |
||
|
|
32f1118a11 |
||
|
|
cedf734f15 |
||
|
|
e35a74f004 |
||
|
|
11960b1e19 |
||
|
|
dc7ae0bad1 |
||
|
|
0b8479ad73 |
||
|
|
7235029486 |
||
|
|
139d2d8f96 |
||
|
|
e2bdc9288b |
||
|
|
68e76fea2e |
||
|
|
fcae127664 |
||
|
|
24d7aefe28 |
||
|
|
e41e1fec10 |
||
|
|
a52036ed0f |
||
|
|
cfff8e8d09 |
||
|
|
59a6fb3839 |
||
|
|
e1338e06a2 | ||
|
|
f7d46e7747 | ||
|
|
2c451bf6ba |
||
|
|
33c3acfc87 |
||
|
|
f08205789e |
||
|
|
30308332bb |
||
|
|
08f590fa9e |
||
|
|
5ed14650ab |
||
|
|
ad517d09fa |
||
|
|
bafd5419fa |
||
|
|
58e25ccf47 |
||
|
|
ceb8ff18c6 |
||
|
|
6637bcebe1 |
||
|
|
9f8347dbaf |
||
|
|
297880bbfa |
||
|
|
44b8238e40 |
||
|
|
d316f193a8 |
||
|
|
901d8cdd60 |
||
|
|
544f072659 |
||
|
|
dcaeef0f3d |
||
|
|
0b97aca02a |
||
|
|
706b56d555 |
||
|
|
ea19a2a5f5 |
||
|
|
163c16876f |
||
|
|
1708e53d9e |
||
|
|
9ec4e7ae1b |
||
|
|
fadb630142 |
||
|
|
9ccaef2b6a |
||
|
|
85c71fa834 |
||
|
|
799c4f1673 |
||
|
|
56b165537f |
||
|
|
e3b6b0c470 |
||
|
|
72d04d7c7f | ||
|
|
9319a2c645 | ||
|
|
216f43d0ba |
||
|
|
b8c37bfa89 |
||
|
|
519f9c569c |
||
|
|
1c64d1c6b1 |
||
|
|
34d848b16a |
||
|
|
d4a8354ba2 |
||
|
|
ea214282c1 | ||
|
|
fce4182860 | ||
|
|
b061126955 | ||
|
|
d8e6540f24 | ||
|
|
0142fefe1b | ||
|
|
03673d9fad | ||
|
|
f923b671ce | ||
|
|
cea6e935e9 | ||
|
|
fec8e8d5ab | ||
|
|
cb34191128 | ||
|
|
6aff9c94be | ||
|
|
0cfc9399d7 | ||
|
|
ecc1ede928 |
||
|
|
8bc31360e8 |
||
|
|
8a356ad870 |
||
|
|
fccbd43c1e |
||
|
|
404b820144 |
||
|
|
49534ce91d |
||
|
|
af557388c7 |
||
|
|
902b63f676 |
||
|
|
f2dd2e5124 |
||
|
|
2ab8beb195 |
||
|
|
59da3e4ed4 |
||
|
|
547daf7a36 |
||
|
|
5fb72c7200 | ||
|
|
8ad4eb8321 | ||
|
|
f3b1055b2a | ||
|
|
62c5520180 | ||
|
|
7eba044dd8 | ||
|
|
f9a4eb1647 | ||
|
|
ee6f469aa5 | ||
|
|
33a69d7d0a |
||
|
|
1e72f2457b |
||
|
|
9d635bc026 | ||
|
|
52144ce20b | ||
|
|
2b28cd2a88 | ||
|
|
d35ce8dd2e | ||
|
|
173b93a4c3 | ||
|
|
f14f7783df | ||
|
|
7a582ff5a0 | ||
|
|
d7674b3c0c | ||
|
|
610551c7b6 |
||
|
|
7690e995b8 | ||
|
|
7a92b82097 | ||
|
|
72129c3d03 | ||
|
|
0afd990ee6 | ||
|
|
75d6e2fc10 | ||
|
|
18d5902367 | ||
|
|
14e64b3b22 | ||
|
|
09a99e1ecc | ||
|
|
b01e66dc58 | ||
|
|
3ff1472ea9 |
||
|
|
2d1fe3ec0f |
||
|
|
b9153404f4 |
||
|
|
3438b77e88 | ||
|
|
9344224452 | ||
|
|
c96c0400f3 |
||
|
|
c349bd9e25 |
||
|
|
507e6b80ab |
||
|
|
2d3d0d5eab |
||
|
|
80efbd3d57 |
||
|
|
43ac5395b9 |
||
|
|
8a4c9b33e1 |
||
|
|
892e1731f7 | ||
|
|
730175910c | ||
|
|
1704ffe88f | ||
|
|
d773079aba | ||
|
|
d9541c9c21 | ||
|
|
270783e614 |
||
|
|
59bb0a3ce7 |
||
|
|
549f48bc7a |
||
|
|
e87ede075c |
||
|
|
5815e1eff8 |
||
|
|
37126d6d3f |
||
|
|
e19f2396b3 |
||
|
|
c71840631e |
||
|
|
40d3190317 |
||
|
|
d85cfb84e1 |
||
|
|
83d6254757 |
||
|
|
0d4580fef3 |
||
|
|
3ec7cfa0d5 |
||
|
|
bb3e159bc6 |
||
|
|
43e9cdd275 |
||
|
|
2218a6f52a |
||
|
|
1d7e92ecab |
||
|
|
f84b2dae04 |
||
|
|
7e0eb2ff9d |
||
|
|
fc6290479f |
||
|
|
ea1328660e |
||
|
|
1caf40eee8 |
||
|
|
5e2d698356 |
||
|
|
aa7946d353 |
||
|
|
390a11d7d2 |
||
|
|
35bbf4800f |
||
|
|
b894a0b747 |
||
|
|
3f2090f10a |
||
|
|
08387157bb |
||
|
|
06155d3d67 |
||
|
|
9975e1cc6e |
||
|
|
64e9153426 |
||
|
|
f085428b32 |
||
|
|
92f4c503cd |
||
|
|
e717e1623c |
||
|
|
8a13032419 |
||
|
|
a2efd686a9 |
||
|
|
78010ef06e |
||
|
|
1eb57ba262 |
||
|
|
958e657521 |
||
|
|
657298112b |
||
|
|
7aba0df323 |
||
|
|
9b248a15b3 |
||
|
|
3a4d41346c |
||
|
|
27be9fe229 |
||
|
|
a8b100eb8c |
||
|
|
016b9f90e0 |
||
|
|
2dcbb944a8 |
||
|
|
5dd8cde2f9 |
||
|
|
5dc2432950 |
||
|
|
564b4c0d5c |
||
|
|
85a833a74b |
||
|
|
b4eb1adbeb |
||
|
|
dab2084c74 |
||
|
|
453dcbe808 |
||
|
|
62804e2f06 |
||
|
|
d3032c10a2 |
||
|
|
964ba12bc5 | ||
|
|
b14b137fdd |
||
|
|
edac1e5427 | ||
|
|
618195c065 |
||
|
|
ccfe5047bf |
||
|
|
bb60287005 |
||
|
|
e5553177d7 |
||
|
|
5f941be5a3 |
||
|
|
b62ed3408b |
||
|
|
88c89248d0 |
||
|
|
3907a4f9b6 |
||
|
|
175479f65f |
||
|
|
359575b12f |
||
|
|
a307e9c3cc |
||
|
|
16a85ffcd8 |
||
|
|
b42f6f9a48 |
||
|
|
c9fbd1f5de |
||
|
|
b3b630ee7b |
||
|
|
fe57c3d689 |
||
|
|
50b23299f8 |
||
|
|
25e2f4da32 |
||
|
|
0f95ed72cd |
||
|
|
263e0bf6e0 |
||
|
|
f75cd05e50 |
||
|
|
3e79572660 |
||
|
|
f3d33f830c |
||
|
|
8e1f662d93 |
||
|
|
efcc12bc76 |
||
|
|
a53030a806 | ||
|
|
6e22914360 | ||
|
|
a95fed3041 |
||
|
|
95b4271b3b | ||
|
|
aa4db3d00e | ||
|
|
95816c5ae2 |
||
|
|
361eb08f42 | ||
|
|
3809f0c77b |
||
|
|
1d0c0adeab |
||
|
|
a715176499 |
||
|
|
40e80d60e5 |
||
|
|
f7c47f498c |
||
|
|
cdad99583e |
||
|
|
eeb17855a6 |
||
|
|
a1cf2aff6e |
||
|
|
81a7c83c67 |
||
|
|
5bab188106 |
||
|
|
939cf5fcf2 |
||
|
|
45af482e73 |
||
|
|
dfb857aa08 |
||
|
|
3b0660a686 |
||
|
|
f7cdd20a42 |
||
|
|
3d665d48c0 | ||
|
|
1f84e5055e | ||
|
|
5dafe19a9d | ||
|
|
ecbce07636 | ||
|
|
806aa8c579 |
||
|
|
1ed9770892 |
||
|
|
25f3b0878e |
||
|
|
3e3ed76a8c |
||
|
|
d12d46b049 |
||
|
|
931d6f878c |
||
|
|
ad3b1b9d1b |
||
|
|
85eff33b81 |
||
|
|
6a358902f2 |
||
|
|
b8d789c1b4 |
||
|
|
32c6826e13 |
||
|
|
30832ced1c |
||
|
|
880d835ccc |
||
|
|
db650ca7cb |
||
|
|
5e0211dd5e |
||
|
|
b776089ecc |
||
|
|
d5f5300e63 |
||
|
|
422384e576 |
||
|
|
76f054e957 |
||
|
|
4262cfc16a |
||
|
|
f6988c9206 |
||
|
|
5fd41b2e15 |
||
|
|
fe432de156 |
||
|
|
49707813f4 |
||
|
|
32017f7fb1 |
||
|
|
b076b2154c |
||
|
|
c09e748a12 |
||
|
|
08974e50d9 |
||
|
|
c8e2c621ef |
||
|
|
b3b26e602c |
||
|
|
6fa90fa792 |
||
|
|
186604a8a2 |
||
|
|
b2f5551d22 |
||
|
|
adf21ac630 |
||
|
|
bd37763e98 |
||
|
|
cec40b378d | ||
|
|
cd085412d1 | ||
|
|
684cbff634 |
||
|
|
82c9409006 |
||
|
|
96569177a8 |
||
|
|
6b1394ebf8 |
||
|
|
4e10ad6299 |
||
|
|
70f0fd3a0a |
||
|
|
b7344d7045 |
||
|
|
c7eb47183d |
||
|
|
4544b634c6 |
||
|
|
e17d50e0e8 |
||
|
|
8de1470973 |
||
|
|
62f532454e |
||
|
|
1bbbee37a6 |
||
|
|
12cb58f220 |
||
|
|
2629631536 |
||
|
|
9a47d30266 |
||
|
|
80188a1bd0 |
||
|
|
003df5b22b |
||
|
|
d52534ae32 |
||
|
|
d9cbc06ff1 |
||
|
|
8b3010825e |
||
|
|
f4842cd3e6 |
||
|
|
46e0e01066 |
||
|
|
17d3f13f24 |
||
|
|
de22bbb6cb |
||
|
|
fa5b136205 |
||
|
|
6edd5e699e |
||
|
|
d3bb9a0514 |
||
|
|
05380f23fc |
||
|
|
82a00dde41 |
||
|
|
5da65096fc |
||
|
|
311e173b99 |
||
|
|
cfba439417 | ||
|
|
fdc96f323a |
||
|
|
20e84a9cfb | ||
|
|
61aeffb90c | ||
|
|
7002fd45c3 | ||
|
|
1345ea7f42 | ||
|
|
e82bb06025 | ||
|
|
96280b3d2c |
||
|
|
fde9068efb |
||
|
|
cee99d1210 |
||
|
|
c1f50e49be |
||
|
|
b77484e1a7 |
||
|
|
606ce46db1 |
||
|
|
f0c77a32be |
||
|
|
ea5e8c66c1 |
||
|
|
783d402038 |
||
|
|
1ad3704e17 |
||
|
|
3745810db2 |
||
|
|
884b81a0f8 |
||
|
|
41c56481af |
||
|
|
72373c9d0b |
||
|
|
62cc28c7b0 |
26
.claude/hooks/session-init.sh
Executable file
|
|
@ -0,0 +1,26 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Only run in remote/cloud environments
|
||||
if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
command -v gh &> /dev/null && exit 0
|
||||
|
||||
LOCAL_BIN="$HOME/.local/bin"
|
||||
mkdir -p "$LOCAL_BIN"
|
||||
|
||||
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
||||
VERSION=$(curl -fsSL https://api.github.com/repos/cli/cli/releases/latest | grep '"tag_name"' | cut -d'"' -f4)
|
||||
TARBALL="gh_${VERSION#v}_linux_${ARCH}.tar.gz"
|
||||
|
||||
echo "Installing gh ${VERSION}..."
|
||||
TEMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TEMP"' EXIT
|
||||
curl -fsSL "https://github.com/cli/cli/releases/download/${VERSION}/${TARBALL}" | tar -xz -C "$TEMP"
|
||||
cp "$TEMP"/gh_*/bin/gh "$LOCAL_BIN/gh"
|
||||
chmod 755 "$LOCAL_BIN/gh"
|
||||
|
||||
[ -n "$CLAUDE_ENV_FILE" ] && echo "export PATH=\"$LOCAL_BIN:\$PATH\"" >> "$CLAUDE_ENV_FILE"
|
||||
echo "gh installed: $("$LOCAL_BIN/gh" --version | head -1)"
|
||||
15
.claude/settings.json
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/session-init.sh",
|
||||
"timeout": 120
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,13 @@ Be friendly and welcoming while maintaining high standards. Call out what works
|
|||
|
||||
Even perfect code for unwanted features should be rejected.
|
||||
|
||||
### Dependency version compatibility
|
||||
|
||||
When a PR adapts code to a new version of a dependency (e.g., removing a parameter that was dropped upstream, using a new API):
|
||||
- **The version pin in `pyproject.toml` must match.** If the change breaks compatibility with the previously-pinned minimum version, the minimum version must be bumped. Otherwise users on the old version get a regression.
|
||||
- **If backwards compatibility with the old version is desired**, the code must handle both versions (e.g., try/except, version check). Simply deleting the old API usage without bumping the pin is always wrong — it silently breaks users on the old version.
|
||||
- **Lock file (`uv.lock`) changes should be scoped to the PR's purpose.** A PR fixing a ty compatibility issue should not also include unrelated dependency version bumps (anthropic, google-auth, etc.) from running `uv sync --upgrade`. These create noise and make the diff harder to review.
|
||||
|
||||
### API design and naming
|
||||
|
||||
Identify confusing patterns or non-idiomatic code:
|
||||
|
|
|
|||
168
.claude/skills/review-issue/SKILL.md
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
---
|
||||
name: review-issue
|
||||
description: Review an incoming external issue (and any gated-closed PR behind it) and decide whether to assign the contributor or decline. Use when the maintainer says "look at this issue", "review issue #N", "should we take this", or asks whether to assign someone. Assigning the author auto-reopens their PR for normal review. This is the entry point for incoming-issue triage — distinct from review-pr, which responds to bot reviews on your own open PR.
|
||||
---
|
||||
|
||||
# Triaging contributions under the issue-link gate
|
||||
|
||||
FastMCP auto-closes external PRs unless the author is **assigned to a referenced issue**
|
||||
(see [require-issue-link.yml](../../../.github/workflows/require-issue-link.yml)). The practical
|
||||
effect: contributors open an issue, open a PR, get auto-closed, and ask to be assigned. The
|
||||
maintainer almost never sees the PR directly — **the issue is the decision point**, and
|
||||
**assigning the author is the single action that reopens their PR** and sends it into review.
|
||||
|
||||
This skill turns "look at this issue" into one of two outcomes:
|
||||
- **Assign** — the issue is valid, we want it fixed, an external PR is appropriate, and a sound
|
||||
PR already exists → assign the author (auto-reopens the PR) and queue it for code review.
|
||||
- **Decline** — leave the issue/PR closed and explain why on the issue.
|
||||
|
||||
Be opinionated about declining. The gate moved spam from junk PRs to junk issues; this skill is
|
||||
worthless if it just rubber-stamps assignment. Assignment is a commitment to review and likely
|
||||
merge, not a courtesy.
|
||||
|
||||
## How the gate works (the part that matters here)
|
||||
|
||||
- External PR is closed unless its body has `Fixes/Closes/Resolves #N` **and** the author is
|
||||
assigned to issue `#N`.
|
||||
- **Assigning the author to the issue auto-reopens their closed PR** and re-runs the check —
|
||||
this is the lever you pull. `gh issue edit N --add-assignee <login>`. The assignment fires a
|
||||
`require-issue-link` run; expect it to pass. If it fails, the gate itself misbehaved (not the
|
||||
PR) — investigate the run, don't re-assign.
|
||||
- Maintainer-authored PRs are exempt. A `trusted-contributor` label exempts a contributor up
|
||||
front. Reopening the PR or removing the `missing-issue-link` label applies a sticky
|
||||
`bypass-issue-check`.
|
||||
- Sibling bots have usually already run on the issue: `marvin-triage-issue` (investigates +
|
||||
recommends), `marvin-dedupe-issues` / `auto-close-duplicates` (dupes), `auto-close-needs-mre`
|
||||
(missing MRE). Read their comments before re-deriving anything.
|
||||
|
||||
## Step 1 — Orient
|
||||
|
||||
Read the issue, its bot triage, and any PR behind it. Run these together:
|
||||
|
||||
```bash
|
||||
gh issue view N --repo PrefectHQ/fastmcp \
|
||||
--json number,title,state,author,body,labels,assignees,comments
|
||||
# Find PRs the author opened that reference this issue (they're likely CLOSED):
|
||||
gh pr list --repo PrefectHQ/fastmcp --state all --search "author:<login> #N in:body" \
|
||||
--json number,title,state,url,labels
|
||||
```
|
||||
|
||||
If a PR exists, pull its metadata and any review-bot comments (CodeRabbit, Codex). Treat the bot
|
||||
comments as leads, not conclusions — they often don't run on closed PRs at all, and even when
|
||||
they do you still owe the PR your own read:
|
||||
|
||||
```bash
|
||||
gh pr view <pr> --repo PrefectHQ/fastmcp --json number,title,body,labels,files,additions,deletions
|
||||
gh pr view <pr> --repo PrefectHQ/fastmcp --comments
|
||||
```
|
||||
|
||||
## Step 2 — Classify the issue (is it valid AND a real bug?)
|
||||
|
||||
- Is there a real, reproducible problem? For bugs, demand an MRE that shows FastMCP misbehaving
|
||||
— not user config error, not a question, not an upstream-SDK issue.
|
||||
- Is it a duplicate or already fixed on `main`? Check the dedupe bot's comment and recent commits.
|
||||
- If the issue itself is weak, **stop here and decline** — don't evaluate the PR. A good PR
|
||||
attached to a bad issue is still declined.
|
||||
|
||||
**A reproducible MRE is not the same as a bug.** This is the trap that produces wrong verdicts:
|
||||
an MRE can demonstrate real, observable behavior that is nonetheless *not a bug*, because it
|
||||
violates no contract the framework intends to hold. The decisive question is not "does this
|
||||
reproduce?" but "does the demonstrated behavior violate the intended contract for this API?" A
|
||||
shared-mutable-state MRE only matters if callers are *supposed* to mutate that state; an
|
||||
ordering/timing MRE only matters if the framework promises an order; a "wrong" value only matters
|
||||
relative to what the API guarantees. An MRE that has to reach past the supported surface to
|
||||
trigger the behavior (mutating a field meant to be set only at construction, depending on an
|
||||
internal that isn't part of the public contract) is showing you a property, not a defect.
|
||||
|
||||
You usually cannot read the intended contract off the code — the code shows what it *does*, not
|
||||
what it *promises*. **The maintainer is often the only authoritative source for the contract, so
|
||||
stopping to ask is legitimate and expected here.** Ask "is X a supported pattern / does this API
|
||||
promise Y?" before sinking time into investigating a fix. If the behavior is in-contract correct,
|
||||
decline — no matter how cleanly the PR fixes it, and no matter how real the MRE looks.
|
||||
|
||||
## Step 3 — Investigate the PR (mandatory; do NOT skip if a PR exists)
|
||||
|
||||
The most common failure of this skill is judging a PR from the diff hunk and the PR description
|
||||
alone. That is a cursory review and it produces wrong verdicts — a redundant-looking conditional
|
||||
can be a real bug fix; a tidy-looking diff can patch the wrong layer. **You cannot assess a PR
|
||||
without reading the code it changes in context.** Reading `gh pr diff` is necessary but never
|
||||
sufficient.
|
||||
|
||||
Do all of this before forming any opinion on quality:
|
||||
|
||||
1. **Read the diff in full**, then **open every file it touches in the repo** (`Read`, not just
|
||||
the patch). The hunk shows *what changed*; the file shows *what it changed into*.
|
||||
2. **Trace the functions and values the change depends on.** Grep for the called functions,
|
||||
the fields being set, and the defaults. If the PR overrides or replaces a value, find what
|
||||
produced the original value and what consumes it downstream.
|
||||
3. **Establish the actual root cause from the issue's MRE**, then check whether the change fixes
|
||||
*that* — at the layer where the bug originates, not a compensating patch elsewhere.
|
||||
4. **Check consistency with adjacent code.** Does the new value/behavior match how nearby code
|
||||
already handles the same case? An inconsistency is a real finding; a match is evidence the fix
|
||||
is correct.
|
||||
5. **Run or read the tests** the PR adds/changes — do they actually exercise the bug, and would
|
||||
they fail without the fix?
|
||||
|
||||
Write down, for yourself, a one-line answer to: *what was broken, where, and does this change fix
|
||||
it there?* If you can't answer from evidence you've actually read, you haven't investigated yet.
|
||||
|
||||
Then separate findings by severity: a **cosmetic** nit (style, a redundant-but-harmless line) is a
|
||||
review comment, not a blocker. A **substantive** defect (wrong layer, breaks an adjacent path,
|
||||
doesn't actually fix the MRE) changes the verdict. Don't let a cosmetic nit read as a reason to
|
||||
decline, and don't let a clean style read as evidence of correctness.
|
||||
|
||||
## Step 4 — Decide if an external PR is appropriate (CONTRIBUTING.md)
|
||||
|
||||
This is the gate CONTRIBUTING.md actually enforces. Map the change to a category:
|
||||
|
||||
- **Simple, well-scoped bug fix** → external PR welcome. Assignable.
|
||||
- **Docs / typo / example fix** → welcome. Assignable.
|
||||
- **Auth provider** → assignable (auth is the one integration exception).
|
||||
- **Enhancement / feature** → needs a maintainer-approved design proposal *in the issue first*.
|
||||
Do **not** assign just because code exists. If the proposal is sound, the path is "approve the
|
||||
approach in the issue, then assign" — not "assign because they were fast."
|
||||
- **Third-party integration** (middleware, provider adapters, non-auth) → decline; belongs in a
|
||||
separate package.
|
||||
- **Sweeping / multi-subsystem change with no prior discussion** → decline.
|
||||
|
||||
Combine the category with the Step 3 investigation: does it fix the cause or paper over a symptom?
|
||||
Does it read like unedited LLM output (verbose body, speculative/shotgun changes)? CONTRIBUTING.md
|
||||
says we close those — a closed PR that reads that way is staying closed.
|
||||
|
||||
## Step 5 — Recommend, then act
|
||||
|
||||
Present a short verdict to the maintainer before mutating anything: **assign** or **decline**,
|
||||
one or two sentences of reasoning, and the exact command you'll run. Wait for confirmation on
|
||||
borderline calls; for clear-cut ones you may proceed and report.
|
||||
|
||||
**Assign** (valid issue + appropriate external contribution + sound PR exists):
|
||||
|
||||
```bash
|
||||
gh issue edit N --repo PrefectHQ/fastmcp --add-assignee <login>
|
||||
```
|
||||
|
||||
That reopens the PR automatically. Then hand off to code review — invoke the `code-review` /
|
||||
`review-pr` skills on the reopened PR. Assignment is not approval; the code still gets the normal
|
||||
pass.
|
||||
|
||||
If a PR's head branch was deleted, assignment can't reopen it — the workflow comments asking the
|
||||
author to open a fresh PR. Don't try to force it.
|
||||
|
||||
**Decline** (invalid issue, wrong contribution type, or low-quality PR): leave it closed and
|
||||
comment on the **issue** explaining the decision, pointing to the relevant CONTRIBUTING.md
|
||||
section. Per repo rules, use `--body-file`, never inline `--body`, for any comment that could
|
||||
contain `$`, backticks, or code:
|
||||
|
||||
```bash
|
||||
gh issue comment N --repo PrefectHQ/fastmcp --body-file /tmp/triage-reply.md
|
||||
```
|
||||
|
||||
Keep the reply short and point to the relevant CONTRIBUTING.md section. (If a `github-reply`
|
||||
skill is available for maintainer voice/tone, use it — but it isn't required.)
|
||||
|
||||
## What this skill does NOT do
|
||||
|
||||
- It doesn't bypass the gate via `trusted-contributor` / `bypass-issue-check` — that's a
|
||||
deliberate maintainer escalation, not a triage outcome.
|
||||
- It doesn't merge. Assignment → reopen → review → (maybe) merge are distinct steps.
|
||||
- It doesn't re-run the first-pass triage the bots already did; read their output instead.
|
||||
108
.claude/skills/review-pr/SKILL.md
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
---
|
||||
name: review-pr
|
||||
description: Monitor and respond to automated PR reviews (Codex bot). Use when pushing a PR, checking review status, or responding to bot feedback. Handles the full cycle of push -> wait for review -> evaluate comments -> fix -> re-push.
|
||||
---
|
||||
|
||||
# PR Review Workflow
|
||||
|
||||
This repo has `chatgpt-codex-connector[bot]` configured as an automated reviewer. After every push to a PR branch, Codex reviews the diff and either:
|
||||
- Reacts with a thumbs-up on its review body (no suggestions — PR is clean)
|
||||
- Posts inline comments with suggestions (each tagged with a priority badge)
|
||||
|
||||
## Checking review status
|
||||
|
||||
After pushing, check whether Codex has reviewed the latest commit:
|
||||
|
||||
```bash
|
||||
# Get the latest commit SHA on the branch
|
||||
LATEST=$(git rev-parse HEAD)
|
||||
|
||||
# Check if Codex has reviewed that specific commit
|
||||
gh api repos/PrefectHQ/fastmcp/pulls/{PR_NUMBER}/reviews \
|
||||
| jq "[.[] | select(.user.login == \"chatgpt-codex-connector[bot]\" and .commit_id == \"$LATEST\")] | length"
|
||||
```
|
||||
|
||||
If the count is 0, Codex hasn't reviewed the latest push yet. Wait and check again.
|
||||
|
||||
If the count is > 0, check for inline comments on the latest review:
|
||||
|
||||
```bash
|
||||
# Get the review body to check for thumbs-up
|
||||
gh api repos/PrefectHQ/fastmcp/pulls/{PR_NUMBER}/reviews \
|
||||
| jq '[.[] | select(.user.login == "chatgpt-codex-connector[bot]") | {state, body: .body[:300], commit_id: .commit_id}] | last'
|
||||
```
|
||||
|
||||
A clean review from Codex looks like a review body that contains a thumbs-up reaction or says "no suggestions." If the body contains "Here are some automated review suggestions," there are inline comments to evaluate.
|
||||
|
||||
## Evaluating Codex comments
|
||||
|
||||
Fetch all inline comments from Codex:
|
||||
|
||||
```bash
|
||||
gh api repos/PrefectHQ/fastmcp/pulls/{PR_NUMBER}/comments \
|
||||
| jq '[.[] | select(.user.login == "chatgpt-codex-connector[bot]") | {body, path, line, created_at}]'
|
||||
```
|
||||
|
||||
Codex comments include priority badges:
|
||||
- `P0` (red) — Critical issue, likely a real bug
|
||||
- `P1` (orange) — Important, worth fixing
|
||||
- `P2` (yellow) — Moderate, evaluate on merit
|
||||
|
||||
**How to evaluate Codex comments:**
|
||||
|
||||
1. **Treat Codex as a competent but sometimes overzealous reviewer.** It catches real bugs (cache eviction ordering, silent data loss, missing validation) but also suggests scope expansions and hypothetical improvements.
|
||||
|
||||
2. **Fix real bugs** — issues in code you actually changed where behavior is incorrect or data is silently lost.
|
||||
|
||||
3. **Dismiss scope expansion** — if a comment points out a pre-existing limitation unrelated to your diff, note it as a potential follow-up but don't block the PR.
|
||||
|
||||
4. **Dismiss speculative concerns** — if a comment describes a scenario that requires very specific conditions and the existing behavior is acceptable, dismiss it.
|
||||
|
||||
5. **When fixing, be proactive** — if Codex found one instance of a pattern bug (e.g., missing role validation in one handler), check all similar code paths before pushing. Codex will find the next instance on the next review cycle, so get ahead of it.
|
||||
|
||||
## Responding to every comment
|
||||
|
||||
**Every Codex comment must get a visible response** — either a fix or a reply explaining why it was dismissed. The maintainer can't see your reasoning otherwise.
|
||||
|
||||
- **If fixing**: The fix itself is the response. No reply needed unless the fix is non-obvious.
|
||||
- **If dismissing**: Reply to the comment thread with a brief explanation of why. Keep it to 1-2 sentences. Examples:
|
||||
- "This is pre-existing behavior unrelated to this diff — the scope lookup fallback existed before caching was added. Worth a follow-up issue but not blocking this PR."
|
||||
- "The AsyncExitStack handles cleanup when the session exits, so the subprocess isn't leaked — just kept alive slightly longer than necessary in this edge case."
|
||||
- "Gemini supports a much wider range of media types than OpenAI/Anthropic, so a restrictive allowlist would be inaccurate here."
|
||||
|
||||
Use `gh api` to reply (note: use `in_reply_to`, not a `/replies` sub-path):
|
||||
|
||||
```bash
|
||||
# Reply to a specific review comment
|
||||
gh api repos/PrefectHQ/fastmcp/pulls/{PR_NUMBER}/comments \
|
||||
-f body="Your reply here" \
|
||||
-F in_reply_to={COMMENT_ID}
|
||||
```
|
||||
|
||||
## The fix-push-review cycle
|
||||
|
||||
After evaluating comments:
|
||||
|
||||
1. Fix all real issues in one batch
|
||||
2. Reply to all dismissed comments with reasoning
|
||||
3. Think about what patterns Codex might flag next — check similar code paths proactively
|
||||
4. Commit and push
|
||||
5. Check that Codex reviews the new commit
|
||||
6. Repeat until Codex gives a clean review (thumbs-up) or only has dismissible comments
|
||||
|
||||
## Responding to stale comments
|
||||
|
||||
Codex sometimes re-posts old comments that reference code you've already fixed (they appear on the old commit's diff). These are stale — verify the fix is in the latest commit and reply noting the fix is already in place.
|
||||
|
||||
## Labels — never apply or invent them
|
||||
|
||||
**Do not apply labels to PRs or issues programmatically, and never create new ones.** Issues and PRs in this repo are auto-labeled by a bot based on title, body, and code changes — there's no fixed canonical list to match against, and GitHub's "add labels" API auto-creates any label name that doesn't already exist, so a typo or guessed name silently pollutes the repo's label list with a stray, uncolored duplicate. There is no MCP tool to delete a label, so a mistaken creation can only be cleaned up by hand in repo settings.
|
||||
|
||||
Don't call out a "suggested" or "appropriate" label in the PR body either — the bot doesn't read it, and it just adds noise.
|
||||
|
||||
## When a PR is ready
|
||||
|
||||
A PR is ready for human review when:
|
||||
- All Codex comments are either fixed or replied to with dismissal reasoning
|
||||
- CI checks pass
|
||||
- The diff is clean and focused on the stated purpose
|
||||
3
.coderabbit.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
reviews:
|
||||
path_filters:
|
||||
- "!docs/python-sdk/**"
|
||||
27
.github/ISSUE_TEMPLATE/bug.yml
vendored
|
|
@ -3,31 +3,30 @@ description: Report a bug or unexpected behavior in FastMCP
|
|||
labels: [bug, pending]
|
||||
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Thanks for contributing to FastMCP! 🙏
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for reporting a bug!
|
||||
|
||||
A good bug report is one of the most valuable contributions you can make — see [CONTRIBUTING.md](../../CONTRIBUTING.md). If the fix is straightforward, a PR is also welcome.
|
||||
|
||||
### Before you submit
|
||||
|
||||
To help us help you, please:
|
||||
|
||||
- 🔄 **Make sure you're testing on the latest version of FastMCP** - many issues are already fixed in newer versions
|
||||
- 🔍 **Check if someone else has already reported this issue** or if it's been fixed on the main branch
|
||||
- 📋 **You MUST include a copy/pasteable and properly formatted MRE** (minimal reproducible example) below or your issue may be closed without response
|
||||
|
||||
Thanks for helping to make FastMCP better! 🚀
|
||||
- Make sure you're testing on the **latest version** of FastMCP — many issues are already fixed in newer releases
|
||||
- Check if someone else has **already reported this** or if it's been fixed on the main branch
|
||||
- You **must** include a copy/pasteable, properly formatted MRE (minimal reproducible example) or your issue may be closed without response
|
||||
- **The ideal issue is a clear problem description and an MRE — that's it.** If you've done genuine investigation and have a non-obvious insight into the root cause, include it. But please don't speculate or ask an LLM to generate a diagnosis. We have LLMs too, and an incorrect analysis is harder to work with than none at all.
|
||||
- **Keep it short.** A clear description plus a concise MRE is ideal — aim to fit in a single screen. Issues that include unsolicited root cause analysis, proposed fixes, or multi-section diagnostic writeups will be labeled `too-long` and not triaged until condensed.
|
||||
- **Using an LLM?** Great — but it must follow these guidelines. Generic LLM output that ignores our contributing conventions will be closed. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
label: What happened?
|
||||
description: |
|
||||
Please explain what you're experiencing and what you would expect to happen instead.
|
||||
Describe the bug in a few sentences. What did you do, what happened, and what did you expect instead?
|
||||
|
||||
Provide as much detail as possible to help us understand and solve your problem quickly.
|
||||
Do NOT include root cause analysis, proposed fixes, or diagnostic writeups — just describe the problem.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
|
|
|||
25
.github/ISSUE_TEMPLATE/enhancement.yml
vendored
|
|
@ -3,32 +3,27 @@ description: Suggest an idea or improvement for FastMCP
|
|||
labels: [enhancement, pending]
|
||||
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Thanks for contributing to FastMCP! 🙏
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for suggesting an improvement to FastMCP!
|
||||
|
||||
Enhancement issues are the **primary way** features and improvements get into FastMCP. Maintainers use well-written issues to implement changes that fit the codebase's patterns and ship quickly. A clear issue here is more impactful than a PR — see [CONTRIBUTING.md](../../CONTRIBUTING.md) for why.
|
||||
|
||||
### Before you submit
|
||||
|
||||
To help us evaluate your enhancement request:
|
||||
|
||||
- 🔍 **Check if this has already been requested** - search existing issues first
|
||||
- 💭 **Think about the broader impact** - how would this affect other users?
|
||||
- 📋 **Consider implementation complexity** - is this a small change or a major feature?
|
||||
|
||||
Thanks for helping to make FastMCP better! 🚀
|
||||
- 🔍 **Check if this has already been requested** — search existing issues first
|
||||
- 🎯 **Describe the problem you're trying to solve**, not the solution you want — we'll figure out the best implementation
|
||||
- ✂️ **Keep it short.** A motivating description and a concrete use case is the ideal request — aim to fit in a single screen. Skip proposed implementations, API designs, or multi-option analyses — maintainers will figure out the approach. Requests that are difficult to parse will be labeled `too-long` and not triaged until condensed.
|
||||
- 🤖 **Using an LLM?** Great — but it must follow these guidelines. Generic LLM output that ignores our contributing conventions will be closed. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Enhancement
|
||||
description: |
|
||||
Please describe the enhancement:
|
||||
What problem or use case does this solve? How does current behavior fall short?
|
||||
|
||||
- What problem or use case would it solve?
|
||||
- How would it improve your workflow or experience with FastMCP?
|
||||
- Are there any alternative solutions you've considered?
|
||||
Focus on the *what* and *why* — the motivating scenario. You don't need to propose an API or implementation.
|
||||
validations:
|
||||
required: true
|
||||
|
|
|
|||
100
.github/actions/run-claude/action.yml
vendored
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
# Composite Action for running Claude Code Action
|
||||
#
|
||||
# Wraps anthropics/claude-code-action with MCP server configuration.
|
||||
# Template based on elastic/ai-github-actions base action.
|
||||
#
|
||||
# Usage:
|
||||
# - uses: ./.github/actions/run-claude
|
||||
# with:
|
||||
# prompt: "Your prompt here"
|
||||
# claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
# github-token: ${{ steps.marvin-token.outputs.token }}
|
||||
# allowed-tools: "Edit,Read,Write,Bash(*),mcp__github__add_issue_comment"
|
||||
#
|
||||
name: "Run Claude"
|
||||
description: "Run Claude Code with MCP servers"
|
||||
author: "FastMCP"
|
||||
|
||||
branding:
|
||||
icon: "cpu"
|
||||
color: "orange"
|
||||
|
||||
inputs:
|
||||
prompt:
|
||||
description: "Prompt to pass to Claude"
|
||||
required: true
|
||||
|
||||
claude-oauth-token:
|
||||
description: "Claude Code OAuth token for authentication"
|
||||
required: true
|
||||
|
||||
github-token:
|
||||
description: "GitHub token for Claude to operate with"
|
||||
required: true
|
||||
|
||||
allowed-tools:
|
||||
description: "Comma-separated list of allowed tools (e.g. Edit,Write,Bash(npm test))"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
extra-allowed-tools:
|
||||
description: "Additional comma-separated tools to append to allowed-tools"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
model:
|
||||
description: "Model to use for Claude"
|
||||
required: false
|
||||
default: "claude-opus-4-8"
|
||||
|
||||
allowed-bots:
|
||||
description: "Allowed bot usernames, or '*' for all bots"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
track-progress:
|
||||
description: "Whether Claude should track progress"
|
||||
required: false
|
||||
default: "true"
|
||||
|
||||
mcp-servers:
|
||||
description: "MCP server configuration JSON"
|
||||
required: false
|
||||
default: '{"mcpServers":{"agents-md-generator":{"type":"http","url":"https://agents-md-generator.fastmcp.app/mcp"},"public-code-search":{"type":"http","url":"https://public-code-search.fastmcp.app/mcp"}}}'
|
||||
|
||||
trigger-phrase:
|
||||
description: "Trigger phrase (for mention workflows)"
|
||||
required: false
|
||||
default: "/marvin"
|
||||
|
||||
outputs:
|
||||
conclusion:
|
||||
description: "The conclusion of the Claude Code run"
|
||||
value: ${{ steps.claude.outputs.conclusion }}
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Clean up stale Claude locks
|
||||
shell: bash
|
||||
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ inputs.github-token }}
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ inputs.github-token }}
|
||||
claude_code_oauth_token: ${{ inputs.claude-oauth-token }}
|
||||
bot_name: "Marvin Context Protocol"
|
||||
trigger_phrase: ${{ inputs.trigger-phrase }}
|
||||
allowed_bots: ${{ inputs.allowed-bots }}
|
||||
track_progress: ${{ inputs.track-progress }}
|
||||
prompt: ${{ inputs.prompt }}
|
||||
claude_args: |
|
||||
${{ (inputs.allowed-tools != '' || inputs.extra-allowed-tools != '') && format('--allowedTools ''{0}{1}''', inputs.allowed-tools, inputs.extra-allowed-tools != '' && format(',{0}', inputs.extra-allowed-tools) || '') || '' }}
|
||||
${{ inputs.mcp-servers != '' && format('--mcp-config ''{0}''', inputs.mcp-servers) || '' }}
|
||||
--model ${{ inputs.model }}
|
||||
settings: |
|
||||
{"model": "${{ inputs.model }}"}
|
||||
66
.github/actions/run-pytest/action.yml
vendored
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
name: "Run Pytest"
|
||||
description: "Run pytest with appropriate flags for the test type and platform"
|
||||
|
||||
inputs:
|
||||
test-type:
|
||||
description: "Type of tests to run: unit, integration, client_process, or conformance"
|
||||
required: false
|
||||
default: "unit"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Run pytest
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ inputs.test-type }}" == "integration" ]; then
|
||||
MARKER="integration"
|
||||
TIMEOUT="30"
|
||||
MAX_PROCS="2"
|
||||
EXTRA_FLAGS=""
|
||||
elif [ "${{ inputs.test-type }}" == "client_process" ]; then
|
||||
MARKER="client_process or subprocess_heavy"
|
||||
TIMEOUT="5"
|
||||
MAX_PROCS="0"
|
||||
EXTRA_FLAGS="-x"
|
||||
elif [ "${{ inputs.test-type }}" == "conformance" ]; then
|
||||
MARKER="conformance"
|
||||
TIMEOUT="120"
|
||||
MAX_PROCS="0"
|
||||
EXTRA_FLAGS="-x"
|
||||
else
|
||||
MARKER="not integration and not client_process and not subprocess_heavy and not conformance"
|
||||
TIMEOUT="5"
|
||||
MAX_PROCS="4"
|
||||
EXTRA_FLAGS=""
|
||||
fi
|
||||
|
||||
# Windows previously ran serially: parallel workers crashed intermittently
|
||||
# when many tests spawned stdio subprocesses (#2715, reverted in #2726).
|
||||
# Most of those tests now run in-memory, but tests that spawn a fresh
|
||||
# interpreter importing all of FastMCP still crash xdist workers on the
|
||||
# 2-core Windows runners. They carry the subprocess_heavy marker and run
|
||||
# in the serial client_process step instead.
|
||||
PARALLEL_FLAGS=""
|
||||
if [ "$MAX_PROCS" != "0" ]; then
|
||||
PARALLEL_FLAGS="--numprocesses auto --maxprocesses $MAX_PROCS --dist worksteal"
|
||||
fi
|
||||
|
||||
# pytest-timeout has no signal-based method on Windows, so it falls back
|
||||
# to the thread method, which dumps stacks and os._exit()s the process.
|
||||
# Under a contended runner that turns a single slow test into a dead
|
||||
# xdist worker, failing whichever unrelated test that worker happened to
|
||||
# be running. Give parallel Windows runs more headroom so ordinary
|
||||
# scheduling jitter does not take a worker down.
|
||||
if [ "$RUNNER_OS" == "Windows" ] && [ "$MAX_PROCS" != "0" ]; then
|
||||
TIMEOUT=$((TIMEOUT * 4))
|
||||
fi
|
||||
|
||||
uv run --no-sync pytest \
|
||||
--inline-snapshot=disable \
|
||||
--timeout=$TIMEOUT \
|
||||
--durations=50 \
|
||||
-m "$MARKER" \
|
||||
$PARALLEL_FLAGS \
|
||||
$EXTRA_FLAGS \
|
||||
tests
|
||||
33
.github/actions/setup-uv/action.yml
vendored
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
name: "Setup UV Environment"
|
||||
description: "Install uv and dependencies (requires checkout first)"
|
||||
|
||||
inputs:
|
||||
python-version:
|
||||
description: "Python version to use"
|
||||
required: false
|
||||
default: "3.10"
|
||||
resolution:
|
||||
description: "Dependency resolution: locked, upgrade, or lowest-direct"
|
||||
required: false
|
||||
default: "locked"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
python-version: ${{ inputs.python-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ inputs.resolution }}" == "locked" ]; then
|
||||
uv sync --locked
|
||||
elif [ "${{ inputs.resolution }}" == "upgrade" ]; then
|
||||
uv sync --upgrade
|
||||
else
|
||||
uv sync --resolution ${{ inputs.resolution }}
|
||||
fi
|
||||
14
.github/dependabot.yml
vendored
|
|
@ -1,14 +0,0 @@
|
|||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
labels:
|
||||
- "dependencies"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
labels:
|
||||
- "dependencies"
|
||||
34
.github/pull_request_template.md
vendored
|
|
@ -1,28 +1,22 @@
|
|||
## Description
|
||||
<!--
|
||||
Please provide a clear and concise description of the changes made in this pull request.
|
||||
|
||||
Using AI to generate code? Please include a note in the description with which AI tool you used.
|
||||
-->
|
||||
<!-- What does this PR do? Link to the issue it addresses. -->
|
||||
|
||||
**Contributors Checklist**
|
||||
<!--
|
||||
NOTE:
|
||||
1. You must create an issue in the repository before making a Pull Request.
|
||||
2. You must not create a Pull Request for an issue that is already assigned to someone else.
|
||||
Closes #
|
||||
|
||||
If you do not follow these steps, your Pull Request will be closed without review.
|
||||
-->
|
||||
## Contribution type
|
||||
|
||||
- [ ] My change closes #(issue number)
|
||||
- [ ] I have followed the repository's development workflow
|
||||
- [ ] I have tested my changes manually and by adding relevant tests
|
||||
- [ ] I have performed all required documentation updates
|
||||
<!-- Check the one that applies. If you're unsure whether your change is welcome, please open an issue first — see CONTRIBUTING.md. -->
|
||||
|
||||
**Review Checklist**
|
||||
<!-- Your Pull Request will not be reviewed if tests are failing, you have not self-reviewed your changes, or you have not checked all of the following: -->
|
||||
- [ ] Bug fix (simple, well-scoped fix for a clearly broken behavior)
|
||||
- [ ] Documentation improvement
|
||||
- [ ] Enhancement (maintainers typically implement enhancements — see [CONTRIBUTING.md](../CONTRIBUTING.md))
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] This PR addresses an existing issue (or fixes a self-evident bug)
|
||||
- [ ] I have read [CONTRIBUTING.md](../CONTRIBUTING.md)
|
||||
- [ ] I have added tests that cover my changes
|
||||
- [ ] I have run `uv run prek run --all-files` and all checks pass
|
||||
- [ ] I have self-reviewed my changes
|
||||
- [ ] My Pull Request is ready for review
|
||||
|
||||
---
|
||||
- [ ] If I used an LLM, it followed the repo's contributing conventions (not generic output)
|
||||
|
|
|
|||
26
.github/release.yml
vendored
|
|
@ -8,12 +8,25 @@ changelog:
|
|||
labels:
|
||||
- feature
|
||||
|
||||
- title: Enhancements 🔧
|
||||
- title: Breaking Changes ⚠️
|
||||
labels:
|
||||
- breaking change
|
||||
exclude:
|
||||
labels:
|
||||
- contrib
|
||||
- security
|
||||
|
||||
- title: Enhancements ✨
|
||||
labels:
|
||||
- enhancement
|
||||
exclude:
|
||||
labels:
|
||||
- breaking change
|
||||
- security
|
||||
|
||||
- title: Security 🔒
|
||||
labels:
|
||||
- security
|
||||
|
||||
- title: Fixes 🐞
|
||||
labels:
|
||||
|
|
@ -21,13 +34,7 @@ changelog:
|
|||
exclude:
|
||||
labels:
|
||||
- contrib
|
||||
|
||||
- title: Breaking Changes 🛫
|
||||
labels:
|
||||
- breaking change
|
||||
exclude:
|
||||
labels:
|
||||
- contrib
|
||||
- security
|
||||
|
||||
- title: Docs 📚
|
||||
labels:
|
||||
|
|
@ -41,6 +48,9 @@ changelog:
|
|||
- title: Dependencies 📦
|
||||
labels:
|
||||
- dependencies
|
||||
exclude:
|
||||
labels:
|
||||
- security
|
||||
|
||||
- title: Other Changes 🦾
|
||||
labels:
|
||||
|
|
|
|||
62
.github/scripts/mention/gh-get-review-threads.sh
vendored
Executable file
|
|
@ -0,0 +1,62 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Get PR review threads with comments via GitHub GraphQL API
|
||||
#
|
||||
# Usage:
|
||||
# gh-get-review-threads.sh [FILTER]
|
||||
#
|
||||
# Arguments:
|
||||
# FILTER - Optional: filter for unresolved threads from specific author
|
||||
#
|
||||
# Environment (set by composite action):
|
||||
# MENTION_REPO - Repository (owner/repo format)
|
||||
# MENTION_PR_NUMBER - Pull request number
|
||||
# GITHUB_TOKEN - GitHub API token
|
||||
#
|
||||
# Output:
|
||||
# JSON array of review threads with nested comments
|
||||
|
||||
# Parse OWNER and REPO from MENTION_REPO
|
||||
REPO_FULL="${MENTION_REPO:?MENTION_REPO environment variable is required}"
|
||||
OWNER="${REPO_FULL%/*}"
|
||||
REPO="${REPO_FULL#*/}"
|
||||
PR_NUMBER="${MENTION_PR_NUMBER:?MENTION_PR_NUMBER environment variable is required}"
|
||||
FILTER="${1:-}"
|
||||
|
||||
gh api graphql -f query='
|
||||
query($owner: String!, $repo: String!, $prNumber: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
pullRequest(number: $prNumber) {
|
||||
reviewThreads(first: 100) {
|
||||
nodes {
|
||||
id
|
||||
isResolved
|
||||
isOutdated
|
||||
path
|
||||
line
|
||||
comments(first: 50) {
|
||||
nodes {
|
||||
id
|
||||
body
|
||||
author { login }
|
||||
createdAt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}' -F owner="$OWNER" \
|
||||
-F repo="$REPO" \
|
||||
-F prNumber="$PR_NUMBER" \
|
||||
--jq '.data.repository.pullRequest.reviewThreads.nodes' | \
|
||||
if [ -n "$FILTER" ]; then
|
||||
jq --arg author "$FILTER" '
|
||||
map(select(
|
||||
.isResolved == false and
|
||||
.comments.nodes | any(.author.login == $author)
|
||||
))'
|
||||
else
|
||||
cat
|
||||
fi
|
||||
61
.github/scripts/mention/gh-resolve-review-thread.sh
vendored
Executable file
|
|
@ -0,0 +1,61 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Resolve a GitHub PR review thread, optionally posting a comment first
|
||||
#
|
||||
# Usage:
|
||||
# gh-resolve-review-thread.sh THREAD_ID [COMMENT]
|
||||
#
|
||||
# Arguments:
|
||||
# THREAD_ID - The GraphQL node ID of the review thread to resolve
|
||||
# COMMENT - Optional: Comment body to post before resolving
|
||||
#
|
||||
# Environment (set by composite action):
|
||||
# MENTION_REPO - Repository (owner/repo format)
|
||||
# MENTION_PR_NUMBER - Pull request number
|
||||
# GITHUB_TOKEN - GitHub API token
|
||||
#
|
||||
# Behavior:
|
||||
# 1. If COMMENT is provided, posts it as a reply to the thread
|
||||
# 2. Resolves the thread
|
||||
|
||||
# Validate required environment variables
|
||||
: "${MENTION_REPO:?MENTION_REPO environment variable is required}"
|
||||
: "${MENTION_PR_NUMBER:?MENTION_PR_NUMBER environment variable is required}"
|
||||
THREAD_ID="${1:?Thread ID required}"
|
||||
COMMENT="${2:-}"
|
||||
|
||||
# Step 1: Post comment if provided
|
||||
if [ -n "$COMMENT" ]; then
|
||||
echo "Posting comment to thread..." >&2
|
||||
COMMENT_RESULT=$(gh api graphql -f query='
|
||||
mutation($threadId: ID!, $body: String!) {
|
||||
addPullRequestReviewThreadReply(input: {
|
||||
pullRequestReviewThreadId: $threadId,
|
||||
body: $body
|
||||
}) {
|
||||
comment {
|
||||
id
|
||||
}
|
||||
}
|
||||
}' -f threadId="$THREAD_ID" -f body="$COMMENT")
|
||||
if echo "$COMMENT_RESULT" | jq -e '.errors' > /dev/null 2>&1; then
|
||||
echo "Error posting comment: $COMMENT_RESULT" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Step 2: Resolve the thread
|
||||
echo "Resolving thread..." >&2
|
||||
RESOLVE_RESULT=$(gh api graphql -f query='
|
||||
mutation($threadId: ID!) {
|
||||
resolveReviewThread(input: {threadId: $threadId}) {
|
||||
thread {
|
||||
id
|
||||
isResolved
|
||||
}
|
||||
}
|
||||
}' -f threadId="$THREAD_ID" --jq '.data.resolveReviewThread.thread')
|
||||
|
||||
echo "$RESOLVE_RESULT"
|
||||
echo "✓ Thread resolved" >&2
|
||||
251
.github/scripts/pr-review/pr-comment.sh
vendored
Executable file
|
|
@ -0,0 +1,251 @@
|
|||
#!/bin/bash
|
||||
# pr-comment.sh - Queue a structured inline review comment for the PR review
|
||||
#
|
||||
# Usage:
|
||||
# pr-comment.sh <file> <line> --severity <level> --title <description> --why <reason> [suggestion via stdin]
|
||||
# pr-comment.sh <file> <line> --severity <level> --title <description> --why <reason> --no-suggestion
|
||||
#
|
||||
# Arguments:
|
||||
# file File path (required)
|
||||
# line Line number (required)
|
||||
# --severity Severity level: critical, high, medium, low, nitpick (required)
|
||||
# --title Brief description for comment heading (required)
|
||||
# --why One sentence explaining the risk/impact (required)
|
||||
# --no-suggestion Explicitly skip suggestion (use for architectural issues)
|
||||
#
|
||||
# The suggestion code is read from stdin (use heredoc). If no stdin and no --no-suggestion, errors.
|
||||
#
|
||||
# Examples:
|
||||
# # With suggestion (preferred)
|
||||
# pr-comment.sh src/main.go 42 --severity high --title "Missing error check" --why "Errors are silently ignored" <<'EOF'
|
||||
# if err != nil {
|
||||
# return fmt.Errorf("operation failed: %w", err)
|
||||
# }
|
||||
# EOF
|
||||
#
|
||||
# # Without suggestion (for issues requiring broader changes)
|
||||
# pr-comment.sh src/main.go 42 --severity medium --title "Consider extracting to function" \
|
||||
# --why "This logic is duplicated in 3 places" --no-suggestion
|
||||
#
|
||||
# Environment variables (set by the composite action):
|
||||
# PR_REVIEW_REPO - Repository (owner/repo)
|
||||
# PR_REVIEW_PR_NUMBER - Pull request number
|
||||
# PR_REVIEW_COMMENTS_DIR - Directory to cache comments (default: /tmp/pr-review-comments)
|
||||
|
||||
set -e
|
||||
|
||||
# Configuration from environment
|
||||
REPO="${PR_REVIEW_REPO:?PR_REVIEW_REPO environment variable is required}"
|
||||
PR_NUMBER="${PR_REVIEW_PR_NUMBER:?PR_REVIEW_PR_NUMBER environment variable is required}"
|
||||
COMMENTS_DIR="${PR_REVIEW_COMMENTS_DIR:-/tmp/pr-review-comments}"
|
||||
|
||||
# Severity emoji mapping
|
||||
declare -A SEVERITY_EMOJI=(
|
||||
[critical]="🔴 CRITICAL"
|
||||
[high]="🟠 HIGH"
|
||||
[medium]="🟡 MEDIUM"
|
||||
[low]="⚪ LOW"
|
||||
[nitpick]="💬 NITPICK"
|
||||
)
|
||||
|
||||
# Parse arguments
|
||||
FILE=""
|
||||
LINE=""
|
||||
SEVERITY=""
|
||||
TITLE=""
|
||||
WHY=""
|
||||
NO_SUGGESTION=false
|
||||
|
||||
# First two positional args are file and line
|
||||
if [ $# -lt 2 ]; then
|
||||
echo "Error: file and line are required"
|
||||
echo "Usage: pr-comment.sh <file> <line> --severity <level> --title <desc> --why <reason> [<<'EOF' ... EOF]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
FILE="$1"
|
||||
LINE="$2"
|
||||
shift 2
|
||||
|
||||
# Parse named arguments
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--severity)
|
||||
SEVERITY="$2"
|
||||
shift 2
|
||||
;;
|
||||
--title)
|
||||
TITLE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--why)
|
||||
WHY="$2"
|
||||
shift 2
|
||||
;;
|
||||
--no-suggestion)
|
||||
NO_SUGGESTION=true
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
echo "Error: Unknown argument: $1"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Read suggestion from stdin if available
|
||||
SUGGESTION=""
|
||||
if [ ! -t 0 ]; then
|
||||
SUGGESTION=$(cat)
|
||||
fi
|
||||
|
||||
# Validate required arguments
|
||||
if [ -z "$SEVERITY" ]; then
|
||||
echo "Error: --severity is required (critical, high, medium, low, nitpick)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$TITLE" ]; then
|
||||
echo "Error: --title is required"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$WHY" ]; then
|
||||
echo "Error: --why is required"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate severity level
|
||||
if [ -z "${SEVERITY_EMOJI[$SEVERITY]}" ]; then
|
||||
echo "Error: Invalid severity '$SEVERITY'. Must be one of: critical, high, medium, low, nitpick"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Require either suggestion or explicit --no-suggestion
|
||||
if [ -z "$SUGGESTION" ] && [ "$NO_SUGGESTION" = false ]; then
|
||||
echo "Error: Suggestion required. Provide code via stdin (heredoc) or use --no-suggestion"
|
||||
echo ""
|
||||
echo "Example with suggestion:"
|
||||
echo " pr-comment.sh file.go 42 --severity high --title \"desc\" --why \"reason\" <<'EOF'"
|
||||
echo " fixed code here"
|
||||
echo " EOF"
|
||||
echo ""
|
||||
echo "Example without suggestion:"
|
||||
echo " pr-comment.sh file.go 42 --severity medium --title \"desc\" --why \"reason\" --no-suggestion"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate line is a positive integer (>= 1)
|
||||
if ! [[ "$LINE" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Error: Line number must be a positive integer (>= 1), got: $LINE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get the diff for this file to validate the comment location
|
||||
DIFF_DATA=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" --paginate | jq --arg f "$FILE" '.[] | select(.filename==$f)')
|
||||
|
||||
if [ -z "$DIFF_DATA" ]; then
|
||||
echo "Error: File '${FILE}' not found in PR diff"
|
||||
echo ""
|
||||
echo "Files changed in this PR:"
|
||||
gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" --paginate --jq '.[].filename'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PATCH=$(echo "$DIFF_DATA" | jq -r '.patch // empty')
|
||||
|
||||
if [ -z "$PATCH" ]; then
|
||||
echo "Error: No patch data for file '${FILE}' (file may be binary or too large)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Verify the line exists in the diff
|
||||
LINE_IN_DIFF=$(echo "$PATCH" | awk -v target_line="$LINE" '
|
||||
BEGIN { current_line = 0; found = 0 }
|
||||
/^@@/ {
|
||||
line = $0
|
||||
gsub(/.*\+/, "", line)
|
||||
gsub(/[^0-9].*/, "", line)
|
||||
current_line = line - 1
|
||||
next
|
||||
}
|
||||
{
|
||||
if (substr($0, 1, 1) != "-") {
|
||||
current_line++
|
||||
if (current_line == target_line) {
|
||||
found = 1
|
||||
exit
|
||||
}
|
||||
}
|
||||
}
|
||||
END { if (found) print "1"; else print "0" }
|
||||
')
|
||||
|
||||
if [ "$LINE_IN_DIFF" != "1" ]; then
|
||||
echo "Error: Line ${LINE} not found in the diff for '${FILE}'"
|
||||
echo ""
|
||||
echo "Note: You can only comment on lines that appear in the diff (added, modified, or context lines)"
|
||||
echo ""
|
||||
echo "First 50 lines of diff for this file:"
|
||||
echo "$PATCH" | head -50
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create comments directory if it doesn't exist
|
||||
mkdir -p "${COMMENTS_DIR}"
|
||||
|
||||
# Assemble the comment body
|
||||
SEVERITY_LABEL="${SEVERITY_EMOJI[$SEVERITY]}"
|
||||
|
||||
BODY="**${SEVERITY_LABEL}** ${TITLE}
|
||||
|
||||
Why: ${WHY}"
|
||||
|
||||
# Add suggestion block if provided
|
||||
if [ -n "$SUGGESTION" ]; then
|
||||
BODY="${BODY}
|
||||
|
||||
\`\`\`suggestion
|
||||
${SUGGESTION}
|
||||
\`\`\`"
|
||||
fi
|
||||
|
||||
# Append standard footer
|
||||
FOOTER='
|
||||
|
||||
---
|
||||
Marvin Context Protocol | Type `/marvin` to interact further
|
||||
|
||||
Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.'
|
||||
|
||||
BODY_WITH_FOOTER="${BODY}${FOOTER}"
|
||||
|
||||
# Generate unique comment ID
|
||||
COMMENT_ID="comment-$(date +%s)-$(od -An -N4 -tu4 /dev/urandom | tr -d ' ')"
|
||||
COMMENT_FILE="${COMMENTS_DIR}/${COMMENT_ID}.json"
|
||||
|
||||
# Create the comment JSON object
|
||||
jq -n \
|
||||
--arg path "$FILE" \
|
||||
--argjson line "$LINE" \
|
||||
--arg side "RIGHT" \
|
||||
--arg body "$BODY_WITH_FOOTER" \
|
||||
--arg id "$COMMENT_ID" \
|
||||
'{
|
||||
path: $path,
|
||||
line: $line,
|
||||
side: $side,
|
||||
body: $body,
|
||||
_meta: {
|
||||
id: $id,
|
||||
file: $path,
|
||||
line: $line
|
||||
}
|
||||
}' > "${COMMENT_FILE}"
|
||||
|
||||
echo "✓ Queued review comment for ${FILE}:${LINE}"
|
||||
echo " Severity: ${SEVERITY_LABEL}"
|
||||
echo " Title: ${TITLE}"
|
||||
echo " Comment ID: ${COMMENT_ID}"
|
||||
echo " Comment will be submitted with pr-review.sh"
|
||||
echo " Remove with: pr-remove-comment.sh ${FILE} ${LINE}"
|
||||
128
.github/scripts/pr-review/pr-diff.sh
vendored
Executable file
|
|
@ -0,0 +1,128 @@
|
|||
#!/bin/bash
|
||||
# pr-diff.sh - Show changed files or diff for a specific file
|
||||
#
|
||||
# Usage:
|
||||
# pr-diff.sh - List all changed files (shows full diff if small enough)
|
||||
# pr-diff.sh <file> - Show diff for a specific file with line numbers
|
||||
#
|
||||
# Environment variables (set by the composite action):
|
||||
# PR_REVIEW_REPO - Repository (owner/repo)
|
||||
# PR_REVIEW_PR_NUMBER - Pull request number
|
||||
|
||||
set -e
|
||||
|
||||
# Configuration from environment
|
||||
REPO="${PR_REVIEW_REPO:?PR_REVIEW_REPO environment variable is required}"
|
||||
PR_NUMBER="${PR_REVIEW_PR_NUMBER:?PR_REVIEW_PR_NUMBER environment variable is required}"
|
||||
EXPECTED_HEAD="${PR_REVIEW_HEAD_SHA:-}"
|
||||
|
||||
# Check if HEAD has changed since review started (race condition detection)
|
||||
if [ -n "$EXPECTED_HEAD" ]; then
|
||||
CURRENT_HEAD=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}" --jq '.head.sha')
|
||||
if [ "$CURRENT_HEAD" != "$EXPECTED_HEAD" ]; then
|
||||
echo "⚠️ WARNING: PR head has changed since review started!"
|
||||
echo " Review started at: ${EXPECTED_HEAD:0:7}"
|
||||
echo " Current head: ${CURRENT_HEAD:0:7}"
|
||||
echo " Line numbers below may not match the commit being reviewed."
|
||||
echo ""
|
||||
fi
|
||||
fi
|
||||
|
||||
# Thresholds for "too big" - show file list only if exceeded
|
||||
MAX_FILES=25
|
||||
MAX_TOTAL_LINES=1500
|
||||
|
||||
FILE="$1"
|
||||
|
||||
# Function to add line numbers to a patch
|
||||
# Format: [LINE] +added | [LINE] context | [----] -deleted
|
||||
add_line_numbers() {
|
||||
awk '
|
||||
BEGIN { new_line = 0 }
|
||||
/^@@/ {
|
||||
# Parse hunk header: @@ -old_start,old_count +new_start,new_count @@
|
||||
match($0, /\+([0-9]+)/)
|
||||
new_line = substr($0, RSTART+1, RLENGTH-1) - 1
|
||||
print ""
|
||||
print $0
|
||||
next
|
||||
}
|
||||
/^-/ {
|
||||
# Deleted line - cannot comment on these
|
||||
printf "[----] %s\n", $0
|
||||
next
|
||||
}
|
||||
/^\+/ {
|
||||
# Added line - can comment, show line number
|
||||
new_line++
|
||||
printf "[%4d] %s\n", new_line, $0
|
||||
next
|
||||
}
|
||||
{
|
||||
# Context line (space prefix) - can comment, show line number
|
||||
new_line++
|
||||
printf "[%4d] %s\n", new_line, $0
|
||||
}
|
||||
'
|
||||
}
|
||||
|
||||
if [ -z "$FILE" ]; then
|
||||
# Get file list with stats
|
||||
FILES_DATA=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" --paginate)
|
||||
|
||||
FILE_COUNT=$(echo "$FILES_DATA" | jq 'length')
|
||||
TOTAL_ADDITIONS=$(echo "$FILES_DATA" | jq '[.[].additions] | add // 0')
|
||||
TOTAL_DELETIONS=$(echo "$FILES_DATA" | jq '[.[].deletions] | add // 0')
|
||||
TOTAL_LINES=$((TOTAL_ADDITIONS + TOTAL_DELETIONS))
|
||||
|
||||
echo "PR #${PR_NUMBER} Summary: ${FILE_COUNT} files changed (+${TOTAL_ADDITIONS}/-${TOTAL_DELETIONS})"
|
||||
echo ""
|
||||
|
||||
# Check if diff is too large
|
||||
if [ "$FILE_COUNT" -gt "$MAX_FILES" ] || [ "$TOTAL_LINES" -gt "$MAX_TOTAL_LINES" ]; then
|
||||
echo "⚠️ Large diff detected (>${MAX_FILES} files or >${MAX_TOTAL_LINES} lines changed)"
|
||||
echo " Review files individually using: pr-diff.sh <filename>"
|
||||
echo ""
|
||||
echo "Files changed:"
|
||||
echo "$FILES_DATA" | jq -r '.[] | " \(.filename) (+\(.additions)/-\(.deletions))"'
|
||||
else
|
||||
# Small enough - show all diffs with line numbers
|
||||
echo "Files changed:"
|
||||
echo "$FILES_DATA" | jq -r '.[] | " \(.filename) (+\(.additions)/-\(.deletions))"'
|
||||
echo ""
|
||||
echo "─────────────────────────────────────────────────────────────────────"
|
||||
echo ""
|
||||
|
||||
# Show each file's diff by iterating over indices
|
||||
for i in $(seq 0 $((FILE_COUNT - 1))); do
|
||||
FNAME=$(echo "$FILES_DATA" | jq -r ".[$i].filename")
|
||||
PATCH=$(echo "$FILES_DATA" | jq -r ".[$i].patch // empty")
|
||||
|
||||
if [ -n "$PATCH" ]; then
|
||||
echo "## ${FNAME}"
|
||||
echo "Use: pr-comment.sh ${FNAME} <LINE> --severity <level> --title \"desc\" --why \"reason\" <<'EOF' ... EOF"
|
||||
echo "Format: [LINE] +added | [LINE] context | [----] -deleted (can't comment)"
|
||||
echo "$PATCH" | add_line_numbers
|
||||
echo ""
|
||||
echo "─────────────────────────────────────────────────────────────────────"
|
||||
echo ""
|
||||
fi
|
||||
done
|
||||
fi
|
||||
else
|
||||
# Show specific file diff
|
||||
PATCH=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" --paginate --jq --arg file "$FILE" '.[] | select(.filename==$file) | .patch')
|
||||
|
||||
if [ -z "$PATCH" ]; then
|
||||
echo "Error: File '${FILE}' not found in PR diff"
|
||||
echo ""
|
||||
echo "Files changed in this PR:"
|
||||
gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" --paginate --jq '.[].filename'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "## ${FILE}"
|
||||
echo "Use: pr-comment.sh ${FILE} <LINE> --severity <level> --title \"desc\" --why \"reason\" <<'EOF' ... EOF"
|
||||
echo "Format: [LINE] +added | [LINE] context | [----] -deleted (can't comment)"
|
||||
echo "$PATCH" | add_line_numbers
|
||||
fi
|
||||
190
.github/scripts/pr-review/pr-existing-comments.sh
vendored
Executable file
|
|
@ -0,0 +1,190 @@
|
|||
#!/bin/bash
|
||||
# pr-existing-comments.sh - Fetch existing review threads on a PR
|
||||
#
|
||||
# Usage:
|
||||
# pr-existing-comments.sh - Show all review threads with full details
|
||||
# pr-existing-comments.sh --summary - Show per-file summary only (for large PRs)
|
||||
# pr-existing-comments.sh --unresolved - Show only unresolved threads
|
||||
# pr-existing-comments.sh --file <path> - Show threads for a specific file
|
||||
# pr-existing-comments.sh --full - Show full comment text (no truncation)
|
||||
#
|
||||
# Output: Formatted summary of existing review threads grouped by file,
|
||||
# showing thread status, comments, and whether issues were addressed.
|
||||
#
|
||||
# For large PRs, use --summary first to see the overview, then --file <path>
|
||||
# to get full thread details when reviewing each file.
|
||||
#
|
||||
# Environment variables (set by the composite action):
|
||||
# PR_REVIEW_REPO - Repository (owner/repo)
|
||||
# PR_REVIEW_PR_NUMBER - Pull request number
|
||||
|
||||
set -e
|
||||
|
||||
# Configuration from environment
|
||||
REPO="${PR_REVIEW_REPO:?PR_REVIEW_REPO environment variable is required}"
|
||||
PR_NUMBER="${PR_REVIEW_PR_NUMBER:?PR_REVIEW_PR_NUMBER environment variable is required}"
|
||||
|
||||
OWNER="${REPO%/*}"
|
||||
REPO_NAME="${REPO#*/}"
|
||||
|
||||
# Parse arguments
|
||||
FILTER_UNRESOLVED=false
|
||||
FILTER_FILE=""
|
||||
SUMMARY_ONLY=false
|
||||
FULL_TEXT=false
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--unresolved)
|
||||
FILTER_UNRESOLVED=true
|
||||
shift
|
||||
;;
|
||||
--file)
|
||||
FILTER_FILE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--summary)
|
||||
SUMMARY_ONLY=true
|
||||
shift
|
||||
;;
|
||||
--full)
|
||||
FULL_TEXT=true
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
echo "Usage: pr-existing-comments.sh [--summary] [--unresolved] [--file <path>] [--full]"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Fetch review threads via GraphQL
|
||||
THREADS=$(gh api graphql -f query='
|
||||
query($owner: String!, $repo: String!, $prNumber: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
pullRequest(number: $prNumber) {
|
||||
reviewThreads(first: 100) {
|
||||
nodes {
|
||||
id
|
||||
isResolved
|
||||
isOutdated
|
||||
path
|
||||
line
|
||||
originalLine
|
||||
startLine
|
||||
originalStartLine
|
||||
diffSide
|
||||
comments(first: 50) {
|
||||
nodes {
|
||||
id
|
||||
body
|
||||
author { login }
|
||||
createdAt
|
||||
originalCommit { abbreviatedOid }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}' -F owner="$OWNER" \
|
||||
-F repo="$REPO_NAME" \
|
||||
-F prNumber="$PR_NUMBER" \
|
||||
--jq '.data.repository.pullRequest.reviewThreads.nodes')
|
||||
|
||||
if [ -z "$THREADS" ] || [ "$THREADS" = "null" ]; then
|
||||
echo "No existing review threads found."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Apply filters
|
||||
FILTERED="$THREADS"
|
||||
|
||||
if [ "$FILTER_UNRESOLVED" = true ]; then
|
||||
FILTERED=$(echo "$FILTERED" | jq '[.[] | select(.isResolved == false)]')
|
||||
fi
|
||||
|
||||
if [ -n "$FILTER_FILE" ]; then
|
||||
FILTERED=$(echo "$FILTERED" | jq --arg file "$FILTER_FILE" '[.[] | select(.path == $file)]')
|
||||
fi
|
||||
|
||||
THREAD_COUNT=$(echo "$FILTERED" | jq 'length')
|
||||
|
||||
if [ "$THREAD_COUNT" -eq 0 ]; then
|
||||
if [ "$FILTER_UNRESOLVED" = true ]; then
|
||||
echo "No unresolved review threads found."
|
||||
elif [ -n "$FILTER_FILE" ]; then
|
||||
echo "No review threads found for ${FILTER_FILE}."
|
||||
else
|
||||
echo "No existing review threads found."
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Count resolved vs unresolved
|
||||
RESOLVED_COUNT=$(echo "$FILTERED" | jq '[.[] | select(.isResolved == true)] | length')
|
||||
UNRESOLVED_COUNT=$(echo "$FILTERED" | jq '[.[] | select(.isResolved == false)] | length')
|
||||
OUTDATED_COUNT=$(echo "$FILTERED" | jq '[.[] | select(.isOutdated == true)] | length')
|
||||
|
||||
echo "Existing review threads: ${THREAD_COUNT} total (${UNRESOLVED_COUNT} unresolved, ${RESOLVED_COUNT} resolved, ${OUTDATED_COUNT} outdated)"
|
||||
echo ""
|
||||
|
||||
# Summary mode: show per-file counts only
|
||||
if [ "$SUMMARY_ONLY" = true ]; then
|
||||
echo "Threads by file:"
|
||||
echo "$FILTERED" | jq -r '
|
||||
group_by(.path) | .[] |
|
||||
. as $threads |
|
||||
($threads | length) as $total |
|
||||
([$threads[] | select(.isResolved == false)] | length) as $unresolved |
|
||||
([$threads[] | select(.isResolved == true)] | length) as $resolved |
|
||||
([$threads[] | select(.isOutdated == true)] | length) as $outdated |
|
||||
([$threads[] | select(.comments.nodes | length > 1)] | length) as $has_replies |
|
||||
" " + $threads[0].path +
|
||||
" — " + ($total | tostring) + " threads" +
|
||||
" (" + ($unresolved | tostring) + " unresolved, " + ($resolved | tostring) + " resolved" +
|
||||
(if $outdated > 0 then ", " + ($outdated | tostring) + " outdated" else "" end) +
|
||||
")" +
|
||||
(if $has_replies > 0 then " ⚠️ " + ($has_replies | tostring) + " with replies" else "" end)
|
||||
'
|
||||
echo ""
|
||||
echo "Use: pr-existing-comments.sh --file <path> to see full thread details for a file"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Full detail mode: output threads grouped by file
|
||||
# Show full conversation for threads with replies
|
||||
FIRST_LIMIT=200
|
||||
REPLY_LIMIT=300
|
||||
if [ "$FULL_TEXT" = true ]; then
|
||||
FIRST_LIMIT=999999
|
||||
REPLY_LIMIT=999999
|
||||
fi
|
||||
|
||||
echo "$FILTERED" | jq -r --argjson first_limit "$FIRST_LIMIT" --argjson reply_limit "$REPLY_LIMIT" '
|
||||
group_by(.path) | .[] |
|
||||
"## " + .[0].path + " (" + (length | tostring) + " threads)\n" +
|
||||
([.[] |
|
||||
" " +
|
||||
(if .isResolved then "✅ RESOLVED" elif .isOutdated then "⚠️ OUTDATED" else "🔴 UNRESOLVED" end) +
|
||||
" (line " + (if .line then (.line | tostring) elif .startLine then (.startLine | tostring) elif .originalLine then ("~" + (.originalLine | tostring)) elif .originalStartLine then ("~" + (.originalStartLine | tostring)) else "?" end) + ")" +
|
||||
# Show the commit the comment was originally made on
|
||||
(if .comments.nodes[0].originalCommit.abbreviatedOid then " [" + .comments.nodes[0].originalCommit.abbreviatedOid + "]" else "" end) +
|
||||
# Flag threads with replies — indicates a conversation happened
|
||||
(if (.comments.nodes | length) > 1 then " ← has replies" else "" end) +
|
||||
"\n" +
|
||||
([.comments.nodes | to_entries[] |
|
||||
.value as $comment |
|
||||
.key as $idx |
|
||||
($comment.body | gsub("\n"; " ")) as $flat |
|
||||
if $idx == 0 then
|
||||
" @" + ($comment.author.login // "unknown") + ": " + $flat[0:$first_limit] +
|
||||
(if ($flat | length) > $first_limit then " [truncated]" else "" end)
|
||||
else
|
||||
" ↳ @" + ($comment.author.login // "unknown") + ": " + $flat[0:$reply_limit] +
|
||||
(if ($flat | length) > $reply_limit then " [truncated]" else "" end)
|
||||
end
|
||||
] | join("\n")) +
|
||||
"\n"
|
||||
] | join("\n"))
|
||||
'
|
||||
84
.github/scripts/pr-review/pr-remove-comment.sh
vendored
Executable file
|
|
@ -0,0 +1,84 @@
|
|||
#!/bin/bash
|
||||
# pr-remove-comment.sh - Remove a queued review comment
|
||||
#
|
||||
# Usage:
|
||||
# pr-remove-comment.sh <file> <line-number>
|
||||
# pr-remove-comment.sh <comment-id>
|
||||
#
|
||||
# Examples:
|
||||
# pr-remove-comment.sh src/main.go 42
|
||||
# pr-remove-comment.sh comment-1234567890-1234567890
|
||||
#
|
||||
# This script removes a previously queued comment before it's submitted.
|
||||
# Useful if the agent realizes it made a mistake or wants to update a comment.
|
||||
#
|
||||
# Environment variables (set by the composite action):
|
||||
# PR_REVIEW_COMMENTS_DIR - Directory containing comment files (default: /tmp/pr-review-comments)
|
||||
|
||||
set -e
|
||||
|
||||
COMMENTS_DIR="${PR_REVIEW_COMMENTS_DIR:-/tmp/pr-review-comments}"
|
||||
|
||||
if [ ! -d "${COMMENTS_DIR}" ]; then
|
||||
echo "No comments directory found: ${COMMENTS_DIR}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check if first argument looks like a comment ID
|
||||
if [[ "$1" =~ ^comment- ]]; then
|
||||
COMMENT_ID="$1"
|
||||
COMMENT_FILE="${COMMENTS_DIR}/${COMMENT_ID}.json"
|
||||
|
||||
if [ -f "${COMMENT_FILE}" ]; then
|
||||
FILE=$(jq -r '._meta.file // .path' "${COMMENT_FILE}")
|
||||
LINE=$(jq -r '._meta.line // .line' "${COMMENT_FILE}")
|
||||
rm -f "${COMMENT_FILE}"
|
||||
echo "✓ Removed comment ${COMMENT_ID} for ${FILE}:${LINE}"
|
||||
else
|
||||
echo "Comment not found: ${COMMENT_ID}"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
# Treat as file and line number
|
||||
FILE="$1"
|
||||
LINE="$2"
|
||||
|
||||
if [ -z "$FILE" ] || [ -z "$LINE" ]; then
|
||||
echo "Usage:"
|
||||
echo " pr-remove-comment.sh <file> <line-number>"
|
||||
echo " pr-remove-comment.sh <comment-id>"
|
||||
echo ""
|
||||
echo "Examples:"
|
||||
echo " pr-remove-comment.sh src/main.go 42"
|
||||
echo " pr-remove-comment.sh comment-1234567890-1234567890"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate line is a positive integer (>= 1)
|
||||
if ! [[ "$LINE" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Error: Line number must be a positive integer (>= 1), got: $LINE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Find and remove matching comment files
|
||||
# Use nullglob to handle case where no files match
|
||||
shopt -s nullglob
|
||||
REMOVED=0
|
||||
for COMMENT_FILE in "${COMMENTS_DIR}"/comment-*.json; do
|
||||
|
||||
COMMENT_FILE_PATH=$(jq -r '._meta.file // .path' "${COMMENT_FILE}")
|
||||
COMMENT_LINE=$(jq -r '._meta.line // .line' "${COMMENT_FILE}")
|
||||
|
||||
if [ "$COMMENT_FILE_PATH" = "$FILE" ] && [ "$COMMENT_LINE" = "$LINE" ]; then
|
||||
COMMENT_ID=$(basename "${COMMENT_FILE}" .json)
|
||||
rm -f "${COMMENT_FILE}"
|
||||
echo "✓ Removed comment ${COMMENT_ID} for ${FILE}:${LINE}"
|
||||
REMOVED=$((REMOVED + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$REMOVED" -eq 0 ]; then
|
||||
echo "No comment found for ${FILE}:${LINE}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
143
.github/scripts/pr-review/pr-review.sh
vendored
Executable file
|
|
@ -0,0 +1,143 @@
|
|||
#!/bin/bash
|
||||
# pr-review.sh - Submit a PR review (approve, request changes, or comment)
|
||||
#
|
||||
# Usage: pr-review.sh <APPROVE|REQUEST_CHANGES|COMMENT> [review-body]
|
||||
# Example: pr-review.sh REQUEST_CHANGES "Please fix the issues noted above"
|
||||
#
|
||||
# This script creates and submits a review with any queued inline comments.
|
||||
# Comments are read from individual files in PR_REVIEW_COMMENTS_DIR (created by pr-comment.sh).
|
||||
#
|
||||
# The review body can contain special characters (backticks, dollar signs, etc.)
|
||||
# and will be safely passed to the GitHub API without shell interpretation.
|
||||
#
|
||||
# Environment variables (set by the composite action):
|
||||
# PR_REVIEW_REPO - Repository (owner/repo)
|
||||
# PR_REVIEW_PR_NUMBER - Pull request number
|
||||
# PR_REVIEW_HEAD_SHA - HEAD commit SHA
|
||||
# PR_REVIEW_COMMENTS_DIR - Directory containing queued comment files (default: /tmp/pr-review-comments)
|
||||
|
||||
set -e
|
||||
|
||||
# Configuration from environment
|
||||
REPO="${PR_REVIEW_REPO:?PR_REVIEW_REPO environment variable is required}"
|
||||
PR_NUMBER="${PR_REVIEW_PR_NUMBER:?PR_REVIEW_PR_NUMBER environment variable is required}"
|
||||
HEAD_SHA="${PR_REVIEW_HEAD_SHA:?PR_REVIEW_HEAD_SHA environment variable is required}"
|
||||
COMMENTS_DIR="${PR_REVIEW_COMMENTS_DIR:-/tmp/pr-review-comments}"
|
||||
|
||||
# Arguments
|
||||
EVENT="$1"
|
||||
shift 2>/dev/null || true
|
||||
|
||||
# Read body from remaining arguments
|
||||
# Join all remaining arguments with spaces, preserving the string as-is
|
||||
BODY="$*"
|
||||
|
||||
if [ -z "$EVENT" ]; then
|
||||
echo "Usage: pr-review.sh <APPROVE|REQUEST_CHANGES|COMMENT> [review-body]"
|
||||
echo "Example: pr-review.sh REQUEST_CHANGES 'Please fix the issues noted in the inline comments'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate event type
|
||||
case "$EVENT" in
|
||||
APPROVE|REQUEST_CHANGES|COMMENT)
|
||||
;;
|
||||
*)
|
||||
echo "Error: Invalid event type '${EVENT}'"
|
||||
echo "Must be one of: APPROVE, REQUEST_CHANGES, COMMENT"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# Read queued comments from individual files
|
||||
COMMENTS="[]"
|
||||
COMMENT_COUNT=0
|
||||
|
||||
if [ -d "${COMMENTS_DIR}" ]; then
|
||||
# Collect all comment files and merge into a single JSON array
|
||||
# Remove _meta fields before submitting (they're only for internal use)
|
||||
COMMENT_FILES=("${COMMENTS_DIR}"/comment-*.json)
|
||||
|
||||
if [ -f "${COMMENT_FILES[0]}" ]; then
|
||||
# Use jq to read all comment files, extract the comment data (without _meta), and combine
|
||||
COMMENTS=$(jq -s '[.[] | del(._meta)]' "${COMMENTS_DIR}"/comment-*.json)
|
||||
COMMENT_COUNT=$(echo "$COMMENTS" | jq 'length')
|
||||
if [ "$COMMENT_COUNT" -gt 0 ]; then
|
||||
echo "Found ${COMMENT_COUNT} queued inline comment(s)"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Append standard footer to the review body (if body is provided)
|
||||
FOOTER='
|
||||
|
||||
---
|
||||
Marvin Context Protocol | Type `/marvin` to interact further
|
||||
|
||||
Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.'
|
||||
|
||||
if [ -n "$BODY" ]; then
|
||||
BODY_WITH_FOOTER="${BODY}${FOOTER}"
|
||||
else
|
||||
BODY_WITH_FOOTER=""
|
||||
fi
|
||||
|
||||
# Build the review request JSON
|
||||
# Use jq to safely construct the JSON with all special characters handled
|
||||
REVIEW_JSON=$(jq -n \
|
||||
--arg commit_id "$HEAD_SHA" \
|
||||
--arg event "$EVENT" \
|
||||
--arg body "$BODY_WITH_FOOTER" \
|
||||
--argjson comments "$COMMENTS" \
|
||||
'{
|
||||
commit_id: $commit_id,
|
||||
event: $event,
|
||||
comments: $comments
|
||||
} + (if $body != "" then {body: $body} else {} end)')
|
||||
|
||||
# Check if HEAD has changed since review started (race condition detection)
|
||||
CURRENT_HEAD=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}" --jq '.head.sha')
|
||||
if [ "$CURRENT_HEAD" != "$HEAD_SHA" ]; then
|
||||
echo "⚠️ WARNING: PR head has changed since review started!"
|
||||
echo " Review started at: ${HEAD_SHA:0:7}"
|
||||
echo " Current head: ${CURRENT_HEAD:0:7}"
|
||||
echo ""
|
||||
echo " New commits may have shifted line numbers. Review will be submitted"
|
||||
echo " against the original commit (${HEAD_SHA:0:7}) but comments may be outdated."
|
||||
echo ""
|
||||
fi
|
||||
|
||||
echo "Submitting ${EVENT} review for commit ${HEAD_SHA:0:7}..."
|
||||
|
||||
# Create and submit the review in one API call
|
||||
# Use a temp file to safely pass the JSON body
|
||||
TEMP_JSON=$(mktemp)
|
||||
trap "rm -f ${TEMP_JSON}" EXIT
|
||||
echo "$REVIEW_JSON" > "${TEMP_JSON}"
|
||||
|
||||
RESPONSE=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}/reviews" \
|
||||
-X POST \
|
||||
--input "${TEMP_JSON}" 2>&1) || {
|
||||
echo "Error submitting review:"
|
||||
echo "$RESPONSE"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Clean up the comments directory after successful submission
|
||||
if [ -d "${COMMENTS_DIR}" ] && [ "$COMMENT_COUNT" -gt 0 ]; then
|
||||
rm -f "${COMMENTS_DIR}"/comment-*.json
|
||||
# Remove directory if empty
|
||||
rmdir "${COMMENTS_DIR}" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
REVIEW_URL=$(echo "$RESPONSE" | jq -r '.html_url // empty')
|
||||
REVIEW_STATE=$(echo "$RESPONSE" | jq -r '.state // empty')
|
||||
|
||||
if [ -n "$REVIEW_URL" ]; then
|
||||
echo "✓ Review submitted (${REVIEW_STATE}): ${REVIEW_URL}"
|
||||
if [ "$COMMENT_COUNT" -gt 0 ]; then
|
||||
echo " Included ${COMMENT_COUNT} inline comment(s)"
|
||||
fi
|
||||
else
|
||||
echo "✓ Review submitted successfully"
|
||||
fi
|
||||
80
.github/scripts/triage-label.sh
vendored
Executable file
|
|
@ -0,0 +1,80 @@
|
|||
#!/usr/bin/env bash
|
||||
# Locked-down label helper for the Marvin triage workflow.
|
||||
#
|
||||
# Marvin runs on untrusted issue/PR bodies from non-write users, so it must
|
||||
# NOT be handed raw `gh api` (that would expose every endpoint the app token
|
||||
# can reach). This helper is the ONLY GitHub write it is allowed to perform:
|
||||
# it adds or removes repository labels on the one issue/PR being triaged.
|
||||
#
|
||||
# The target repo and number come from the environment set by the workflow —
|
||||
# never from the model — and the operation is fixed to the additive labels
|
||||
# endpoint (POST/DELETE /repos/{repo}/issues/{n}/labels), which works for both
|
||||
# issues and PRs and cannot clobber labels applied by other workflows.
|
||||
set -euo pipefail
|
||||
|
||||
repo="${TRIAGE_REPO:?TRIAGE_REPO not set}"
|
||||
number="${TRIAGE_NUMBER:?TRIAGE_NUMBER not set}"
|
||||
|
||||
if [[ ! "$number" =~ ^[0-9]+$ ]]; then
|
||||
echo "TRIAGE_NUMBER must be numeric, got: $number" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
op="${1:-}"
|
||||
shift || true
|
||||
case "$op" in
|
||||
add) method=POST ;;
|
||||
remove) method=DELETE ;;
|
||||
*)
|
||||
echo "usage: triage-label.sh <add|remove> <label>..." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ "$#" -eq 0 ]]; then
|
||||
echo "no labels given" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Reject anything that isn't a plausible label name. Notably blocks '/' so a
|
||||
# crafted value can't turn the DELETE path into a different endpoint.
|
||||
label_re="^[A-Za-z0-9 ._'-]+$"
|
||||
for label in "$@"; do
|
||||
if [[ ! "$label" =~ $label_re ]]; then
|
||||
echo "refusing suspicious label name: $label" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# Never let triage add or remove the Require Issue Link control labels. Those
|
||||
# govern PR enforcement (bypass-issue-check / trusted-contributor are sticky
|
||||
# exemptions, "prs welcome" waives the assignment requirement) and reopening
|
||||
# (missing-issue-link is how closed PRs are found), so a prompt-injected triage
|
||||
# run must not be able to grant an exemption or break recovery. Enforced here —
|
||||
# in code — not merely in the prompt.
|
||||
#
|
||||
# Exact match against array entries, not a substring scan of a joined string:
|
||||
# label names may contain spaces ("prs welcome"), which in a space-delimited
|
||||
# string would also make bare "prs" and "welcome" match.
|
||||
protected=(missing-issue-link bypass-issue-check trusted-contributor "prs welcome")
|
||||
for label in "$@"; do
|
||||
lower="${label,,}"
|
||||
for p in "${protected[@]}"; do
|
||||
if [[ "$lower" == "$p" ]]; then
|
||||
echo "refusing to touch protected control label: $label" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "$method" == POST ]]; then
|
||||
args=()
|
||||
for label in "$@"; do
|
||||
args+=(-f "labels[]=$label")
|
||||
done
|
||||
gh api --method POST "/repos/${repo}/issues/${number}/labels" "${args[@]}"
|
||||
else
|
||||
for label in "$@"; do
|
||||
gh api --method DELETE "/repos/${repo}/issues/${number}/labels/${label}"
|
||||
done
|
||||
fi
|
||||
4
.github/workflows/auto-close-duplicates.yml
vendored
|
|
@ -16,11 +16,11 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
|
|
|||
4
.github/workflows/auto-close-needs-mre.yml
vendored
|
|
@ -16,11 +16,11 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
|
|
|||
176
.github/workflows/martian-issue-triage.yml
vendored
|
|
@ -1,176 +0,0 @@
|
|||
name: Martian Issue Triage
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, labeled]
|
||||
|
||||
jobs:
|
||||
martian-issue-triage:
|
||||
if: |
|
||||
(github.event.action == 'opened' && github.actor == 'strawgate') ||
|
||||
(github.event.action == 'labeled' && github.event.label.name == 'triage-martian')
|
||||
|
||||
concurrency:
|
||||
group: triage-martian-${{ github.event.issue.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
repository: ${{ github.repository }}
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
# Install UV package manager
|
||||
- name: Install UV
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Set triage prompt
|
||||
id: triage-prompt
|
||||
run: |
|
||||
cat >> $GITHUB_OUTPUT << 'EOF'
|
||||
PROMPT<<PROMPT_END
|
||||
You're an issue triage assistant for FastMCP, a Python framework for building Model Context Protocol servers and clients.
|
||||
|
||||
# IMPORTANT RULES
|
||||
1. You will not make branches or pull requests. Your ONLY action will be investigating the issue, locating related issues,
|
||||
pull requests, and files in the repository and reporting your findings.
|
||||
2. You will identify the issue type (bug/feature/question) up front and tailor the Recommendation (e.g., for questions: answer directly + links; for bugs: point to failing tests/lines).
|
||||
3. You will avoid speculation and only assert facts that are deeply rooted (traceable) to the codebase, language/framework conventions, related issues, related pull requests, etc.
|
||||
4. The main branch of the repository has been cloned locally, but changes will not be accepted and you are not allowed to make pull requests or other changes. You can search the local repository for relevant code. You will use the available MCP Server tools identify related issues and pull requests (search_issues and search_pull_requests) and you can use search_code to look at the code in relevant dependent packages. For example, you can use search_code to look at the underlying SDK `https://github.com/modelcontextprotocol/python-sdk` to see how it implements a certain class or function relevant to the issue at hand.
|
||||
|
||||
# Getting Started
|
||||
1. Call the generate_agents_md tool to get a high-level summary of the project you're working in
|
||||
2. Get the issue ${{ github.event.issue.number }} in the GitHub repository: ${{ github.repository }}.
|
||||
3. Use the search_issues and search_pull_requests tools to scour the repository for actually related issues and pull requests
|
||||
4. Call the search_code, get_files, etc. tools to search the repository to identify the related classes, methods, docs, tests, etc that are relevant to the issue.
|
||||
|
||||
# Providing a Great Response
|
||||
Your number one priority is to provide a great response to the issue. A great response is a response that is clear, concise, accurate, and actionable. You will avoid long paragraphs, flowery language, and overly verbose responses. Your readers have limited time and attention, so you will be concise and to the point.
|
||||
|
||||
In priority order your goal is to:
|
||||
1. Provide context about the request or issue (related issues, pull requests, files, etc.)
|
||||
2. Layout a single high-quality and actionable recommendation for how to address the issue based on your knowledge of the project, codebase, and issue
|
||||
3. Provide an high quality and detailed plan that a junior developer could follow to implement the recommendation
|
||||
|
||||
Populate the following sections in your response:
|
||||
Recommendation (or “No recommendation” with reason)
|
||||
Findings
|
||||
Detailed Action Plan
|
||||
Related Items
|
||||
Related Files
|
||||
Related Webpages
|
||||
|
||||
You may not be able to do all of these things, sometimes you may find that all you can do is provide in-depth context of the issue and related items. That's perfectly acceptable and expected. Your performance is judged by how accurate your findings are, do the investigation required to have high confidence in your findings and recommendations. "I don't know" or "I'm unable to recommend a course of action" is better than a bad or wrong answer.
|
||||
|
||||
When formulating your response, you will never "bury the lede", you will always provide a clear and concise tl;dr as the first thing in your response. As your response grows in length you can organize the more detailed parts of your response collapsible sections using <details> and <summary> tags. You shouldn't put everything in collapsible sections, especially if the response is short. Use your discretion to determine when to use collapsible sections to avoid overwhelming the reader with too much detail -- think of them like an appendix that can be expanded if the reader is interested.
|
||||
|
||||
# Example output for "Recommendation" part of the response
|
||||
PR #654 already implements the requested feature but is incomplete. The Pull Request is not in a mergeable state yet, the remaining work should be completed: 1) update the Calculator.divide method to utilize the new DivisionByZeroError or the safe_divide function, and 2) update the tests to ensure that the Calculator.divide method raises the new DivisionByZeroError when the divisor is 0.
|
||||
|
||||
<details>
|
||||
<summary>Findings</summary>
|
||||
...details from the code analysis that are relevant to the issue and the recommendation...
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Detailed Action Plan</summary>
|
||||
...a detailed plan that a junior developer could follow to implement the recommendation...
|
||||
</details>
|
||||
|
||||
# Example Output for "Related Items" part of the response
|
||||
|
||||
<details>
|
||||
<summary>Related Issues and Pull Requests</summary>
|
||||
|
||||
| Repository | Issue or PR | Relevance |
|
||||
| --- | --- | --- |
|
||||
| jlowin/fastmcp | [Add matrix operations support](https://github.com/jlowin/fastmcp/pull/680) | This pull request directly addresses the feature request for adding matrix operations to the calculator. |
|
||||
| jlowin/fastmcp | [Add matrix operations support](https://github.com/jlowin/fastmcp/issues/681) | This issue directly addresses the feature request for adding matrix operations to the calculator. |
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Related Files</summary>
|
||||
|
||||
| Repository | File | Relevance | Sections |
|
||||
| --- | --- | --- | --- |
|
||||
| modelcontextprotocol/python-sdk | [test_calculator.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/test_calculator.py) | This file contains the test cases for the Calculator class, including a test that specifically asserts a ValueError is raised for division by zero, confirming the current intended behavior. | [25-27](https://github.com/modelcontextprotocol/python-sdk/blob/main/test_calculator.py#L25-L27) |
|
||||
| modelcontextprotocol/python-sdk | [calculator.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/calculator.py) | This file contains the implementation of the Calculator class, specifically the `divide` method which raises the ValueError when dividing by zero, matching the bug report. | [29-32](https://github.com/modelcontextprotocol/python-sdk/blob/main/calculator.py#L29-L32) |
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Related Webpages</summary>
|
||||
| Name | URL | Relevance |
|
||||
| --- | --- | --- |
|
||||
| Handling Division by Zero Best Practices | https://my-blog-about-division-by-zero.com/handling+division+by+zero+in+calculator | This webpage provides general best practices for handling division by zero in calculator applications and in Python, which is directly relevant to the issue and potential solutions. |
|
||||
</details>
|
||||
|
||||
PROMPT_END
|
||||
EOF
|
||||
|
||||
- name: Setup GitHub MCP Server
|
||||
run: |
|
||||
mkdir -p /tmp/mcp-config
|
||||
cat > /tmp/mcp-config/mcp-servers.json << 'EOF'
|
||||
{
|
||||
"mcpServers": {
|
||||
"repository-summary": {
|
||||
"type": "http",
|
||||
"url": "https://agents-md-generator.fastmcp.app/mcp"
|
||||
},
|
||||
"code-search": {
|
||||
"type": "http",
|
||||
"url": "https://public-code-search.fastmcp.app/mcp"
|
||||
},
|
||||
"github-research": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"github-research-mcp"
|
||||
],
|
||||
"env": {
|
||||
"DISABLE_SUMMARIES": "true",
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ steps.marvin-token.outputs.token }}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
- name: Clean up stale Claude locks
|
||||
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
|
||||
|
||||
- name: Run Martian for Issue Triage
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ steps.marvin-token.outputs.token }}
|
||||
bot_name: "Marvin Context Protocol"
|
||||
prompt: ${{ steps.triage-prompt.outputs.PROMPT }}
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY_FOR_CI }}
|
||||
track_progress: true
|
||||
claude_args: |
|
||||
--model claude-sonnet-4-5-20250929
|
||||
--allowedTools mcp__repository-summary,mcp__code-search__search_code,mcp__github-research__get_repository,mcp__github-research__get_issue,mcp__github-research__get_pull_request,mcp__github-research__search_issues,mcp__github-research__search_pull_requests,mcp__github-research__get_files
|
||||
--mcp-config /tmp/mcp-config/mcp-servers.json
|
||||
settings: |
|
||||
{
|
||||
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}"
|
||||
}
|
||||
148
.github/workflows/marvin-comment-on-issue.yml
vendored
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
# Respond to /marvin mentions in issue comments (elastic mention-in-issue style)
|
||||
# Calls run-claude directly
|
||||
|
||||
name: Comment on Issue
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
comment:
|
||||
if: |
|
||||
!github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '/marvin') &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Install UV
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --python 3.12
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: React to comment with eyes
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.marvin-token.outputs.token }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/issues/comments/${{ github.event.comment.id }}/reactions" -f content=eyes 2>/dev/null || true
|
||||
|
||||
- name: Run Claude for Issue Comment
|
||||
uses: ./.github/actions/run-claude
|
||||
env:
|
||||
COMMENT_BODY: ${{ github.event.comment.body }}
|
||||
ISSUE_TITLE: ${{ github.event.issue.title }}
|
||||
with:
|
||||
claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
github-token: ${{ steps.marvin-token.outputs.token }}
|
||||
trigger-phrase: "/marvin"
|
||||
allowed-bots: "*"
|
||||
allowed-tools: "Edit,MultiEdit,Glob,Grep,LS,Read,Write,WebSearch,WebFetch,mcp__github_comment__update_claude_comment,mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,Bash(*),mcp__agents-md-generator__generate_agents_md,mcp__public-code-search__search_code"
|
||||
prompt: |
|
||||
<context>
|
||||
Repository: ${{ github.repository }}
|
||||
Issue Number: #${{ github.event.issue.number }}
|
||||
Issue Title: ${{ env.ISSUE_TITLE }}
|
||||
Issue Author: ${{ github.event.issue.user.login }}
|
||||
Comment Author: ${{ github.event.comment.user.login }}
|
||||
</context>
|
||||
|
||||
<user_request>
|
||||
${{ env.COMMENT_BODY }}
|
||||
</user_request>
|
||||
|
||||
<task>
|
||||
You have been mentioned in a GitHub issue comment. Understand the request, gather context, complete the task, and respond with results.
|
||||
</task>
|
||||
|
||||
<constraints>
|
||||
You CAN: Read/analyze code, modify files, write code, run tests, execute commands, commit code, push changes, create branches, create pull requests
|
||||
</constraints>
|
||||
|
||||
<allowed_tools>
|
||||
You have access to the following tools (comma-separated list):
|
||||
|
||||
Edit,MultiEdit,Glob,Grep,LS,Read,Write,WebSearch,WebFetch,mcp__github_comment__update_claude_comment,mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,Bash(*),mcp__agents-md-generator__generate_agents_md,mcp__public-code-search__search_code
|
||||
|
||||
You can only use tools that are explicitly listed above. For Bash commands, the pattern `Bash(command:*)` means you can run that command with any arguments. If a command is not listed, it is not available.
|
||||
</allowed_tools>
|
||||
|
||||
<getting_started>
|
||||
Use `mcp__agents-md-generator__generate_agents_md` to get repository context before responding.
|
||||
</getting_started>
|
||||
|
||||
<investigation_approach>
|
||||
Be thorough in your investigations:
|
||||
- Understand the full context of the repository
|
||||
- Review related code, issues, and PRs
|
||||
- Consider edge cases and implications
|
||||
- Gather all relevant information before responding
|
||||
|
||||
Available tools:
|
||||
- `mcp__public-code-search__search_code`: Search code in OTHER repositories (use `Grep`/`Read` for this repo)
|
||||
- `WebSearch`: Search the web for documentation, best practices, or solutions
|
||||
- `WebFetch`: Fetch and read content from URLs
|
||||
</investigation_approach>
|
||||
|
||||
<common_tasks>
|
||||
- Answer questions about the codebase
|
||||
- Help debug reported problems
|
||||
- Suggest solutions or workarounds
|
||||
- Provide code examples
|
||||
- Help clarify requirements
|
||||
- Link to relevant documentation or code
|
||||
- Create branches, commit changes, and open PRs when asked
|
||||
</common_tasks>
|
||||
|
||||
<response_guidelines>
|
||||
- Lead with a tl;dr — the bottom line in 1-3 sentences, always visible. The reader should be able to act without expanding anything.
|
||||
- Push supporting detail (code analysis, verification output, related items) into collapsible `<details>` blocks. These are appendices, not the main message.
|
||||
- Short responses (a few sentences) don't need collapsible sections at all.
|
||||
- Be concise and actionable.
|
||||
- If the request is unclear, ask clarifying questions.
|
||||
- Report findings and recommendations — not your process. Do not include task checklists or "steps I took" narration.
|
||||
- Every claim needs evidence: cite file paths, line numbers, or command output. Never say "the code does X" without pointing to where.
|
||||
- If you're uncertain, say so. "I couldn't confirm this" is better than a speculative answer.
|
||||
</response_guidelines>
|
||||
|
||||
<github_safety>
|
||||
- Do not write `fixes #N`, `closes #N`, or `resolves #N` in comments — these can accidentally close issues.
|
||||
- When referencing issues, use plain `#N` or link syntax without action keywords.
|
||||
</github_safety>
|
||||
|
||||
<response_footer>
|
||||
Always end your comment with a new line, three dashes, and the footer message:
|
||||
<exact_content>
|
||||
|
||||
---
|
||||
Marvin Context Protocol | Type `/marvin` to interact further
|
||||
|
||||
Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.
|
||||
</exact_content>
|
||||
</response_footer>
|
||||
|
||||
<github_formatting>
|
||||
When writing GitHub comments, wrap branch names, tags, or other @-references in backticks (e.g., `@main`, `@v1.0`) to avoid accidentally pinging users. Do not add backticks around terms that are already inside backticks or code blocks.
|
||||
</github_formatting>
|
||||
307
.github/workflows/marvin-comment-on-pr.yml
vendored
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
# Respond to /marvin mentions in PR review comments and issue comments on PRs
|
||||
# Calls run-claude directly
|
||||
|
||||
name: Comment on PR
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
comment:
|
||||
if: |
|
||||
github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '/marvin') &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout PR head branch
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
# do not set to pull_request.head.ref, claude will pull the branch if needed
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install UV
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --python 3.12
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: React to comment with eyes
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.marvin-token.outputs.token }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/issues/comments/${{ github.event.comment.id }}/reactions" -f content=eyes 2>/dev/null || true
|
||||
|
||||
- name: Get PR HEAD SHA
|
||||
id: pr-info
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.marvin-token.outputs.token }}
|
||||
run: |
|
||||
PR_NUMBER="${{ github.event.issue.number }}"
|
||||
HEAD_SHA=$(gh api "repos/${{ github.repository }}/pulls/${PR_NUMBER}" --jq '.head.sha')
|
||||
echo "head_sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "pr_number=${PR_NUMBER}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Run Claude for PR Comment
|
||||
uses: ./.github/actions/run-claude
|
||||
env:
|
||||
MENTION_REPO: ${{ github.repository }}
|
||||
MENTION_PR_NUMBER: ${{ steps.pr-info.outputs.pr_number }}
|
||||
MENTION_SCRIPTS: ${{ github.workspace }}/.github/scripts/mention
|
||||
PR_REVIEW_REPO: ${{ github.repository }}
|
||||
PR_REVIEW_PR_NUMBER: ${{ steps.pr-info.outputs.pr_number }}
|
||||
PR_REVIEW_HEAD_SHA: ${{ steps.pr-info.outputs.head_sha }}
|
||||
PR_REVIEW_COMMENTS_DIR: /tmp/pr-review-comments
|
||||
PR_REVIEW_HELPERS_DIR: ${{ github.workspace }}/.github/scripts/pr-review
|
||||
COMMENT_BODY: ${{ github.event.comment.body }}
|
||||
PR_TITLE: ${{ github.event.issue.title }}
|
||||
with:
|
||||
claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
github-token: ${{ steps.marvin-token.outputs.token }}
|
||||
trigger-phrase: "/marvin"
|
||||
allowed-bots: "*"
|
||||
allowed-tools: "Edit,MultiEdit,Glob,Grep,LS,Read,Write,WebSearch,WebFetch,mcp__github_comment__update_claude_comment,mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,Bash(*),mcp__agents-md-generator__generate_agents_md,mcp__public-code-search__search_code"
|
||||
prompt: |
|
||||
<context>
|
||||
Repository: ${{ github.repository }}
|
||||
PR Number: #${{ steps.pr-info.outputs.pr_number }}
|
||||
PR Title: ${{ env.PR_TITLE }}
|
||||
PR Author: ${{ github.event.issue.user.login }}
|
||||
Comment Author: ${{ github.event.comment.user.login }}
|
||||
|
||||
**Note**: The PR head branch has already been checked out. The workspace is ready - you can immediately start working on the PR code.
|
||||
</context>
|
||||
|
||||
<user_request>
|
||||
${{ env.COMMENT_BODY }}
|
||||
</user_request>
|
||||
|
||||
<task>
|
||||
You have been mentioned in a Pull Request comment. Understand the request, gather context, complete the task, and respond with results.
|
||||
</task>
|
||||
|
||||
<constraints>
|
||||
You CAN: Read/analyze code, modify files, write code, run tests, execute commands, resolve review threads, commit and push changes to the PR branch, checkout branches
|
||||
You CANNOT: Create new branches unrelated to this PR, create new pull requests
|
||||
|
||||
When making changes, commit and push to the PR's head branch so the author gets the fix directly.
|
||||
</constraints>
|
||||
|
||||
<allowed_tools>
|
||||
You have access to the following tools (comma-separated list):
|
||||
|
||||
Edit,MultiEdit,Glob,Grep,LS,Read,Write,WebSearch,WebFetch,mcp__github_comment__update_claude_comment,mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,Bash(*),mcp__agents-md-generator__generate_agents_md,mcp__public-code-search__search_code
|
||||
|
||||
You can only use tools that are explicitly listed above. For Bash commands, the pattern `Bash(command:*)` means you can run that command with any arguments. If a command is not listed, it is not available.
|
||||
</allowed_tools>
|
||||
|
||||
<getting_started>
|
||||
Use `mcp__agents-md-generator__generate_agents_md` to get repository context before responding.
|
||||
</getting_started>
|
||||
|
||||
<investigation_approach>
|
||||
Be thorough in your investigations:
|
||||
- Understand the full context of the repository
|
||||
- Review related code, issues, and PRs
|
||||
- Consider edge cases and implications
|
||||
- Gather all relevant information before responding
|
||||
|
||||
Available tools:
|
||||
- `mcp__public-code-search__search_code`: Search code in OTHER repositories (use `Grep`/`Read` for this repo)
|
||||
- `WebSearch`: Search the web for documentation, best practices, or solutions
|
||||
- `WebFetch`: Fetch and read content from URLs
|
||||
</investigation_approach>
|
||||
|
||||
<common_tasks>
|
||||
- Address review feedback and fix issues (commit and push to the PR branch)
|
||||
- Answer questions about the changes
|
||||
- Make code changes and push them
|
||||
- Resolve review threads after addressing feedback
|
||||
- Perform PR reviews when asked (use the PR review process below)
|
||||
</common_tasks>
|
||||
|
||||
<pr_review_guidance>
|
||||
When asked to review this PR, follow this structured review process.
|
||||
The `$PR_REVIEW_HELPERS_DIR` environment variable is pre-configured for all scripts below.
|
||||
|
||||
<review_process>
|
||||
Follow these steps in order:
|
||||
|
||||
**Step 1: Gather context**
|
||||
- Use `mcp__agents-md-generator__generate_agents_md` to get repository context
|
||||
(if this fails, explore the repository to understand the codebase — read key files like README, CONTRIBUTING, etc.)
|
||||
- Run `$PR_REVIEW_HELPERS_DIR/pr-existing-comments.sh --summary` to see existing review threads per file
|
||||
- Run `$PR_REVIEW_HELPERS_DIR/pr-diff.sh` to see changed files with line-numbered diffs
|
||||
(for large PRs, this lists files only — review each with `pr-diff.sh <filename>`)
|
||||
|
||||
**Step 2: Review each file**
|
||||
For each changed file:
|
||||
a. If the summary showed existing threads for this file, first run:
|
||||
`$PR_REVIEW_HELPERS_DIR/pr-existing-comments.sh --file <path>`
|
||||
Read the full thread details. The output uses these conventions:
|
||||
- `← has replies` — a conversation happened; read carefully before commenting
|
||||
- `[truncated]` — comment was cut short; add `--full` if you need the complete text to understand the comment
|
||||
- `[abc1234]` — commit the comment was made on; use `git show abc1234` if needed
|
||||
- `~42` — approximate line from an older revision (exact line no longer maps to current diff)
|
||||
b. Review the diff. Use `Read` to see full file contents when you need more context.
|
||||
Identify issues matching review_criteria. Do NOT flag:
|
||||
- Issues in unchanged code (only review the diff)
|
||||
- Style preferences handled by linters
|
||||
- Pre-existing issues not introduced by this PR
|
||||
- Issues already covered by existing threads (see below)
|
||||
|
||||
**Existing thread rules** (check BEFORE leaving any comment):
|
||||
- Resolved with reviewer reply → reviewer's decision is final. Do NOT re-flag.
|
||||
Examples: "It should remain as X", "This is intentional", "No need to do this change"
|
||||
- Resolved without reply → author likely fixed it. Do NOT re-raise unless the fix introduced a new problem.
|
||||
- Unresolved → already flagged. Do NOT re-comment. Mention in review body if you have more to add.
|
||||
- Outdated → code changed. Only re-flag if the issue still applies to the current diff.
|
||||
When in doubt, do not duplicate. Redundant comments erode trust in the review process.
|
||||
|
||||
**Step 3: Leave comments for NEW issues only**
|
||||
For each genuinely new issue not covered by existing threads:
|
||||
```bash
|
||||
$PR_REVIEW_HELPERS_DIR/pr-comment.sh <file> <line> \
|
||||
--severity <critical|high|medium|low|nitpick> \
|
||||
--title "Brief description" \
|
||||
--why "Risk or impact" <<'EOF'
|
||||
corrected code here
|
||||
EOF
|
||||
```
|
||||
Always provide suggestion code. Use `--no-suggestion` only when the fix requires
|
||||
changes across multiple locations. Broader architectural concerns belong in the
|
||||
review body, not inline comments.
|
||||
|
||||
To remove a queued comment: `$PR_REVIEW_HELPERS_DIR/pr-remove-comment.sh <file> <line>`
|
||||
|
||||
**Step 4: Submit the review**
|
||||
```bash
|
||||
$PR_REVIEW_HELPERS_DIR/pr-review.sh <APPROVE|REQUEST_CHANGES|COMMENT> "<review body>"
|
||||
```
|
||||
- REQUEST_CHANGES: Any 🔴 CRITICAL or 🟠 HIGH issues found
|
||||
- COMMENT: 🟡 MEDIUM issues found (but no critical/high)
|
||||
- APPROVE: No issues, or only ⚪ LOW / 💬 NITPICK suggestions
|
||||
|
||||
The review body should include broader architectural concerns not suited for inline comments.
|
||||
Avoid summarizing the PR or offering praise. If approving with no issues, omit the review body.
|
||||
A standard footer is automatically appended to all comments and reviews.
|
||||
</review_process>
|
||||
|
||||
<severity_classification>
|
||||
🔴 CRITICAL - Must fix before merge (security vulnerabilities, data corruption, production-breaking bugs)
|
||||
🟠 HIGH - Should fix before merge (logic errors, missing validation, significant performance issues)
|
||||
🟡 MEDIUM - Address soon, non-blocking (error handling gaps, suboptimal patterns, missing edge cases)
|
||||
⚪ LOW - Author discretion, non-blocking (minor improvements, documentation, style not covered by linters)
|
||||
💬 NITPICK - Truly optional (stylistic preferences, alternative approaches — safe to ignore)
|
||||
</severity_classification>
|
||||
|
||||
<review_criteria>
|
||||
Focus on these categories, in priority order:
|
||||
1. Security vulnerabilities (injection, XSS, auth bypass, secrets exposure)
|
||||
2. Logic bugs that could cause runtime failures or incorrect behavior
|
||||
3. Data integrity issues (race conditions, missing transactions, corruption risk)
|
||||
4. Performance bottlenecks (N+1 queries, memory leaks, blocking operations)
|
||||
5. Error handling gaps (unhandled exceptions, missing validation)
|
||||
6. Breaking changes to public APIs without migration path
|
||||
7. Missing or incorrect test coverage for critical paths
|
||||
</review_criteria>
|
||||
|
||||
<review_calibration>
|
||||
**What NOT to flag** — do not comment on:
|
||||
- Issues in unchanged code (only review the diff)
|
||||
- Input already validated or sanitized at a different layer
|
||||
- Theoretical performance concerns without evidence that N is large
|
||||
- Style or formatting not in the project's linting rules
|
||||
- Missing tests for trivial or generated code
|
||||
- Pre-existing patterns the PR is following consistently
|
||||
|
||||
**Calibration examples**:
|
||||
- Unguarded return from a lookup (e.g., `tool = registry.get(name)` used without None check) → FLAG if the diff introduces the unguarded usage
|
||||
- Same pattern, but the function's return type is `Tool` (not `Optional[Tool]`) → DO NOT FLAG, the type system guarantees non-None
|
||||
- String interpolation in a query with user input → FLAG
|
||||
- String interpolation in a query with a hardcoded enum value → DO NOT FLAG
|
||||
- O(n²) loop → FLAG only if there's evidence N can be large (e.g., user-controlled list). If N is bounded by design (e.g., number of MCP tools), do not flag.
|
||||
|
||||
When in doubt, do not flag. A false positive wastes a reviewer's time and erodes trust in every future review comment.
|
||||
</review_calibration>
|
||||
</pr_review_guidance>
|
||||
|
||||
<review_thread_tools>
|
||||
View unresolved review threads:
|
||||
```bash
|
||||
$MENTION_SCRIPTS/gh-get-review-threads.sh
|
||||
```
|
||||
|
||||
Filter for unresolved threads from a specific reviewer:
|
||||
```bash
|
||||
$MENTION_SCRIPTS/gh-get-review-threads.sh "reviewer-username"
|
||||
```
|
||||
|
||||
Resolve a review thread after addressing feedback:
|
||||
```bash
|
||||
$MENTION_SCRIPTS/gh-resolve-review-thread.sh "THREAD_ID" "Fixed by updating the error handling"
|
||||
```
|
||||
- `THREAD_ID` is the GraphQL node ID from the review threads output (e.g., `PRRT_kwDOABC123`)
|
||||
- The comment is optional - use it to explain what you did
|
||||
|
||||
Note: You can resolve threads after pushing fixes, or resolve them to acknowledge feedback that will be addressed separately.
|
||||
</review_thread_tools>
|
||||
|
||||
<response_guidelines>
|
||||
- Lead with a tl;dr — the bottom line in 1-3 sentences, always visible. The reader should be able to act without expanding anything.
|
||||
- Push supporting detail (code analysis, verification output, related items) into collapsible `<details>` blocks. These are appendices, not the main message.
|
||||
- Short responses (a few sentences) don't need collapsible sections at all.
|
||||
- Be concise and actionable.
|
||||
- If the request is unclear, ask clarifying questions.
|
||||
- When making code changes, commit and push them to the PR branch so the author gets the fix directly.
|
||||
- Every claim needs evidence: cite file paths, line numbers, or command output. Never say "the code does X" without pointing to where.
|
||||
- If you're uncertain, say so. "I couldn't confirm this" is better than a speculative answer.
|
||||
|
||||
**When performing a PR review**: Your substantive feedback belongs in the PR review submission
|
||||
(via pr-review.sh), not in the comment response. The comment should only report:
|
||||
- That you've submitted the review (with the outcome: approved, requested changes, etc.)
|
||||
- Any issues encountered during the review process
|
||||
- Brief status updates
|
||||
|
||||
Do NOT duplicate the review content in your comment - the review itself contains all the details.
|
||||
Keep the comment short, e.g., "I've submitted my review requesting changes. See the review for details."
|
||||
</response_guidelines>
|
||||
|
||||
<github_safety>
|
||||
- Do not write `fixes #N`, `closes #N`, or `resolves #N` in comments — these can accidentally close issues.
|
||||
- When referencing issues, use plain `#N` or link syntax without action keywords.
|
||||
</github_safety>
|
||||
|
||||
<response_footer>
|
||||
Always end your comment with a new line, three dashes, and the footer message:
|
||||
<exact_content>
|
||||
|
||||
---
|
||||
Marvin Context Protocol | Type `/marvin` to interact further
|
||||
|
||||
Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.
|
||||
</exact_content>
|
||||
</response_footer>
|
||||
|
||||
<github_formatting>
|
||||
When writing GitHub comments, wrap branch names, tags, or other @-references in backticks (e.g., `@main`, `@v1.0`) to avoid accidentally pinging users. Do not add backticks around terms that are already inside backticks or code blocks.
|
||||
</github_formatting>
|
||||
77
.github/workflows/marvin-dedupe-issues.yml
vendored
|
|
@ -19,13 +19,20 @@ jobs:
|
|||
issues: write
|
||||
id-token: write
|
||||
|
||||
# TEMPORARY PIN — see the matching note in marvin-label-triage.yml.
|
||||
# Claude Code 2.1.216 broke every Bash call under the action's subprocess
|
||||
# isolation, which this workflow needs for all of its `gh` searching.
|
||||
# https://github.com/anthropics/claude-code/issues/79997
|
||||
env:
|
||||
PINNED_CLAUDE_CODE_VERSION: "2.1.215"
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
|
@ -37,23 +44,38 @@ jobs:
|
|||
PROMPT<<PROMPT_END
|
||||
Find up to 3 likely duplicate issues for GitHub issue ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}.
|
||||
|
||||
Follow these steps precisely:
|
||||
# Core Principle
|
||||
Silence is better than noise. A false positive wastes a human's time and erodes trust in every future report. Most runs should end with no comment — that means the system is working.
|
||||
|
||||
# Steps
|
||||
|
||||
1. Check if the GitHub issue (a) is closed, (b) does not need to be deduped (eg. because it is broad product feedback without a specific solution, or positive feedback), or (c) already has a duplicates comment that you made earlier. If so, do not proceed.
|
||||
|
||||
2. View the GitHub issue and produce a summary of the issue
|
||||
2. View the GitHub issue and produce a summary of the issue.
|
||||
|
||||
3. Then, launch 3 parallel agents using the Task tool to search GitHub for duplicates of this issue, using diverse keywords and search approaches, using the summary from step 2
|
||||
3. Launch 3 parallel agents using the Task tool to search GitHub for duplicates, using diverse keywords and search approaches, using the summary from step 2.
|
||||
|
||||
4. Next, consider the results from steps 2 and 3 and filter out false positives that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed.
|
||||
4. Filter aggressively for false positives. The bar for "duplicate" is high:
|
||||
|
||||
5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates). If there are no duplicates, DO NOT COMMENT. Just exit.
|
||||
A duplicate means the SAME bug or the SAME feature request. Apply this test to every candidate:
|
||||
- **Same fix test**: Could the candidate be closed by the exact same code change? If not, not a duplicate.
|
||||
- **Same symptom test**: Does the user experience the exact same broken behavior? "Both involve middleware" is not duplication. "Both get TypeError on line 42 of proxy.py when calling mount()" is duplication.
|
||||
- **Same request test** (for features): Are they asking for the same specific capability? "Both want better auth" is not duplication. "Both request OAuth PKCE flow for CLI login" is duplication.
|
||||
|
||||
Notes for your agents:
|
||||
Candidates found by only one search agent deserve extra scrutiny — a single keyword match is often a false positive.
|
||||
|
||||
When in doubt, do not flag. A missed duplicate is harmless; a false positive wastes the reporter's time.
|
||||
If there are no duplicates remaining, do not proceed — just exit.
|
||||
|
||||
5. **Quality gate**: Before commenting, re-read each candidate as a skeptical reviewer. For each one, ask: "Would a maintainer who knows this codebase agree this is a duplicate, or would they dismiss it?" If you'd need to hedge with "might" or "possibly," drop it.
|
||||
|
||||
6. Comment back on the issue with your findings (or exit silently if none remain). Do NOT add any labels — labeling is handled by a later workflow step.
|
||||
|
||||
# Notes for your agents
|
||||
- Use `gh` to interact with GitHub, rather than web fetch
|
||||
- Do not use other tools, beyond `gh` and Task (eg. don't use other MCP servers, file edit, etc.)
|
||||
- Make a todo list first
|
||||
- Do not use other tools beyond `gh` and Task (no MCP servers, file edit, etc.)
|
||||
- Never include this issue as a duplicate of itself
|
||||
- When searching, read the FULL body of candidate issues — titles alone are not enough to judge duplication
|
||||
|
||||
For your comment, follow this format precisely (example with 3 suspected duplicates):
|
||||
|
||||
|
|
@ -61,7 +83,7 @@ jobs:
|
|||
Found 3 possible duplicate issues:
|
||||
|
||||
1. #123: Issue title here
|
||||
2. #456: Another issue title
|
||||
2. #456: Another issue title
|
||||
3. #789: Third issue title
|
||||
|
||||
This issue will be automatically closed as a duplicate in 3 days.
|
||||
|
|
@ -76,20 +98,49 @@ jobs:
|
|||
- name: Clean up stale Claude locks
|
||||
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
|
||||
|
||||
- name: Install pinned Claude Code
|
||||
id: pin-claude
|
||||
run: |
|
||||
curl -fsSL https://claude.ai/install.sh | bash -s -- "$PINNED_CLAUDE_CODE_VERSION"
|
||||
echo "path=$HOME/.local/bin/claude" >> "$GITHUB_OUTPUT"
|
||||
"$HOME/.local/bin/claude" --version
|
||||
|
||||
- name: Run Marvin dedupe command
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
path_to_claude_code_executable: ${{ steps.pin-claude.outputs.path }}
|
||||
github_token: ${{ steps.marvin-token.outputs.token }}
|
||||
bot_name: "Marvin Context Protocol"
|
||||
prompt: ${{ steps.dedupe-prompt.outputs.PROMPT }}
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY_FOR_CI }}
|
||||
allowed_non_write_users: "*"
|
||||
claude_args: |
|
||||
--allowedTools Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh api:*),Bash(gh issue comment:*),Task
|
||||
--allowedTools "Bash(gh issue view:*)","Bash(gh search:*)","Bash(gh issue list:*)","Bash(gh api:*)","Bash(gh issue comment:*)",Task
|
||||
settings: |
|
||||
{
|
||||
"model": "claude-sonnet-4-5-20250929",
|
||||
"model": "claude-sonnet-5",
|
||||
"env": {
|
||||
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}"
|
||||
}
|
||||
}
|
||||
|
||||
- name: Add potential-duplicate label if bot commented in this run
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.marvin-token.outputs.token }}
|
||||
run: |
|
||||
ISSUE=${{ github.event.issue.number || inputs.issue_number }}
|
||||
# Only match bot comments created in the last 10 minutes (this run)
|
||||
CUTOFF=$(date -u -d '10 minutes ago' '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null \
|
||||
|| date -u -v-10M '+%Y-%m-%dT%H:%M:%SZ')
|
||||
HAS_RECENT=$(gh api "repos/${{ github.repository }}/issues/${ISSUE}/comments?sort=created&direction=desc&per_page=10" \
|
||||
--jq "[.[] | select(
|
||||
.user.type == \"Bot\" and
|
||||
(.body | test(\"possible duplicate issues\"; \"i\")) and
|
||||
.created_at >= \"${CUTOFF}\"
|
||||
)] | length")
|
||||
if [ "$HAS_RECENT" -gt 0 ]; then
|
||||
gh issue edit "$ISSUE" --add-label "potential-duplicate" -R "${{ github.repository }}"
|
||||
echo "Added potential-duplicate label to #${ISSUE}"
|
||||
else
|
||||
echo "No recent duplicate comment found, skipping label"
|
||||
fi
|
||||
|
|
|
|||
179
.github/workflows/marvin-label-triage.yml
vendored
|
|
@ -27,19 +27,36 @@ jobs:
|
|||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
# TEMPORARY PIN — remove once upstream ships a fix.
|
||||
#
|
||||
# Claude Code 2.1.216 regressed the sandbox that claude-code-action wraps
|
||||
# every Bash call in when `allowed_non_write_users` is set: the mountpoint
|
||||
# walk fails closed, so every command — down to `true` — dies with
|
||||
# `bwrap: Can't create file at /home/.mcp.json: Permission denied`.
|
||||
# Marvin still reads the issue and picks correct labels, then cannot run
|
||||
# the helper that applies them, so triage silently applied zero labels
|
||||
# from 2026-07-20 onward while every run reported success.
|
||||
#
|
||||
# 2.1.215 is the last release without the regression.
|
||||
# https://github.com/anthropics/claude-code/issues/79997
|
||||
# https://github.com/anthropics/claude-code-action/issues/1547
|
||||
env:
|
||||
PINNED_CLAUDE_CODE_VERSION: "2.1.215"
|
||||
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: ${{ github.repository }}
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
owner: PrefectHQ
|
||||
|
||||
- name: Set triage prompt
|
||||
id: triage-prompt
|
||||
|
|
@ -48,7 +65,16 @@ jobs:
|
|||
PROMPT<<PROMPT_END
|
||||
You're an issue triage assistant for FastMCP, a Python framework for building Model Context Protocol servers and clients. Your task is to analyze issues/PRs and apply appropriate labels.
|
||||
|
||||
IMPORTANT: Your ONLY action should be to apply labels using mcp__github__update_issue. DO NOT post any comments.
|
||||
IMPORTANT: Your primary action should be to apply labels using the locked-down helper `.github/scripts/triage-label.sh`. DO NOT post comments EXCEPT when applying the too-long label (see below).
|
||||
|
||||
CRITICAL — LABEL MECHANICS:
|
||||
- Apply labels ONLY through the helper, which adds or removes repository labels on THIS issue/PR. It already knows the target repo and number (from the workflow environment) — you never pass them:
|
||||
add: `bash .github/scripts/triage-label.sh add "label1" "label2"`
|
||||
remove: `bash .github/scripts/triage-label.sh remove "label1"`
|
||||
- The helper uses the additive REST labels endpoint, so it works for both issues and PRs and never clobbers labels applied by other workflows — notably the Require Issue Link workflow's `missing-issue-link` control label, which must survive or an auto-closed PR won't reopen when its author is assigned.
|
||||
- The helper is your ONLY GitHub write access. Do NOT use raw `gh api`, `gh issue edit`, `gh pr edit`, or any other mutation — they are not available to you.
|
||||
- Only apply labels that exist in the repository (from `gh label list` in step 1). Never invent labels.
|
||||
- Use `remove` only to correct a label you believe is wrong, and never remove the control labels `missing-issue-link`, `bypass-issue-check`, or `trusted-contributor`.
|
||||
|
||||
Issue/PR Information:
|
||||
- REPO: ${{ github.repository }}
|
||||
|
|
@ -67,7 +93,7 @@ jobs:
|
|||
|
||||
3. Analyze and apply labels based on these guidelines:
|
||||
|
||||
CORE CATEGORIES (apply EXACTLY ONE - these are mutually exclusive):
|
||||
CORE CATEGORIES (apply EXACTLY ONE - these are mutually exclusive; skip if applying too-long):
|
||||
- bug: Reports of broken functionality OR PRs that fix bugs
|
||||
- enhancement: New functions/endpoints, improvements to existing features, internal tooling, workflow improvements, minor new capabilities
|
||||
- feature: ONLY for major headline functionality worthy of a blog post announcement (2-4 per release, never for issues)
|
||||
|
|
@ -95,8 +121,12 @@ jobs:
|
|||
|
||||
STATUS (apply if applicable):
|
||||
- needs more info: Issue lacks reproduction steps, error messages, or clear description
|
||||
- good first issue: ONLY if it's clearly scoped, has obvious solution, and touches limited files
|
||||
- invalid: Spam, completely off-topic, or nonsensical (often LLM-generated)
|
||||
- too-long: Apply when an issue or PR doesn't conform to CONTRIBUTING.md. Issues should be a short problem description, an MRE, and expected vs. actual behavior — not a design document. PRs should have a focused description of the change — not a report. We don't need proposed solutions or design alternatives (the issue should describe the problem and let maintainers architect the fix), summaries of what tests cover, explanations of code we can read ourselves, or speculative root-cause analysis. Common LLM failure modes to watch for: verbose "diagnostic" writeups, large proposed patches in issue bodies, multi-section reports restating what's visible in the diff, numbered lists of possible approaches or solutions, "suggested" schemas/shapes/APIs, generic analysis that doesn't reference specific code, and "Notes" sections. But these are heuristics, not rules — a complex PR may legitimately need more context, and a brief submission can still be low-quality. Judge by whether the content helps a reviewer or just adds noise. When applying too-long, still apply the core category and area labels — too-long is a format signal, not a replacement for categorization. Issues still need to be findable by category.
|
||||
|
||||
WHEN APPLYING too-long: After labeling, post a brief comment using mcp__github__add_issue_comment:
|
||||
"Thanks for the report. This issue goes beyond what our contributor guidelines ask for — we just need a short problem description and an MRE. Please see our [contributing guidelines](https://github.com/PrefectHQ/fastmcp/blob/main/CONTRIBUTING.md) and condense this issue. We'll triage it once it's trimmed down."
|
||||
Use this exact text (or very close to it). Do not editorialize or add details.
|
||||
|
||||
AREA LABELS (apply ONLY when thematically central to the issue):
|
||||
- cli: Issues primarily about FastMCP CLI commands (run, dev, install)
|
||||
|
|
@ -105,32 +135,44 @@ jobs:
|
|||
- auth: Authentication is the main concern (Bearer, JWT, OAuth, WorkOS)
|
||||
- openapi: OpenAPI integration/parsing is the primary topic
|
||||
- http: HTTP transport or networking is the main issue
|
||||
- contrib: Specifically about community contributions in src/contrib/
|
||||
- contrib: Specifically about community contributions in fastmcp_slim/fastmcp/contrib/
|
||||
- tests: Issues primarily about testing infrastructure, CI/CD workflows, or test coverage
|
||||
- security: Apply ONLY when the issue/PR addresses an exploitable vulnerability or hardens against one. Examples: SSRF, LFI, path traversal, injection, auth bypass allowing unauthorized access, scope escalation, open redirects. Do NOT apply for ordinary auth bugs (wrong scopes returned, token refresh logic, OAuth flow correctness) unless an attacker could exploit the bug to bypass access controls or escalate privileges. The key question: "Could a malicious actor exploit this?" If the answer is just "it breaks for legitimate users," that's a bug, not a security issue.
|
||||
|
||||
IMPORTANT LABELING RULES:
|
||||
- Be selective - only apply labels that are clearly relevant
|
||||
- Don't apply area labels just because a file in that area is mentioned
|
||||
- The issue must be PRIMARILY about that area to get the label
|
||||
- When in doubt, don't apply the label
|
||||
- Apply 2-5 labels total typically (category + maybe priority + maybe 1-2 areas)
|
||||
LABELING PRINCIPLES:
|
||||
- Precision over recall: a missing label is a minor inconvenience; a wrong label sends the wrong people to the wrong issue. When in doubt, don't apply.
|
||||
- Don't apply area labels just because a file in that area is mentioned — the issue must be PRIMARILY about that area.
|
||||
- Apply 2-5 labels total typically (category + maybe priority + maybe 1-2 areas).
|
||||
- For ambiguous cases (bug vs enhancement, which area label), prefer the more conservative choice or omit the uncertain label entirely.
|
||||
|
||||
META LABELS (rarely needed for issues):
|
||||
- dependencies: Only for dependabot PRs or issues specifically about package updates
|
||||
- DON'T MERGE: Only if PR author explicitly states it's not ready
|
||||
|
||||
4. Apply selected labels:
|
||||
Use mcp__github__update_issue to apply your selected labels
|
||||
DO NOT post any comments
|
||||
Add them with `bash .github/scripts/triage-label.sh add "label1" "label2"`.
|
||||
DO NOT post any comments unless applying too-long (see above)
|
||||
PROMPT_END
|
||||
EOF
|
||||
|
||||
- name: Clean up stale Claude locks
|
||||
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
|
||||
|
||||
# Mirrors how the action installs Claude Code itself, minus the version
|
||||
# it hardcodes. Passing path_to_claude_code_executable makes the action
|
||||
# skip its own install and use this build.
|
||||
- name: Install pinned Claude Code
|
||||
id: pin-claude
|
||||
run: |
|
||||
curl -fsSL https://claude.ai/install.sh | bash -s -- "$PINNED_CLAUDE_CODE_VERSION"
|
||||
echo "path=$HOME/.local/bin/claude" >> "$GITHUB_OUTPUT"
|
||||
"$HOME/.local/bin/claude" --version
|
||||
|
||||
- name: Run Marvin for Issue Triage
|
||||
id: marvin
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
path_to_claude_code_executable: ${{ steps.pin-claude.outputs.path }}
|
||||
github_token: ${{ steps.marvin-token.outputs.token }}
|
||||
bot_name: "Marvin Context Protocol"
|
||||
prompt: ${{ steps.triage-prompt.outputs.PROMPT }}
|
||||
|
|
@ -138,11 +180,114 @@ jobs:
|
|||
allowed_non_write_users: "*"
|
||||
allowed_bots: "marvin-context-protocol"
|
||||
claude_args: |
|
||||
--allowedTools Bash(gh label list),mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__update_issue,mcp__github__get_pull_request_files
|
||||
--allowedTools "Bash(gh label list:*)","Bash(bash .github/scripts/triage-label.sh:*)",mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__add_issue_comment,mcp__github__get_pull_request,mcp__github__get_pull_request_files
|
||||
settings: |
|
||||
{
|
||||
"model": "claude-sonnet-4-5-20250929",
|
||||
"model": "claude-sonnet-5",
|
||||
"env": {
|
||||
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}"
|
||||
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}",
|
||||
"TRIAGE_REPO": "${{ github.repository }}",
|
||||
"TRIAGE_NUMBER": "${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}"
|
||||
}
|
||||
}
|
||||
|
||||
# Triage is fire-and-forget: nobody watches a green run, so a broken
|
||||
# allowlist has to fail the job or it goes unnoticed indefinitely — a
|
||||
# mangled pattern silently produced zero labels across a dozen PRs
|
||||
# because the run still reported success.
|
||||
#
|
||||
# Only denials of commands we MEANT to grant indicate that breakage. An
|
||||
# agent reaching for something never on the allowlist (falling back to
|
||||
# `gh issue view` when the API is down, say) is behaving normally, and
|
||||
# failing on that would cry wolf during every GitHub incident.
|
||||
- name: Fail if Marvin could not run its tools
|
||||
if: always() && steps.marvin.conclusion != 'skipped'
|
||||
env:
|
||||
EXECUTION_FILE: ${{ steps.marvin.outputs.execution_file }}
|
||||
run: |
|
||||
file="${EXECUTION_FILE:-}"
|
||||
if [[ -z "$file" || ! -s "$file" ]]; then
|
||||
file="${RUNNER_TEMP}/claude-execution-output.json"
|
||||
fi
|
||||
# A missing or empty log means we cannot tell a clean run from a
|
||||
# blocked one, which is the exact failure this step exists to catch.
|
||||
if [[ ! -s "$file" ]]; then
|
||||
echo "::error::No Marvin execution log found; cannot verify tool permissions."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The persisted log carries a `permission_denials` array on each
|
||||
# `type: result` entry; the `permission_denials_count` scalar only
|
||||
# appears in the action's condensed stdout summary, never on disk.
|
||||
# Anchor to result entries rather than recursing with `..`, which
|
||||
# descends into each denial's `tool_input` and double-counts any
|
||||
# denied command that happens to mention the field name.
|
||||
if ! summary=$(jq -sr '
|
||||
[ .[] | if type == "array" then .[] else . end ]
|
||||
| map(select(type == "object" and .type == "result"))
|
||||
| map(.permission_denials // []) | flatten
|
||||
| map(.tool_input.command // "")
|
||||
| { total: length,
|
||||
granted: map(select(
|
||||
startswith("gh label list")
|
||||
or startswith("bash .github/scripts/triage-label.sh")
|
||||
))
|
||||
}
|
||||
| "\(.total)\t\(.granted | length)\t\(.granted | join(" | "))"
|
||||
' "$file"); then
|
||||
echo "::error::Could not parse Marvin execution log ($file)."
|
||||
exit 1
|
||||
fi
|
||||
IFS=$'\t' read -r total granted commands <<<"$summary"
|
||||
echo "Denied tool calls: $total (of which allowlisted: $granted)"
|
||||
|
||||
if [[ "$granted" -gt 0 ]]; then
|
||||
echo "::error::Marvin was denied $granted call(s) to tools this workflow grants, so it could not apply labels: ${commands}. The --allowedTools value is not reaching the permission matcher intact — claude_args is lexed with shell-quote, so any Bash(...) pattern containing a space must be quoted or it is split into fragments."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$total" -gt 0 ]]; then
|
||||
echo "::notice::Marvin was denied $total call(s), none of them to tools this workflow grants. That is expected when it probes for a tool we deliberately withhold; the allowlist is intact."
|
||||
fi
|
||||
|
||||
# A granted tool can also fail *after* the permission check, which the
|
||||
# denial count above cannot see. Claude Code 2.1.216 did exactly that:
|
||||
# the sandbox refused to build and every Bash call — including the
|
||||
# labeling helper — exited 1 with `bwrap: ...`, while the run stayed
|
||||
# green. Correlate results back to their Bash tool_use rather than
|
||||
# grepping the whole log, so an issue body quoting a sandbox error
|
||||
# cannot fail an otherwise healthy run.
|
||||
if ! sandbox=$(jq -sr '
|
||||
[ .[] | if type == "array" then .[] else . end ]
|
||||
| map(select(type == "object" and (.type == "assistant" or .type == "user")))
|
||||
| map(.message.content // []) | flatten
|
||||
| map(select(type == "object"))
|
||||
| . as $blocks
|
||||
| ( $blocks
|
||||
| map(select(.type == "tool_use" and .name == "Bash"))
|
||||
| map(.id) ) as $bash
|
||||
| $blocks
|
||||
| map(select(.type == "tool_result" and (.tool_use_id as $i | $bash | index($i))))
|
||||
| map(.content | tostring)
|
||||
| map(select(test("bwrap:|Failed to (start|create) sandbox")))
|
||||
| "\(length)\t\(.[0] // "" | gsub("[\t\n]"; " ") | .[0:200])"
|
||||
' "$file"); then
|
||||
echo "::error::Could not scan Marvin execution log for sandbox failures ($file)."
|
||||
exit 1
|
||||
fi
|
||||
IFS=$'\t' read -r sandbox_failures sandbox_sample <<<"$sandbox"
|
||||
|
||||
if [[ "$sandbox_failures" -gt 0 ]]; then
|
||||
echo "::error::Marvin's Bash tool failed $sandbox_failures time(s) inside the action's subprocess sandbox, so it could not apply labels: ${sandbox_sample}. This is an environment failure, not a prompt or allowlist problem — check whether the pinned Claude Code version (${PINNED_CLAUDE_CODE_VERSION}) still avoids the upstream sandbox regression."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload Marvin execution log
|
||||
if: always() && steps.marvin.conclusion != 'skipped'
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: marvin-triage-execution-log
|
||||
path: |
|
||||
${{ steps.marvin.outputs.execution_file }}
|
||||
${{ runner.temp }}/claude-execution-output.json
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ concurrency:
|
|||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
martian-test-failure:
|
||||
marvin-test-failure:
|
||||
# Only run if the test workflow failed
|
||||
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -23,19 +23,19 @@ jobs:
|
|||
actions: read # Required for Claude to read CI results
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Set up Python 3.10
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
|
|
@ -60,6 +60,17 @@ jobs:
|
|||
2. Identify the root cause of the failure(s)
|
||||
3. Suggest a clear, actionable solution to fix the failure(s)
|
||||
|
||||
# Response Proportionality
|
||||
Match your response length to the complexity of the failure. Not every failure needs a full investigation:
|
||||
|
||||
**Trivial failures** (formatting, linting) — post a short, direct comment. No collapsible sections, no root-cause deep-dive. Example:
|
||||
> CI failed: `ruff format` reformatted 2 files. Run `uv run ruff format .` locally and push.
|
||||
|
||||
**Pre-existing flaky tests** unrelated to the PR — say so briefly. Don't write a full analysis of a test the PR didn't touch. Example:
|
||||
> CI failed due to a pre-existing flaky test (`test_name`) unrelated to this PR's changes. Safe to re-run.
|
||||
|
||||
**Real failures caused by the PR** — these deserve the full analysis format below. Spend your effort here.
|
||||
|
||||
# Getting Started
|
||||
1. Call the generate_agents_md tool to get a high-level summary of the project
|
||||
2. Get the pull request associated with this workflow run from the GitHub repository: ${{ github.repository }}
|
||||
|
|
@ -75,60 +86,61 @@ jobs:
|
|||
5. Search the codebase for relevant files, tests, and implementations
|
||||
|
||||
# Your Response
|
||||
Post a comment on the pull request with your analysis. Your comment should include:
|
||||
Post a comment on the pull request with your analysis.
|
||||
|
||||
## Test Failure Analysis
|
||||
Lead with a tl;dr — 1-2 sentences that tell the developer what broke and what to do about it. This should be visible without expanding anything.
|
||||
|
||||
**Summary**: A brief 1-2 sentence summary of what failed.
|
||||
Push supporting detail into collapsible `<details>` blocks. The reader should be able to act on your comment without expanding a single one. Think of details blocks as appendices — there if someone wants to dig deeper, not required for the main message.
|
||||
|
||||
**Root Cause**: A clear explanation of why the tests failed, based on your analysis of the logs and code.
|
||||
For real (non-trivial) failures, use this structure:
|
||||
|
||||
**Suggested Solution**: Specific, actionable steps to fix the failure(s). Include:
|
||||
- Which files need to be modified
|
||||
- What changes are needed
|
||||
- Why these changes will fix the issue
|
||||
**tl;dr**: What failed and what to do (1-2 sentences, always visible)
|
||||
|
||||
**Root Cause**: Why it failed (a short paragraph, always visible)
|
||||
|
||||
**Fix**: Specific files and changes needed (always visible)
|
||||
|
||||
<details>
|
||||
<summary>Detailed Analysis</summary>
|
||||
|
||||
Include here:
|
||||
- Relevant log excerpts showing the failure
|
||||
- Code snippets that are causing the issue
|
||||
- Any related issues or PRs that might be relevant
|
||||
<summary>Log excerpts</summary>
|
||||
Relevant failure output
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Related Files</summary>
|
||||
|
||||
List files that are relevant to the failure with brief explanations of their relevance.
|
||||
<summary>Related files</summary>
|
||||
Files relevant to the failure
|
||||
</details>
|
||||
|
||||
# Important Guidelines
|
||||
- Be concise and actionable - developers want to quickly understand and fix the issue. Provide
|
||||
additional context, references, etc in collapsible details blocks to ensure that the comment you're adding
|
||||
is short and easy to read but additional information is a click away.
|
||||
- Focus on facts from the logs and code, not speculation
|
||||
- If you can't determine the root cause, say so clearly
|
||||
- If your only suggestion is a bad suggestion (disable the test, change the timeout, etc), indicate that you've run out of ideas and
|
||||
that they probably don't want to do that.
|
||||
- Provide specific file names, line numbers, and code references when possible
|
||||
- You can run make commands (e.g., `make lint`, `make typecheck`, `make sync`) to build, test, or lint the code
|
||||
- You can also run git commands (e.g., `git status`, `git log`, `git diff`) to inspect the repository
|
||||
- You can use WebSearch and WebFetch to research errors, stack traces, or related issues
|
||||
- For bash commands, you are limited to make and git commands only
|
||||
# Quality Standards
|
||||
- Every claim needs evidence: file paths, line numbers, log excerpts. Never say "the test fails" without citing which test and what the error was.
|
||||
- Focus on facts from the logs and code, not speculation. If you can't determine the root cause, say so clearly — "I don't know" is better than a wrong diagnosis.
|
||||
- If your only suggestion is a bad one (disable the test, increase the timeout, etc.), say so honestly rather than dressing it up.
|
||||
- Do not paste raw CLI output (e.g., prek progress bars, pytest collection output) into the comment body. Quote only the relevant failure lines.
|
||||
- Always include specific file names, tool names, and test names in your summary. Never leave a sentence with a blank where a name should be.
|
||||
|
||||
# CRITICAL: ANGRY USERS
|
||||
**IMPORTANT**: If the user is angry with you, the triage bot, don't respond. Just exit immediately without further action.
|
||||
If at any point in the conversation the user has asked you to stop replying to the thread, just exit immediately.
|
||||
# Self-Review Before Posting
|
||||
Before posting your comment, re-read it as the PR author would. Ask:
|
||||
- Can I act on this without expanding any `<details>` block?
|
||||
- Does every claim cite a specific file, line, or log excerpt?
|
||||
- Am I telling them something they can't already see in the CI logs, or just restating them?
|
||||
If your comment doesn't add value beyond what the logs already show, don't post it.
|
||||
|
||||
# STOP SIGNALS
|
||||
If anyone on the PR has asked the bot to stop — e.g., "stop", "go away", "don't comment", "no more bot comments" — exit immediately without further action. This includes past comments in the thread, not just the most recent one.
|
||||
|
||||
If you are posting the same suggestion as you have previously made, do not post the suggestion again.
|
||||
|
||||
# IMPORTANT: EDIT YOUR COMMENT
|
||||
Do not post a new comment every time you triage a failing workflow. If a previous comment has been posted by you (marvin)
|
||||
in a previous triage, edit that comment do not add a new comment for each failure. Be sure to include a note that you've edited
|
||||
your comment to reflect the latest analysis. Don't worry about keeping the old content around, there's comment history for
|
||||
your comment to reflect the latest analysis. Don't worry about keeping the old content around, there's comment history for
|
||||
that.
|
||||
|
||||
# Available Tools
|
||||
- You can run make commands (e.g., `make lint`, `make typecheck`, `make sync`) to build, test, or lint the code
|
||||
- You can also run git commands (e.g., `git status`, `git log`, `git diff`) to inspect the repository
|
||||
- You can use WebSearch and WebFetch to research errors, stack traces, or related issues
|
||||
- For bash commands, you are limited to make and git commands only
|
||||
|
||||
# Problems Encountered
|
||||
If you encounter any problems during your analysis (e.g., unable to fetch logs, tools not working), document them clearly so the team knows what limitations you faced.
|
||||
PROMPT_END
|
||||
|
|
@ -181,5 +193,5 @@ jobs:
|
|||
|
||||
prompt: ${{ steps.analysis-prompt.outputs.PROMPT }}
|
||||
claude_args: |
|
||||
--allowed-tools mcp__repository-summary,mcp__code-search,mcp__github-research,WebSearch,WebFetch,Bash(make:*,git:*)
|
||||
--allowed-tools mcp__repository-summary,mcp__code-search,mcp__github-research,WebSearch,WebFetch,"Bash(make:*)","Bash(git:*)"
|
||||
--mcp-config /tmp/mcp-config/mcp-servers.json
|
||||
221
.github/workflows/marvin-triage-issue.yml
vendored
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
# Triage new issues: investigate, recommend, apply labels
|
||||
# Calls run-claude directly with triage prompt (elastic issue-triage style)
|
||||
|
||||
name: Triage Issue
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
if: |
|
||||
github.event.issue.user.login == 'strawgate' ||
|
||||
(github.event.issue.user.login == 'jlowin' && contains(toJSON(github.event.issue.labels.*.name), 'bug'))
|
||||
concurrency:
|
||||
group: triage-issue-${{ github.event.issue.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: ${{ github.repository }}
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: React to issue with eyes
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.marvin-token.outputs.token }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/reactions" -f content=eyes 2>/dev/null || true
|
||||
|
||||
- name: Run Claude for Triage
|
||||
uses: ./.github/actions/run-claude
|
||||
env:
|
||||
ISSUE_BODY: ${{ github.event.issue.body }}
|
||||
ISSUE_TITLE: ${{ github.event.issue.title }}
|
||||
with:
|
||||
claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
github-token: ${{ steps.marvin-token.outputs.token }}
|
||||
allowed-tools: "Edit,MultiEdit,Glob,Grep,LS,Read,Write,WebSearch,WebFetch,mcp__github_comment__update_claude_comment,mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,Bash(*),mcp__agents-md-generator__generate_agents_md,mcp__public-code-search__search_code"
|
||||
prompt: |
|
||||
<context>
|
||||
Repository: ${{ github.repository }}
|
||||
Issue Number: #${{ github.event.issue.number }}
|
||||
Issue Title: ${{ env.ISSUE_TITLE }}
|
||||
Issue Author: ${{ github.event.issue.user.login }}
|
||||
</context>
|
||||
|
||||
<issue_body>
|
||||
${{ env.ISSUE_BODY }}
|
||||
</issue_body>
|
||||
|
||||
<task>
|
||||
Triage this new GitHub issue and provide a helpful, actionable response. You can write files and execute commands to test, verify, or investigate the issue.
|
||||
</task>
|
||||
|
||||
<constraints>
|
||||
This workflow is for investigation, testing, and planning.
|
||||
|
||||
You CANNOT: Create branches, checkout branches, commit code to the repository
|
||||
Do not push changes to the repository.
|
||||
You CAN: Read/analyze code, search repository, review git history, search for similar issues, write files, verify behavior, provide analysis and recommendations
|
||||
</constraints>
|
||||
|
||||
<allowed_tools>
|
||||
You have access to the following tools (comma-separated list):
|
||||
|
||||
Edit,MultiEdit,Glob,Grep,LS,Read,Write,WebSearch,WebFetch,mcp__github_comment__update_claude_comment,mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,Bash(*),mcp__agents-md-generator__generate_agents_md,mcp__public-code-search__search_code
|
||||
|
||||
You can only use tools that are explicitly listed above. For Bash commands, the pattern `Bash(command:*)` means you can run that command with any arguments. If a command is not listed, it is not available.
|
||||
</allowed_tools>
|
||||
|
||||
<getting_started>
|
||||
Use `mcp__agents-md-generator__generate_agents_md` to get repository context before triaging.
|
||||
</getting_started>
|
||||
|
||||
<investigation_tools>
|
||||
- `mcp__public-code-search__search_code`: Search code in OTHER repositories (use `Grep`/`Read` for this repo)
|
||||
- `WebSearch`: Search the web for documentation, best practices, or solutions
|
||||
- `WebFetch`: Fetch and read content from URLs
|
||||
- Git commands: You have access to git commands, but write commands (commit, push, checkout, branch creation) are blocked
|
||||
- Write: You can write files (e.g., test files, temporary files for verification)
|
||||
- Execution: See `<allowed_tools>` section above for exact list of available execution commands
|
||||
</investigation_tools>
|
||||
|
||||
<execution_guidelines>
|
||||
If execution commands are available (check `<allowed_tools>` section), you can:
|
||||
- Run tests to verify reported bugs or test proposed solutions
|
||||
- Execute scripts to understand behavior
|
||||
- Run linters or static analysis tools
|
||||
- Verify environment setup or dependencies
|
||||
- Test specific code paths or scenarios
|
||||
- Write test files to confirm behavior
|
||||
|
||||
When executing commands:
|
||||
- Explain what you're testing and why
|
||||
- Include command output in your response when relevant
|
||||
- Use execution to validate your findings and recommendations
|
||||
- Only use commands that are explicitly listed in `<allowed_tools>`
|
||||
</execution_guidelines>
|
||||
|
||||
<response_goals>
|
||||
Your number one priority is to provide a great response to the issue. A great response is a response that is clear, concise, accurate, and actionable. You will avoid long paragraphs, flowery language, and overly verbose responses. Your readers have limited time and attention, so you will be concise and to the point.
|
||||
|
||||
In priority order your goal is to:
|
||||
1. Provide context about the request or issue (related issues, pull requests, files, etc.)
|
||||
2. Layout a single high-quality and actionable recommendation for how to address the issue based on your knowledge of the project, codebase, and issue
|
||||
3. Provide a high quality and detailed plan that a junior developer could follow to implement the recommendation
|
||||
4. Use execution to verify findings when appropriate (check `<allowed_tools>` section for available commands)
|
||||
|
||||
Report findings and recommendations — not your process. Do not include task checklists, progress tracking, or "steps I took" narration (e.g., `- [x] Read source code`). The reader cares about what you found, not how you found it.
|
||||
</response_goals>
|
||||
|
||||
<evidence_standards>
|
||||
Every claim in your response must be grounded in evidence you can cite:
|
||||
- **Code references**: Always include file path and line number (e.g., `fastmcp_slim/fastmcp/client/client.py:142`). Never say "the client code does X" without pointing to where.
|
||||
- **Bug confirmation**: If you say a bug is real, show the specific code path that produces it. If you ran a test, include the command and output.
|
||||
- **Related items**: When citing a related issue or PR, explain specifically why it's related — not just that it exists.
|
||||
- **Confidence**: If you're uncertain about a finding, say so. "I don't know" or "I couldn't confirm this" is better than a speculative diagnosis. Only report findings you would confidently defend.
|
||||
</evidence_standards>
|
||||
|
||||
<quality_gate>
|
||||
Before posting, re-read your response as a maintainer would:
|
||||
- Does the tl;dr give the full picture without expanding anything?
|
||||
- Does every claim cite a specific file, line, or test result?
|
||||
- Is this telling the maintainer something they couldn't find in 5 minutes of reading the issue and grepping the code?
|
||||
If your response doesn't add meaningful value beyond restating the issue, it's okay to post a short "confirmed, straightforward fix in [file]:[line]" response instead of a full analysis.
|
||||
</quality_gate>
|
||||
|
||||
<response_sections>
|
||||
Populate the following sections in your response:
|
||||
Recommendation (or "No recommendation" with reason)
|
||||
Findings
|
||||
Verification (if you executed tests or commands - check `<allowed_tools>` section)
|
||||
Detailed Action Plan
|
||||
Related Items
|
||||
Related Files
|
||||
Related Webpages
|
||||
|
||||
You may not be able to do all of these things, sometimes you may find that all you can do is provide in-depth context of the issue and related items. That's perfectly acceptable and expected. Your performance is judged by how accurate your findings are, do the investigation required to have high confidence in your findings and recommendations. "I don't know" or "I'm unable to recommend a course of action" is better than a bad or wrong answer.
|
||||
|
||||
Structure: Lead with a tl;dr (1-3 sentences, always visible) that gives the reader the bottom line — what this issue is, whether it's valid, and what to do about it. The reader should be able to act on your comment without expanding anything.
|
||||
|
||||
Push everything else into collapsible `<details>` blocks: findings, verification output, action plans, related items, related files. These are appendices — valuable for someone who wants to dig deeper, but not required for the main message. The only things that should be visible without clicking are the tl;dr and the recommendation. Short responses (a few sentences) don't need collapsible sections at all.
|
||||
|
||||
</response_sections>
|
||||
<response_examples>
|
||||
# Example: the tl;dr and recommendation are always visible, everything else is collapsed
|
||||
|
||||
**tl;dr**: Confirmed bug — `Calculator.divide` raises `ValueError` instead of `DivisionByZeroError`. PR #654 partially addresses this but is incomplete.
|
||||
|
||||
**Recommendation**: Complete PR #654: update `Calculator.divide` to raise `DivisionByZeroError` and update the test assertions to match.
|
||||
|
||||
<details>
|
||||
<summary>Findings</summary>
|
||||
...details from the code analysis that are relevant to the issue and the recommendation...
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Verification</summary>
|
||||
|
||||
```bash
|
||||
$ pytest test_calculator.py::test_divide_by_zero
|
||||
FAILED - raises ValueError instead of DivisionByZeroError
|
||||
```
|
||||
This confirms the issue report is accurate.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Action Plan</summary>
|
||||
...a detailed plan that a junior developer could follow to implement the recommendation...
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Related Issues and Pull Requests</summary>
|
||||
|
||||
| Issue or PR | Relevance |
|
||||
| --- | --- |
|
||||
| [Add matrix operations support](https://github.com/PrefectHQ/fastmcp/pull/680) | Directly addresses the feature request |
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Related Files</summary>
|
||||
|
||||
| File | Relevance |
|
||||
| --- | --- |
|
||||
| [calculator.py L29-32](https://github.com/modelcontextprotocol/python-sdk/blob/main/calculator.py#L29-L32) | The `divide` method that raises ValueError |
|
||||
| [test_calculator.py L25-27](https://github.com/modelcontextprotocol/python-sdk/blob/main/test_calculator.py#L25-L27) | Test asserting ValueError (needs updating) |
|
||||
</details>
|
||||
</response_examples>
|
||||
|
||||
<response_footer>
|
||||
Always end your comment with a new line, three dashes, and the footer message:
|
||||
<exact_content>
|
||||
|
||||
---
|
||||
Marvin Context Protocol | Type `/marvin` to interact further
|
||||
|
||||
Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.
|
||||
</exact_content>
|
||||
</response_footer>
|
||||
|
||||
<github_formatting>
|
||||
When writing GitHub comments, wrap branch names, tags, or other @-references in backticks (e.g., `@main`, `@v1.0`) to avoid accidentally pinging users. Do not add backticks around terms that are already inside backticks or code blocks.
|
||||
Do not write `fixes #N`, `closes #N`, or `resolves #N` in comments — these can accidentally close issues. Use plain `#N` references instead.
|
||||
</github_formatting>
|
||||
81
.github/workflows/marvin.yml
vendored
|
|
@ -1,81 +0,0 @@
|
|||
name: Marvin Context Protocol
|
||||
|
||||
on:
|
||||
issue_comment: { types: [created] }
|
||||
pull_request_review_comment: { types: [created] }
|
||||
pull_request_review: { types: [submitted] }
|
||||
pull_request: { types: [opened, edited] }
|
||||
issues: { types: [opened, edited, assigned, labeled] }
|
||||
discussion: { types: [created, edited, labeled] }
|
||||
discussion_comment: { types: [created] }
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
actions: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
marvin:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '/marvin')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '/marvin')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '/marvin')) ||
|
||||
(github.event_name == 'pull_request' && contains(github.event.pull_request.body, '/marvin')) ||
|
||||
(github.event_name == 'issues' && contains(github.event.issue.body, '/marvin')) ||
|
||||
(github.event_name == 'discussion' && contains(github.event.discussion.body, '/marvin')) ||
|
||||
(github.event_name == 'discussion_comment' && contains(github.event.comment.body, '/marvin')) ||
|
||||
(github.event_name == 'issues' && github.event.action == 'assigned' && github.event.assignee.login == 'Marvin Context Protocol') ||
|
||||
(github.event_name == 'issues' && github.event.action == 'labeled' && github.event.label.name == 'marvin')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
# Install UV package manager
|
||||
- name: Install UV
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
|
||||
# Install project dependencies
|
||||
- name: Install dependencies
|
||||
run: uv sync --python 3.12
|
||||
|
||||
- name: Run prek
|
||||
uses: j178/prek-action@v1
|
||||
env:
|
||||
SKIP: no-commit-to-branch
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Clean up stale Claude locks
|
||||
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
|
||||
|
||||
# Marvin Assistant
|
||||
- name: Run Marvin
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ steps.marvin-token.outputs.token }}
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
trigger_phrase: "/marvin"
|
||||
allowed_bots: "*"
|
||||
claude_args: |
|
||||
--allowedTools WebSearch,WebFetch,Bash(uv:*),Bash(pre-commit:*),Bash(prek:*),Bash(pytest:*),Bash(ruff:*),Bash(ty:*),Bash(git:*),Bash(gh:*),mcp__github__add_issue_comment,mcp__github__create_issue,mcp__github__get_issue,mcp__github__list_issues,mcp__github__search_issues,mcp__github__update_issue,mcp__github__update_issue_comment,mcp__github__create_pull_request,mcp__github__get_pull_request,mcp__github__get_pull_request_comments,mcp__github__get_pull_request_files,mcp__github__get_pull_request_reviews,mcp__github__get_pull_request_status,mcp__github__list_pull_requests,mcp__github__update_pull_request,mcp__github__update_pull_request_branch,mcp__github__update_pull_request_comment,mcp__github__merge_pull_request
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
settings: |
|
||||
{
|
||||
"model": "claude-sonnet-4-5-20250929",
|
||||
"env": {
|
||||
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}"
|
||||
},
|
||||
"customInstructions": "When you complete work on an issue: (1) You MUST create a pull request using the mcp__github__create_pull_request tool instead of posting a link, and (2) You MUST add the 'marvin-pr' label to the original issue using mcp__github__update_issue. Even if PR creation fails and you post a link instead, you MUST still add the 'marvin-pr' label. Follow the PR message guidelines in CLAUDE.md."
|
||||
}
|
||||
47
.github/workflows/minimize-resolved-reviews.yml
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
# Minimize resolved PR review comments to reduce noise.
|
||||
#
|
||||
# Runs automatically on review activity for same-repo PRs. Fork PRs are
|
||||
# skipped because GITHUB_TOKEN is read-only in that context. Collaborators
|
||||
# can comment "/tidy" on any PR (including forks) to trigger manually.
|
||||
|
||||
name: Minimize Resolved Reviews
|
||||
|
||||
on:
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
pull_request_review_comment:
|
||||
types: [created, edited]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
# Scope the group by event name so that the sibling events fired by a single
|
||||
# review action (pull_request_review + pull_request_review_comment, same instant)
|
||||
# don't cancel each other. Same-PR runs of the *same* event still supersede
|
||||
# cleanly, and the last one always completes.
|
||||
concurrency:
|
||||
group: minimize-reviews-${{ github.event.pull_request.number || github.event.issue.number }}-${{ github.event_name }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
minimize:
|
||||
# /tidy comment: collaborators can trigger on any PR (token has write access)
|
||||
# Review events: skip fork PRs where GITHUB_TOKEN lacks write permissions
|
||||
if: >-
|
||||
(
|
||||
github.event_name == 'issue_comment' &&
|
||||
github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '/tidy') &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)
|
||||
) || (
|
||||
github.event_name != 'issue_comment' &&
|
||||
github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Minimize resolved review comments
|
||||
uses: strawgate/minimize-resolved-pr-reviews@v0
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
87
.github/workflows/publish-fastmcp-remote.yml
vendored
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
name: Publish fastmcp-remote to PyPI
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Publish fastmcp-slim to PyPI"]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
pypi-publish:
|
||||
name: Upload fastmcp-remote to PyPI
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build fastmcp-remote
|
||||
run: uv build --package fastmcp-remote
|
||||
|
||||
- name: Verify matching fastmcp-slim is published
|
||||
run: |
|
||||
SLIM_VERSION=$(python - <<'PY'
|
||||
import email.parser
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
wheel = next(Path("dist").glob("fastmcp_remote-*.whl"))
|
||||
metadata_name = next(
|
||||
name for name in zipfile.ZipFile(wheel).namelist()
|
||||
if name.endswith(".dist-info/METADATA")
|
||||
)
|
||||
metadata = email.parser.Parser().parsestr(
|
||||
zipfile.ZipFile(wheel).read(metadata_name).decode()
|
||||
)
|
||||
for value in metadata.get_all("Requires-Dist", []):
|
||||
requirement, _, marker = value.partition(";")
|
||||
if marker.strip():
|
||||
continue
|
||||
match = re.fullmatch(
|
||||
r"fastmcp-slim(?:\[[^\]]+\])?==([^;\s]+)",
|
||||
requirement.strip(),
|
||||
)
|
||||
if match:
|
||||
print(match.group(1))
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Could not find the base fastmcp-slim dependency")
|
||||
PY
|
||||
)
|
||||
|
||||
for attempt in {1..12}; do
|
||||
if python - "$SLIM_VERSION" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
version = sys.argv[1]
|
||||
url = f"https://pypi.org/pypi/fastmcp-slim/{version}/json"
|
||||
with urllib.request.urlopen(url, timeout=30) as response:
|
||||
json.load(response)
|
||||
PY
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI; refusing to publish fastmcp-remote." >&2
|
||||
exit 1
|
||||
|
||||
- name: Publish fastmcp-remote to PyPI
|
||||
run: uv publish -v dist/fastmcp_remote-*.tar.gz dist/fastmcp_remote-*.whl
|
||||
30
.github/workflows/publish-fastmcp-slim.yml
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
name: Publish fastmcp-slim to PyPI
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
pypi-publish:
|
||||
name: Upload fastmcp-slim to PyPI
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build fastmcp-slim
|
||||
run: uv build --package fastmcp-slim
|
||||
|
||||
- name: Publish fastmcp-slim to PyPI
|
||||
run: uv publish -v dist/fastmcp_slim-*.tar.gz dist/fastmcp_slim-*.whl
|
||||
104
.github/workflows/publish-fastmcp-tasks.yml
vendored
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
name: Publish fastmcp-tasks to PyPI
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Publish fastmcp-slim to PyPI"]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
pypi-publish:
|
||||
name: Upload fastmcp-tasks to PyPI
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
|
||||
# Maintenance branches predate the standalone fastmcp-tasks package and
|
||||
# resolve the `tasks` extra through fastmcp-slim instead. This workflow
|
||||
# runs from the default branch for every fastmcp-slim release, including
|
||||
# those tags, so detect the package rather than assume it is there.
|
||||
- name: Check whether this ref builds fastmcp-tasks
|
||||
id: package_present
|
||||
run: |
|
||||
if [ -d fastmcp_tasks ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "This ref has no fastmcp_tasks package; nothing to publish."
|
||||
fi
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build fastmcp-tasks
|
||||
if: steps.package_present.outputs.present == 'true'
|
||||
run: uv build --package fastmcp-tasks
|
||||
|
||||
- name: Verify matching fastmcp-slim is published
|
||||
if: steps.package_present.outputs.present == 'true'
|
||||
run: |
|
||||
SLIM_VERSION=$(python - <<'PY'
|
||||
import email.parser
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
wheel = next(Path("dist").glob("fastmcp_tasks-*.whl"))
|
||||
metadata_name = next(
|
||||
name for name in zipfile.ZipFile(wheel).namelist()
|
||||
if name.endswith(".dist-info/METADATA")
|
||||
)
|
||||
metadata = email.parser.Parser().parsestr(
|
||||
zipfile.ZipFile(wheel).read(metadata_name).decode()
|
||||
)
|
||||
for value in metadata.get_all("Requires-Dist", []):
|
||||
requirement, _, marker = value.partition(";")
|
||||
if marker.strip():
|
||||
continue
|
||||
match = re.fullmatch(
|
||||
r"fastmcp-slim(?:\[[^\]]+\])?==([^;\s]+)",
|
||||
requirement.strip(),
|
||||
)
|
||||
if match:
|
||||
print(match.group(1))
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Could not find the base fastmcp-slim dependency")
|
||||
PY
|
||||
)
|
||||
|
||||
for attempt in {1..12}; do
|
||||
if python - "$SLIM_VERSION" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
version = sys.argv[1]
|
||||
url = f"https://pypi.org/pypi/fastmcp-slim/{version}/json"
|
||||
with urllib.request.urlopen(url, timeout=30) as response:
|
||||
json.load(response)
|
||||
PY
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI; refusing to publish fastmcp-tasks." >&2
|
||||
exit 1
|
||||
|
||||
- name: Publish fastmcp-tasks to PyPI
|
||||
if: steps.package_present.outputs.present == 'true'
|
||||
run: uv publish -v dist/fastmcp_tasks-*.tar.gz dist/fastmcp_tasks-*.whl
|
||||
238
.github/workflows/publish-fastmcp.yml
vendored
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
name: Publish fastmcp to PyPI
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Publish fastmcp-slim to PyPI"]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
pypi-publish:
|
||||
name: Upload fastmcp to PyPI
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
|
||||
outputs:
|
||||
is_prerelease: ${{ steps.package_version.outputs.is_prerelease }}
|
||||
version: ${{ steps.package_version.outputs.version }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build fastmcp
|
||||
run: uv build --package fastmcp
|
||||
|
||||
- name: Read built package version
|
||||
id: package_version
|
||||
run: |
|
||||
python - <<'PY' >> "$GITHUB_OUTPUT"
|
||||
import email.parser
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
wheel = next(Path("dist").glob("fastmcp-*.whl"))
|
||||
metadata_name = next(
|
||||
name for name in zipfile.ZipFile(wheel).namelist()
|
||||
if name.endswith(".dist-info/METADATA")
|
||||
)
|
||||
metadata = email.parser.Parser().parsestr(
|
||||
zipfile.ZipFile(wheel).read(metadata_name).decode()
|
||||
)
|
||||
version = metadata["Version"]
|
||||
public_version = version.partition("+")[0]
|
||||
is_prerelease = bool(
|
||||
re.search(
|
||||
r"(?i)(?:^|[0-9.])(?:a|b|c|rc|alpha|beta|pre|preview|dev)[0-9]*",
|
||||
public_version,
|
||||
)
|
||||
)
|
||||
print(f"version={version}")
|
||||
print(f"is_prerelease={str(is_prerelease).lower()}")
|
||||
PY
|
||||
|
||||
- name: Verify matching fastmcp-slim is published
|
||||
run: |
|
||||
SLIM_VERSION=$(python - <<'PY'
|
||||
import email.parser
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
wheel = next(Path("dist").glob("fastmcp-*.whl"))
|
||||
metadata_name = next(
|
||||
name for name in zipfile.ZipFile(wheel).namelist()
|
||||
if name.endswith(".dist-info/METADATA")
|
||||
)
|
||||
metadata = email.parser.Parser().parsestr(
|
||||
zipfile.ZipFile(wheel).read(metadata_name).decode()
|
||||
)
|
||||
for value in metadata.get_all("Requires-Dist", []):
|
||||
requirement, _, marker = value.partition(";")
|
||||
if marker.strip():
|
||||
continue
|
||||
match = re.fullmatch(
|
||||
r"fastmcp-slim(?:\[[^\]]+\])?==([^;\s]+)",
|
||||
requirement.strip(),
|
||||
)
|
||||
if match:
|
||||
print(match.group(1))
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Could not find the base fastmcp-slim dependency")
|
||||
PY
|
||||
)
|
||||
|
||||
for attempt in {1..12}; do
|
||||
if python - "$SLIM_VERSION" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
version = sys.argv[1]
|
||||
url = f"https://pypi.org/pypi/fastmcp-slim/{version}/json"
|
||||
with urllib.request.urlopen(url, timeout=30) as response:
|
||||
json.load(response)
|
||||
PY
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI; refusing to publish fastmcp." >&2
|
||||
exit 1
|
||||
|
||||
- name: Verify matching fastmcp-tasks is published
|
||||
run: |
|
||||
TASKS_VERSION=$(python - <<'PY'
|
||||
import email.parser
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
wheel = next(Path("dist").glob("fastmcp-*.whl"))
|
||||
metadata_name = next(
|
||||
name for name in zipfile.ZipFile(wheel).namelist()
|
||||
if name.endswith(".dist-info/METADATA")
|
||||
)
|
||||
metadata = email.parser.Parser().parsestr(
|
||||
zipfile.ZipFile(wheel).read(metadata_name).decode()
|
||||
)
|
||||
# fastmcp-tasks is pinned via the optional `tasks` extra, so its
|
||||
# Requires-Dist entry carries an `extra == "tasks"` marker — unlike the
|
||||
# base slim dependency, do not skip marked entries here.
|
||||
#
|
||||
# Print nothing when there is no such pin. Release lines that resolve
|
||||
# the `tasks` extra through fastmcp-slim instead of a standalone
|
||||
# fastmcp-tasks package have nothing here to verify.
|
||||
for value in metadata.get_all("Requires-Dist", []):
|
||||
requirement, _, _marker = value.partition(";")
|
||||
match = re.fullmatch(r"fastmcp-tasks==([^;\s]+)", requirement.strip())
|
||||
if match:
|
||||
print(match.group(1))
|
||||
break
|
||||
PY
|
||||
)
|
||||
|
||||
if [ -z "$TASKS_VERSION" ]; then
|
||||
echo "This build does not pin fastmcp-tasks; the [tasks] extra cannot be uninstallable, so there is nothing to verify."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for attempt in {1..12}; do
|
||||
if python - "$TASKS_VERSION" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
version = sys.argv[1]
|
||||
url = f"https://pypi.org/pypi/fastmcp-tasks/{version}/json"
|
||||
with urllib.request.urlopen(url, timeout=30) as response:
|
||||
json.load(response)
|
||||
PY
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "fastmcp-tasks ${TASKS_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
echo "fastmcp-tasks ${TASKS_VERSION} is not available on PyPI; refusing to publish fastmcp (the [tasks] extra would be uninstallable)." >&2
|
||||
exit 1
|
||||
|
||||
- name: Publish fastmcp to PyPI
|
||||
run: uv publish -v dist/fastmcp-*.tar.gz dist/fastmcp-*.whl
|
||||
|
||||
update-published-docs:
|
||||
name: Open published-docs PR
|
||||
runs-on: ubuntu-latest
|
||||
needs: pypi-publish
|
||||
if: github.event_name == 'workflow_run' && github.event.workflow_run.event == 'release' && needs['pypi-publish'].outputs.is_prerelease != 'true'
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.workflow_run.head_sha }}
|
||||
token: ${{ steps.marvin-token.outputs.token }}
|
||||
|
||||
- name: Check release line
|
||||
id: release_line
|
||||
env:
|
||||
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
|
||||
run: |
|
||||
git fetch origin "${DEFAULT_BRANCH}:refs/remotes/origin/${DEFAULT_BRANCH}"
|
||||
if git merge-base --is-ancestor HEAD "refs/remotes/origin/${DEFAULT_BRANCH}"; then
|
||||
echo "update_published_docs=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "update_published_docs=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Release commit is not on ${DEFAULT_BRANCH}; skipping published-docs update."
|
||||
fi
|
||||
|
||||
- name: Prepare published docs tree
|
||||
if: steps.release_line.outputs.update_published_docs == 'true'
|
||||
env:
|
||||
RELEASE_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
run: |
|
||||
git fetch origin published-docs
|
||||
git switch --force-create published-docs-sync origin/published-docs
|
||||
git read-tree --reset -u "$RELEASE_SHA"
|
||||
test "$(git write-tree)" = "$(git rev-parse "${RELEASE_SHA}^{tree}")"
|
||||
|
||||
- name: Open published docs PR
|
||||
if: steps.release_line.outputs.update_published_docs == 'true'
|
||||
uses: peter-evans/create-pull-request@v8
|
||||
with:
|
||||
token: ${{ steps.marvin-token.outputs.token }}
|
||||
base: published-docs
|
||||
branch: marvin/publish-docs-v${{ needs.pypi-publish.outputs.version }}
|
||||
commit-message: "Publish FastMCP v${{ needs.pypi-publish.outputs.version }} docs"
|
||||
title: "Publish FastMCP v${{ needs.pypi-publish.outputs.version }} docs"
|
||||
body: "Updates `published-docs` to the exact release tree. Merging publishes the documentation to production."
|
||||
delete-branch: true
|
||||
author: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
|
||||
committer: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
|
||||
26
.github/workflows/publish.yml
vendored
|
|
@ -1,26 +0,0 @@
|
|||
name: Publish FastMCP to PyPI
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
pypi-publish:
|
||||
name: Upload to PyPI
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write # For PyPI's trusted publishing
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: "Install uv"
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build
|
||||
run: uv build
|
||||
|
||||
- name: Publish to PyPi
|
||||
run: uv publish -v dist/*
|
||||
613
.github/workflows/require-issue-link.yml
vendored
Normal file
|
|
@ -0,0 +1,613 @@
|
|||
# Require external PRs to reference an issue with an auto-close keyword
|
||||
# (e.g. "Fixes #123") AND have the PR author assigned to that issue —
|
||||
# unless the referenced issue is labeled "prs welcome", which waives the
|
||||
# assignment requirement for everyone (the link itself is still required,
|
||||
# since that's how the check finds the issue to read the label from).
|
||||
# Otherwise the PR is labeled "missing-issue-link", commented on, and
|
||||
# closed. CONTRIBUTING.md requires external contributors to be assigned to
|
||||
# an issue before opening a PR; this enforces that.
|
||||
#
|
||||
# Adapted from langchain-ai/langchain's require_issue_link.yml. Differences:
|
||||
# - Self-contained: it does NOT depend on a separate labeler workflow
|
||||
# applying an "external" label first, so it can run on `opened`.
|
||||
# - "External" is determined authoritatively, in-script, from the PR
|
||||
# author's repo collaborator permission level — NOT from the event
|
||||
# payload's author_association. author_association reports MEMBER only
|
||||
# for *public* org members; a maintainer whose org membership is
|
||||
# private appears as CONTRIBUTOR/NONE, so gating on it would wrongly
|
||||
# enforce against private-member maintainers. getCollaboratorPermission
|
||||
# reflects effective write access regardless of membership visibility.
|
||||
# - The enforcement path is a single github-script step (the upstream
|
||||
# version is split across four, forcing the label/comment/reopen helpers
|
||||
# to be duplicated per scope).
|
||||
# - Issue assignment events are handled in this same workflow so assigning
|
||||
# the linked issue reopens previously closed PRs automatically.
|
||||
#
|
||||
# Maintainer override: reopen the PR, or remove the "missing-issue-link"
|
||||
# label — either applies a sticky "bypass-issue-check" label and reopens.
|
||||
|
||||
name: Require Issue Link
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
# SECURITY: pull_request_target runs with repo write scope against the
|
||||
# BASE repo. NEVER check out or execute PR-head code here — it would run
|
||||
# with these permissions. This workflow only reads the PR payload and
|
||||
# calls the API; it never checks anything out.
|
||||
# ready_for_review matters because the job skips drafts: without it a
|
||||
# draft opened with no issue link would never be checked when it later
|
||||
# becomes reviewable.
|
||||
types: [opened, edited, reopened, ready_for_review, labeled, unlabeled]
|
||||
issues:
|
||||
# Assignment is what makes a previously closed "not assigned" PR compliant,
|
||||
# so it needs a separate event path that finds and reopens matching PRs.
|
||||
types: [assigned]
|
||||
|
||||
# Dry run: when 'false' the check still runs and logs its verdict but makes
|
||||
# NO mutations at all (no label, comment, close, reopen, or failure). Flip
|
||||
# to 'true' to enforce.
|
||||
env:
|
||||
ENFORCE_ISSUE_LINK: "true"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-issue-link:
|
||||
# Cheap pre-filters only. Maintainer detection is deliberately NOT done
|
||||
# here: the job-level `if` can't call the API, and author_association is
|
||||
# unreliable for private org members (see file header). The job runs,
|
||||
# then the script resolves the author's real permission and exits early
|
||||
# for maintainers.
|
||||
#
|
||||
# Gate: only run on pull_request_target events. The workflow also listens
|
||||
# to `issues.assigned` (handled by reopen-on-assignment below), and without
|
||||
# this guard the job would also fire there — `github.event.pull_request` is
|
||||
# null on an issues event, so `...draft == false` coerces to true and the
|
||||
# script then dereferences a missing PR and crashes. Beyond the event type,
|
||||
# skip drafts, bots, and already-bypassed/trusted PRs, and allow the primary
|
||||
# actions plus the one maintainer-override action we care about (removing
|
||||
# the missing-issue-link label).
|
||||
if: >-
|
||||
github.event_name == 'pull_request_target' &&
|
||||
github.event.pull_request.draft == false &&
|
||||
!endsWith(github.actor, '[bot]') &&
|
||||
!contains(github.event.pull_request.labels.*.name, 'trusted-contributor') &&
|
||||
!contains(github.event.pull_request.labels.*.name, 'bypass-issue-check') &&
|
||||
(
|
||||
(github.event.action != 'labeled' && github.event.action != 'unlabeled') ||
|
||||
(github.event.action == 'unlabeled' && github.event.label.name == 'missing-issue-link')
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
concurrency:
|
||||
group: require-issue-link-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Enforce issue link
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const pr = context.payload.pull_request;
|
||||
const prNumber = pr.number;
|
||||
const action = context.payload.action;
|
||||
const enforce = process.env.ENFORCE_ISSUE_LINK === 'true';
|
||||
const LABEL = 'missing-issue-link';
|
||||
const MARKER = '<!-- require-issue-link -->';
|
||||
// Issue-level label that waives the assignment requirement.
|
||||
const OPEN_LABEL = 'prs welcome';
|
||||
|
||||
// Dry-run guard: every mutating call goes through this so that
|
||||
// ENFORCE_ISSUE_LINK=false means strictly read-only.
|
||||
async function mutate(description, fn) {
|
||||
if (!enforce) {
|
||||
console.log(`[dry-run] would ${description}`);
|
||||
return;
|
||||
}
|
||||
await fn();
|
||||
}
|
||||
|
||||
// Authoritative maintainer check. Uses collaborator permission,
|
||||
// not org membership or author_association:
|
||||
// - GITHUB_TOKEN is an app token and is never an org member,
|
||||
// so the org-membership endpoint always 403s.
|
||||
// - author_association reports MEMBER only for *public* org
|
||||
// members; a private-member maintainer shows as
|
||||
// CONTRIBUTOR/NONE. Permission level is visibility-
|
||||
// independent and reflects effective access.
|
||||
// 404 (not a collaborator) → not a maintainer. Other errors
|
||||
// (rate limit, 5xx) MUST throw: silently treating them as
|
||||
// "not a maintainer" could wrongly close a maintainer's PR.
|
||||
// A throw aborts the script before any close/label call, so the
|
||||
// job fails red and the PR is left untouched — the safe direction.
|
||||
async function hasWriteAccess(username) {
|
||||
if (!username) throw new Error('No username — cannot check permissions');
|
||||
try {
|
||||
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner, repo, username,
|
||||
});
|
||||
const ok = ['admin', 'maintain', 'write'].includes(data.permission);
|
||||
console.log(`${username}: ${data.permission} — ${ok ? 'maintainer' : 'not a maintainer'}`);
|
||||
return ok;
|
||||
} catch (e) {
|
||||
if (e.status === 404) {
|
||||
console.log(`${username} is not a collaborator — not a maintainer`);
|
||||
return false;
|
||||
}
|
||||
throw new Error(
|
||||
`Permission check failed for ${username} (HTTP ${e.status ?? 'unknown'}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function addLabel() {
|
||||
await mutate(`label PR #${prNumber} "${LABEL}"`, async () => {
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: LABEL });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({ owner, repo, name: LABEL, color: 'b76e79' });
|
||||
} catch (createErr) {
|
||||
// 422 = created by a concurrent run between GET and POST.
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: prNumber, labels: [LABEL],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function minimizeStaleComment() {
|
||||
try {
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const stale = comments.find(c => c.body && c.body.includes(MARKER));
|
||||
if (!stale) return;
|
||||
await mutate(`minimize stale comment ${stale.id}`, () => github.graphql(`
|
||||
mutation($id: ID!) {
|
||||
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
|
||||
minimizedComment { isMinimized }
|
||||
}
|
||||
}
|
||||
`, { id: stale.node_id }));
|
||||
} catch (e) {
|
||||
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared "this PR passes" cleanup: drop the label, reopen, and
|
||||
// retire any stale enforcement comment.
|
||||
//
|
||||
// For the normal pass paths we only reopen if THIS workflow had
|
||||
// closed the PR — inferred from the label still being on the
|
||||
// payload. The maintainer-override paths pass forceReopen: the
|
||||
// `unlabeled` event payload no longer carries the just-removed
|
||||
// label, so the heuristic can't see it; without forcing, the
|
||||
// advertised "remove the label to bypass" gesture would leave
|
||||
// the PR closed.
|
||||
async function clearEnforcement(forceReopen = false) {
|
||||
await mutate(`remove "${LABEL}" from PR #${prNumber}`, async () => {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner, repo, issue_number: prNumber, name: LABEL,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
}
|
||||
});
|
||||
const hadLabel = pr.labels.map(l => l.name).includes(LABEL);
|
||||
if (pr.state === 'closed' && (forceReopen || hadLabel)) {
|
||||
await mutate(`reopen PR #${prNumber}`, async () => {
|
||||
await github.rest.pulls.update({
|
||||
owner, repo, pull_number: prNumber, state: 'open',
|
||||
});
|
||||
});
|
||||
}
|
||||
await minimizeStaleComment();
|
||||
}
|
||||
|
||||
async function applyBypass(reason) {
|
||||
console.log(reason);
|
||||
await clearEnforcement(true);
|
||||
await mutate(`add sticky "bypass-issue-check" to PR #${prNumber}`, async () => {
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: 'bypass-issue-check' });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner, repo, name: 'bypass-issue-check', color: '0e8a16',
|
||||
});
|
||||
} catch (createErr) {
|
||||
if (createErr.status !== 422) throw createErr;
|
||||
}
|
||||
}
|
||||
await github.rest.issues.addLabels({
|
||||
owner, repo, issue_number: prNumber, labels: ['bypass-issue-check'],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ── Maintainer-authored PRs are exempt entirely ────────────────
|
||||
if (await hasWriteAccess(pr.user.login)) {
|
||||
console.log(`PR author ${pr.user.login} has write access — exempt`);
|
||||
await clearEnforcement();
|
||||
return;
|
||||
}
|
||||
|
||||
const sender = context.payload.sender?.login;
|
||||
|
||||
// ── Maintainer override: removed the "missing-issue-link" label ─
|
||||
if (action === 'unlabeled') {
|
||||
if (await hasWriteAccess(sender)) {
|
||||
await applyBypass(`Maintainer ${sender} removed ${LABEL} from PR #${prNumber} — bypassing`);
|
||||
return;
|
||||
}
|
||||
// Only triage/admin can manage labels, so a non-write actor
|
||||
// reaching here is rare (triage role). Fall through to the
|
||||
// normal check, which recomputes link + assignment and
|
||||
// re-enforces with the correct message if still failing.
|
||||
console.log(`Non-maintainer ${sender} removed ${LABEL} — re-checking`);
|
||||
}
|
||||
|
||||
// ── Maintainer override: reopened a PR we had closed ───────────
|
||||
if (
|
||||
action === 'reopened' &&
|
||||
pr.labels.map(l => l.name).includes(LABEL) &&
|
||||
(await hasWriteAccess(sender))
|
||||
) {
|
||||
await applyBypass(`Maintainer ${sender} reopened PR #${prNumber} — bypassing`);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Race guard: re-read live labels ────────────────────────────
|
||||
const { data: liveLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner, repo, issue_number: prNumber,
|
||||
});
|
||||
const liveNames = liveLabels.map(l => l.name);
|
||||
if (liveNames.includes('trusted-contributor') || liveNames.includes('bypass-issue-check')) {
|
||||
console.log('PR carries trusted-contributor or bypass-issue-check — clearing any prior enforcement');
|
||||
await clearEnforcement();
|
||||
return;
|
||||
}
|
||||
|
||||
// ── The actual check: an auto-close keyword + issue number ─────
|
||||
const body = pr.body || '';
|
||||
// Match GitHub's auto-close keywords against any reference form
|
||||
// that GitHub itself honors: bare `#123`, the `owner/repo#123`
|
||||
// shorthand, and the full issue URL. Scope the qualified forms to
|
||||
// THIS repo — GitHub only auto-closes same-repo issues, so a
|
||||
// cross-repo reference must not be resolved against our numbering.
|
||||
const repoRef = `${owner}/${repo}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const pattern = new RegExp(
|
||||
'(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s*:?\\s*' +
|
||||
`(?:${repoRef}#|#|https?://github\\.com/${repoRef}/issues/)(\\d+)`,
|
||||
'gi',
|
||||
);
|
||||
const matches = [...body.matchAll(pattern)];
|
||||
|
||||
if (matches.length === 0) {
|
||||
console.log('No issue link found in PR body');
|
||||
await enforceFailure('no-link');
|
||||
return;
|
||||
}
|
||||
|
||||
// The author must be assigned to at least one linked issue.
|
||||
// CONTRIBUTING.md requires external contributors to be assigned
|
||||
// before opening a PR (so maintainers can deconflict / steer
|
||||
// approach first).
|
||||
//
|
||||
// Exception: an issue labeled OPEN_LABEL waives that requirement
|
||||
// for everyone. It's how maintainers advertise "the reporter
|
||||
// isn't implementing this, we'd take a PR from anyone" without
|
||||
// having to assign a specific person up front. Unlike the
|
||||
// PR-level `trusted-contributor` / `bypass-issue-check` escapes,
|
||||
// this one lives on the *issue* and is set ahead of time.
|
||||
const MAX_ISSUES = 5;
|
||||
const allNumbers = [...new Set(matches.map(m => parseInt(m[1], 10)))];
|
||||
const numbers = allNumbers.slice(0, MAX_ISSUES);
|
||||
if (allNumbers.length > MAX_ISSUES) {
|
||||
core.warning(`PR references ${allNumbers.length} issues — checking only the first ${MAX_ISSUES}`);
|
||||
}
|
||||
|
||||
const prAuthor = pr.user.login.toLowerCase();
|
||||
let sawRealIssue = false;
|
||||
let assignedToAny = false;
|
||||
for (const num of numbers) {
|
||||
let issue;
|
||||
try {
|
||||
({ data: issue } = await github.rest.issues.get({
|
||||
owner, repo, issue_number: num,
|
||||
}));
|
||||
} catch (e) {
|
||||
if (e.status === 404) {
|
||||
console.log(`#${num} does not exist — ignoring`);
|
||||
continue;
|
||||
}
|
||||
// Same safe-direction rule as hasWriteAccess: a transient
|
||||
// error must not be read as "not assigned" and close the PR.
|
||||
throw new Error(`Cannot fetch issue #${num} (HTTP ${e.status ?? 'unknown'}): ${e.message}`);
|
||||
}
|
||||
sawRealIssue = true;
|
||||
|
||||
// GitHub returns labels as objects here, but the REST schema
|
||||
// permits bare strings — normalize both rather than assume.
|
||||
const labelNames = (issue.labels || [])
|
||||
.map(l => (typeof l === 'string' ? l : l && l.name))
|
||||
.filter(Boolean)
|
||||
.map(n => n.toLowerCase());
|
||||
if (labelNames.includes(OPEN_LABEL)) {
|
||||
console.log(`#${num} is labeled "${OPEN_LABEL}" — assignment not required`);
|
||||
assignedToAny = true;
|
||||
break;
|
||||
}
|
||||
|
||||
const assignees = (issue.assignees || []).map(a => a.login.toLowerCase());
|
||||
if (assignees.includes(prAuthor)) {
|
||||
console.log(`PR author ${pr.user.login} is assigned to #${num}`);
|
||||
assignedToAny = true;
|
||||
break;
|
||||
}
|
||||
console.log(`PR author ${pr.user.login} is NOT assigned to #${num} (assignees: ${assignees.join(', ') || 'none'})`);
|
||||
}
|
||||
|
||||
if (!sawRealIssue) {
|
||||
console.log('Referenced issue(s) do not exist');
|
||||
await enforceFailure('no-link');
|
||||
return;
|
||||
}
|
||||
if (!assignedToAny) {
|
||||
await enforceFailure('not-assigned');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Linked and assigned — clearing any prior enforcement');
|
||||
await clearEnforcement();
|
||||
|
||||
// ── Label, comment, close, and fail ────────────────────────────
|
||||
// `kind`: 'no-link' (no valid issue reference) or 'not-assigned'
|
||||
// (referenced an issue, but the author isn't assigned to it).
|
||||
async function enforceFailure(kind) {
|
||||
await addLabel();
|
||||
|
||||
const reason = kind === 'no-link'
|
||||
? "it doesn't reference a tracked issue assigned to you"
|
||||
: "you aren't assigned to the issue it references";
|
||||
const steps = kind === 'no-link'
|
||||
? [
|
||||
`1. Find or [open an issue](https://github.com/${owner}/${repo}/issues/new/choose) describing the change — if you open it, you have first claim on it.`,
|
||||
"2. Add `Fixes #<issue>`, `Closes #<issue>`, or `Resolves #<issue>` to **this** PR's description — edit it in place, don't open a new PR.",
|
||||
]
|
||||
: [
|
||||
"1. If you opened the linked issue, a maintainer will assign you when they pick it up and this PR reopens automatically. If someone else opened it, the PR reopens only if a maintainer chooses to assign it to you — please don't comment to ask.",
|
||||
];
|
||||
|
||||
const commentBody = [
|
||||
MARKER,
|
||||
"**Don't open a new pull request — this one reopens on its own.** It's closed for " +
|
||||
`now because ${reason}, but the moment that's fixed it reopens automatically. Keep this ` +
|
||||
'PR and edit it; opening a fresh duplicate just starts you over and creates more to triage.',
|
||||
'',
|
||||
`Per [CONTRIBUTING.md](https://github.com/${owner}/${repo}/blob/main/CONTRIBUTING.md), an external PR must reference an issue that's assigned to its author. To get there:`,
|
||||
'',
|
||||
...steps,
|
||||
'',
|
||||
"Once you're assigned and the link is present, this PR reopens automatically — no further action needed.",
|
||||
'',
|
||||
`*Maintainers: reopen this PR or remove the \`${LABEL}\` label to bypass this check.*`,
|
||||
].join('\n');
|
||||
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const existing = comments.find(c => c.body && c.body.includes(MARKER));
|
||||
if (!existing) {
|
||||
await mutate(`comment on PR #${prNumber}`, () => github.rest.issues.createComment({
|
||||
owner, repo, issue_number: prNumber, body: commentBody,
|
||||
}));
|
||||
} else if (existing.body !== commentBody) {
|
||||
await mutate(`update comment ${existing.id}`, () => github.rest.issues.updateComment({
|
||||
owner, repo, comment_id: existing.id, body: commentBody,
|
||||
}));
|
||||
} else {
|
||||
console.log('Requirement comment already present — skipping');
|
||||
}
|
||||
|
||||
if (pr.state === 'open') {
|
||||
await mutate(`close PR #${prNumber}`, () => github.rest.pulls.update({
|
||||
owner, repo, pull_number: prNumber, state: 'closed',
|
||||
}));
|
||||
}
|
||||
|
||||
if (enforce) {
|
||||
core.setFailed(
|
||||
kind === 'no-link'
|
||||
? 'PR must reference a tracked issue using an auto-close keyword (e.g. "Fixes #123").'
|
||||
: 'PR author must be assigned to the referenced issue.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
reopen-on-assignment:
|
||||
if: github.event_name == 'issues' && github.event.action == 'assigned' && !github.event.issue.pull_request
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
concurrency:
|
||||
group: reopen-on-assignment-${{ github.event.issue.number }}-${{ github.event.assignee.login }}
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
actions: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Reopen linked PRs
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const issueNumber = context.payload.issue.number;
|
||||
const assignee = context.payload.assignee.login;
|
||||
const enforce = process.env.ENFORCE_ISSUE_LINK === 'true';
|
||||
const LABEL = 'missing-issue-link';
|
||||
const MARKER = '<!-- require-issue-link -->';
|
||||
// Match GitHub's auto-close keywords against any reference form
|
||||
// that GitHub itself honors: bare `#123`, the `owner/repo#123`
|
||||
// shorthand, and the full issue URL. Scope the qualified forms to
|
||||
// THIS repo — GitHub only auto-closes same-repo issues, so a
|
||||
// cross-repo reference must not be resolved against our numbering.
|
||||
const repoRef = `${owner}/${repo}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const pattern = new RegExp(
|
||||
'(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s*:?\\s*' +
|
||||
`(?:${repoRef}#|#|https?://github\\.com/${repoRef}/issues/)(\\d+)`,
|
||||
'gi',
|
||||
);
|
||||
|
||||
async function mutate(description, fn) {
|
||||
if (!enforce) {
|
||||
console.log(`[dry-run] would ${description}`);
|
||||
return;
|
||||
}
|
||||
await fn();
|
||||
}
|
||||
|
||||
console.log(`Issue #${issueNumber} assigned to ${assignee} — searching for closed PRs to reopen`);
|
||||
|
||||
const q = [
|
||||
'is:pr',
|
||||
'is:closed',
|
||||
`author:${assignee}`,
|
||||
`label:${LABEL}`,
|
||||
`repo:${owner}/${repo}`,
|
||||
].join(' ');
|
||||
|
||||
let search;
|
||||
try {
|
||||
({ data: search } = await github.rest.search.issuesAndPullRequests({
|
||||
q,
|
||||
per_page: 30,
|
||||
}));
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Failed to search closed PRs for ${assignee} after assigning #${issueNumber} ` +
|
||||
`(HTTP ${e.status ?? 'unknown'}): ${e.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (search.total_count === 0) {
|
||||
console.log('No matching closed PRs found');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${search.total_count} candidate PR(s)`);
|
||||
|
||||
for (const item of search.items) {
|
||||
const prNumber = item.number;
|
||||
|
||||
let issue;
|
||||
try {
|
||||
({ data: issue } = await github.rest.issues.get({
|
||||
owner, repo, issue_number: prNumber,
|
||||
}));
|
||||
} catch (e) {
|
||||
throw new Error(`Cannot fetch PR #${prNumber} issue data (HTTP ${e.status ?? 'unknown'}): ${e.message}`);
|
||||
}
|
||||
|
||||
const labels = (issue.labels || []).map(label => label.name);
|
||||
if (labels.includes('bypass-issue-check')) {
|
||||
console.log(`PR #${prNumber} already has bypass-issue-check — skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const body = issue.body || '';
|
||||
const referencedIssues = [...body.matchAll(pattern)].map(match => parseInt(match[1], 10));
|
||||
if (!referencedIssues.includes(issueNumber)) {
|
||||
console.log(`PR #${prNumber} does not reference #${issueNumber} — skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await mutate(`reopen PR #${prNumber}`, () => github.rest.pulls.update({
|
||||
owner, repo, pull_number: prNumber, state: 'open',
|
||||
}));
|
||||
} catch (e) {
|
||||
if (e.status === 422) {
|
||||
core.warning(`Cannot reopen PR #${prNumber}: the head branch was likely deleted`);
|
||||
await mutate(`comment on unreopenable PR #${prNumber}`, () => github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
body:
|
||||
`You have been assigned to #${issueNumber}, but this PR could not be ` +
|
||||
'reopened because the head branch has been deleted. Please open a new PR ' +
|
||||
'referencing the issue.',
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
await mutate(`remove "${LABEL}" from PR #${prNumber}`, async () => {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner, repo, issue_number: prNumber, name: LABEL,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const comments = await github.paginate(
|
||||
github.rest.issues.listComments,
|
||||
{ owner, repo, issue_number: prNumber, per_page: 100 },
|
||||
);
|
||||
const stale = comments.find(comment => comment.body && comment.body.includes(MARKER));
|
||||
if (stale) {
|
||||
await mutate(`minimize stale comment ${stale.id}`, () => github.graphql(`
|
||||
mutation($id: ID!) {
|
||||
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
|
||||
minimizedComment { isMinimized }
|
||||
}
|
||||
}
|
||||
`, { id: stale.node_id }));
|
||||
}
|
||||
} catch (e) {
|
||||
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
owner, repo, pull_number: prNumber,
|
||||
});
|
||||
const { data: runs } = await github.rest.actions.listWorkflowRuns({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: 'require-issue-link.yml',
|
||||
head_sha: pr.head.sha,
|
||||
status: 'failure',
|
||||
per_page: 1,
|
||||
});
|
||||
if (runs.workflow_runs.length === 0) {
|
||||
console.log(`No failed require-issue-link runs found for PR #${prNumber}`);
|
||||
continue;
|
||||
}
|
||||
await mutate(`re-run failed require-issue-link run for PR #${prNumber}`, () =>
|
||||
github.rest.actions.reRunWorkflowFailedJobs({
|
||||
owner, repo, run_id: runs.workflow_runs[0].id,
|
||||
}),
|
||||
);
|
||||
} catch (e) {
|
||||
core.warning(`Could not re-run require-issue-link for PR #${prNumber}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
55
.github/workflows/run-schema-crash-test.yml
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
name: Schema Crash Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "fastmcp_slim/fastmcp/utilities/json_schema_type.py"
|
||||
- "fastmcp_slim/fastmcp/utilities/json_schema.py"
|
||||
- "fastmcp_slim/fastmcp/utilities/openapi/**"
|
||||
- "fastmcp_slim/fastmcp/server/providers/openapi/**"
|
||||
- "fastmcp_slim/fastmcp/client/mixins/tools.py"
|
||||
- "tests/utilities/json_schema_type/test_real_world_schemas.py"
|
||||
- ".github/workflows/run-schema-crash-test.yml"
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- "fastmcp_slim/fastmcp/utilities/json_schema_type.py"
|
||||
- "fastmcp_slim/fastmcp/utilities/json_schema.py"
|
||||
- "fastmcp_slim/fastmcp/utilities/openapi/**"
|
||||
- "fastmcp_slim/fastmcp/server/providers/openapi/**"
|
||||
- "fastmcp_slim/fastmcp/client/mixins/tools.py"
|
||||
- "tests/utilities/json_schema_type/test_real_world_schemas.py"
|
||||
- ".github/workflows/run-schema-crash-test.yml"
|
||||
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
schema_crash_test:
|
||||
name: "Real-world schema crash test (232K schemas)"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Set up Python
|
||||
run: uv python install 3.12
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync
|
||||
|
||||
- name: Clone openapi-directory
|
||||
run: git clone --depth 1 https://github.com/APIs-guru/openapi-directory.git /tmp/openapi-directory
|
||||
|
||||
- name: Run schema crash test
|
||||
env:
|
||||
RUN_REAL_WORLD_SCHEMA_TEST: "1"
|
||||
OPENAPI_DIRECTORY_PATH: /tmp/openapi-directory
|
||||
run: uv run pytest tests/utilities/json_schema_type/test_real_world_schemas.py -m integration -v -n auto --timeout-method=thread
|
||||
32
.github/workflows/run-static.yml
vendored
|
|
@ -1,18 +1,18 @@
|
|||
name: Run static analysis
|
||||
|
||||
env:
|
||||
# enable colored output
|
||||
# https://github.com/pytest-dev/pytest/issues/7443
|
||||
PY_COLORS: 1
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "fastmcp_slim/**"
|
||||
- "fastmcp_remote/**"
|
||||
- "tests/**"
|
||||
- "uv.lock"
|
||||
- "examples/**"
|
||||
- "pyproject.toml"
|
||||
- "uv.lock"
|
||||
- ".github/workflows/**"
|
||||
|
||||
# run on all pull requests because these checks are required and will block merges otherwise
|
||||
|
|
@ -26,29 +26,17 @@ permissions:
|
|||
jobs:
|
||||
static_analysis:
|
||||
timeout-minutes: 2
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup uv
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
resolution: locked
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync
|
||||
|
||||
- name: Check lockfile is up to date
|
||||
run: |
|
||||
if ! uv lock --check; then
|
||||
echo "❌ Lockfile is out of date!"
|
||||
echo "To update the lockfile, run 'uv lock'."
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ Lockfile is up to date"
|
||||
- name: Run prek
|
||||
uses: j178/prek-action@v1
|
||||
uses: j178/prek-action@v2
|
||||
env:
|
||||
SKIP: no-commit-to-branch
|
||||
|
|
|
|||
252
.github/workflows/run-tests.yml
vendored
|
|
@ -1,17 +1,17 @@
|
|||
name: Tests
|
||||
|
||||
env:
|
||||
# enable colored output
|
||||
PY_COLORS: 1
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "fastmcp_slim/**"
|
||||
- "fastmcp_remote/**"
|
||||
- "tests/**"
|
||||
- "uv.lock"
|
||||
- "pyproject.toml"
|
||||
- "uv.lock"
|
||||
- ".github/workflows/**"
|
||||
|
||||
# run on all pull requests because these checks are required and will block merges otherwise
|
||||
|
|
@ -24,7 +24,7 @@ permissions:
|
|||
|
||||
jobs:
|
||||
run_tests:
|
||||
name: "Run tests: Python ${{ matrix.python-version }} on ${{ matrix.os }}"
|
||||
name: "Tests: Python ${{ matrix.python-version }} on ${{ matrix.os }}"
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
|
|
@ -37,79 +37,231 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
- name: Setup uv
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
python-version: ${{ matrix.python-version }}
|
||||
resolution: locked
|
||||
|
||||
- name: Install FastMCP
|
||||
# run with upgrade to always test against the latest compatible versions
|
||||
run: uv sync --upgrade
|
||||
- name: Run unit tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
|
||||
- name: Run tests (excluding integration and client_process)
|
||||
run: |
|
||||
if [ "${{ matrix.os }}" == "windows-latest" ]; then
|
||||
uv run pytest --inline-snapshot=disable tests -m "not integration and not client_process"
|
||||
else
|
||||
uv run pytest --inline-snapshot=disable tests -m "not integration and not client_process" --numprocesses auto --maxprocesses 4 --dist worksteal
|
||||
fi
|
||||
shell: bash
|
||||
|
||||
- name: Run client process tests separately
|
||||
run: uv run pytest --inline-snapshot=disable tests -m "client_process" -x
|
||||
- name: Run serial subprocess tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
with:
|
||||
test-type: client_process
|
||||
|
||||
run_tests_lowest_direct:
|
||||
name: "Run tests with lowest-direct dependencies"
|
||||
name: "Tests with lowest-direct dependencies"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
- name: Setup uv (lowest-direct)
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
python-version: "3.10"
|
||||
resolution: lowest-direct
|
||||
|
||||
- name: Install FastMCP with lowest-direct resolution
|
||||
# run with lowest-direct to test against the minimum allowed dependency versions
|
||||
run: uv sync --resolution lowest-direct
|
||||
- name: Run unit tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
|
||||
- name: Run tests (excluding integration and client_process)
|
||||
run: uv run --resolution lowest-direct pytest --inline-snapshot=disable tests -m "not integration and not client_process" --numprocesses auto --maxprocesses 4 --dist worksteal
|
||||
- name: Run serial subprocess tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
with:
|
||||
test-type: client_process
|
||||
|
||||
- name: Run client process tests separately
|
||||
run: uv run --resolution lowest-direct pytest --inline-snapshot=disable tests -m "client_process" -x
|
||||
run_conformance_tests:
|
||||
name: "MCP conformance tests"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup uv
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
resolution: locked
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Run conformance tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
with:
|
||||
test-type: conformance
|
||||
|
||||
run_integration_tests:
|
||||
name: "Run integration tests"
|
||||
name: "Integration tests"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
- name: Setup uv
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
python-version: "3.10"
|
||||
|
||||
- name: Install FastMCP
|
||||
# run with upgrade to always test against the latest compatible versions
|
||||
run: uv sync --upgrade
|
||||
resolution: locked
|
||||
|
||||
- name: Run integration tests
|
||||
# use longer per-test timeout for remote API calls (default is 5s)
|
||||
run: uv run pytest tests -m "integration" --timeout=30 --numprocesses auto --maxprocesses 2 --dist worksteal
|
||||
uses: ./.github/actions/run-pytest
|
||||
with:
|
||||
test-type: integration
|
||||
env:
|
||||
FASTMCP_GITHUB_TOKEN: ${{ secrets.FASTMCP_GITHUB_TOKEN }}
|
||||
FASTMCP_TEST_AUTH_GITHUB_CLIENT_ID: ${{ secrets.FASTMCP_TEST_AUTH_GITHUB_CLIENT_ID }}
|
||||
FASTMCP_TEST_AUTH_GITHUB_CLIENT_SECRET: ${{ secrets.FASTMCP_TEST_AUTH_GITHUB_CLIENT_SECRET }}
|
||||
|
||||
package_install_smoke:
|
||||
name: "Package install smoke"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup uv
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
resolution: locked
|
||||
|
||||
- name: Build package wheels
|
||||
run: uv build --all-packages --wheel --out-dir /tmp/fastmcp-dist
|
||||
|
||||
- name: Install bare slim wheel
|
||||
run: |
|
||||
uv venv /tmp/fastmcp-slim-bare-smoke
|
||||
SLIM_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_slim-*.whl)
|
||||
uv pip install --python /tmp/fastmcp-slim-bare-smoke/bin/python "$SLIM_WHEEL"
|
||||
/tmp/fastmcp-slim-bare-smoke/bin/python - <<'PY'
|
||||
from importlib.metadata import entry_points
|
||||
|
||||
import fastmcp
|
||||
import fastmcp.settings
|
||||
|
||||
assert any(ep.name == "fastmcp" for ep in entry_points(group="console_scripts"))
|
||||
|
||||
try:
|
||||
from fastmcp.cli import app
|
||||
except ImportError as exc:
|
||||
assert "FastMCP CLI support is not installed" in str(exc)
|
||||
else:
|
||||
raise AssertionError(f"bare fastmcp-slim unexpectedly imported CLI app {app!r}")
|
||||
|
||||
try:
|
||||
fastmcp.FastMCP
|
||||
except ImportError as exc:
|
||||
assert "fastmcp-slim[server]" in str(exc)
|
||||
else:
|
||||
raise AssertionError("bare fastmcp-slim unexpectedly imported FastMCP")
|
||||
PY
|
||||
|
||||
- name: Install client slim wheel
|
||||
run: |
|
||||
uv venv /tmp/fastmcp-slim-client-smoke
|
||||
SLIM_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_slim-*.whl)
|
||||
uv pip install --python /tmp/fastmcp-slim-client-smoke/bin/python "${SLIM_WHEEL}[client]"
|
||||
/tmp/fastmcp-slim-client-smoke/bin/python - <<'PY'
|
||||
from importlib.metadata import entry_points
|
||||
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.transports import StdioTransport, StreamableHttpTransport
|
||||
from fastmcp.mcp_config import MCPConfig
|
||||
|
||||
assert any(ep.name == "fastmcp" for ep in entry_points(group="console_scripts"))
|
||||
|
||||
try:
|
||||
from fastmcp.cli import app
|
||||
except ImportError as exc:
|
||||
assert "FastMCP CLI support is not installed" in str(exc)
|
||||
else:
|
||||
raise AssertionError(f"client-only slim unexpectedly imported CLI app {app!r}")
|
||||
|
||||
assert Client("https://example.com/mcp")
|
||||
assert StreamableHttpTransport("https://example.com/mcp")
|
||||
assert StdioTransport(command="uvx", args=["demo"])
|
||||
assert MCPConfig.from_dict({"mcpServers": {"demo": {"url": "https://example.com/mcp"}}})
|
||||
|
||||
try:
|
||||
from fastmcp import FastMCP
|
||||
except ImportError as exc:
|
||||
assert "fastmcp-slim[server]" in str(exc)
|
||||
else:
|
||||
raise AssertionError(f"client-only slim unexpectedly imported {FastMCP!r}")
|
||||
PY
|
||||
|
||||
- name: Install server slim wheel
|
||||
run: |
|
||||
uv venv /tmp/fastmcp-slim-server-smoke
|
||||
SLIM_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_slim-*.whl)
|
||||
uv pip install --python /tmp/fastmcp-slim-server-smoke/bin/python "${SLIM_WHEEL}[server]"
|
||||
/tmp/fastmcp-slim-server-smoke/bin/python - <<'PY'
|
||||
from importlib.metadata import entry_points
|
||||
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.cli import app
|
||||
|
||||
assert any(
|
||||
ep.name == "fastmcp" and ep.value == "fastmcp.cli:app"
|
||||
for ep in entry_points(group="console_scripts")
|
||||
)
|
||||
|
||||
mcp = FastMCP("smoke")
|
||||
assert app is not None
|
||||
assert mcp.name == "smoke"
|
||||
PY
|
||||
|
||||
- name: Install full package from matching local wheels
|
||||
run: |
|
||||
uv venv /tmp/fastmcp-full-smoke
|
||||
FULL_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp-*.whl)
|
||||
uv pip install --python /tmp/fastmcp-full-smoke/bin/python --prerelease=allow --find-links /tmp/fastmcp-dist "$FULL_WHEEL"
|
||||
/tmp/fastmcp-full-smoke/bin/python - <<'PY'
|
||||
from importlib.metadata import entry_points
|
||||
from importlib.metadata import requires
|
||||
|
||||
from fastmcp import Client, FastMCP
|
||||
from fastmcp.client.client import CallToolResult
|
||||
from fastmcp.exceptions import ToolError
|
||||
|
||||
fastmcp_reqs = requires("fastmcp") or []
|
||||
assert any("fastmcp-slim[client,server]" in req for req in fastmcp_reqs)
|
||||
assert not any("fastmcp-slim[full" in req for req in fastmcp_reqs)
|
||||
|
||||
assert any(
|
||||
ep.name == "fastmcp" and ep.value == "fastmcp.cli:app"
|
||||
for ep in entry_points(group="console_scripts")
|
||||
)
|
||||
|
||||
assert Client("https://example.com/mcp")
|
||||
assert FastMCP("smoke").name == "smoke"
|
||||
assert CallToolResult is not None
|
||||
assert ToolError is not None
|
||||
PY
|
||||
|
||||
- name: Install fastmcp-remote from matching local wheels
|
||||
run: |
|
||||
uv venv /tmp/fastmcp-remote-smoke
|
||||
REMOTE_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_remote-*.whl)
|
||||
uv pip install --python /tmp/fastmcp-remote-smoke/bin/python --prerelease=allow --find-links /tmp/fastmcp-dist "$REMOTE_WHEEL"
|
||||
/tmp/fastmcp-remote-smoke/bin/python - <<'PY'
|
||||
from importlib.metadata import entry_points
|
||||
from importlib.metadata import requires
|
||||
|
||||
from fastmcp_remote.cli import build_parser
|
||||
|
||||
remote_reqs = requires("fastmcp-remote") or []
|
||||
assert any("fastmcp-slim[client,server]" in req for req in remote_reqs)
|
||||
assert any(
|
||||
ep.name == "fastmcp-remote" and ep.value == "fastmcp_remote.cli:main"
|
||||
for ep in entry_points(group="console_scripts")
|
||||
)
|
||||
assert build_parser().prog == "fastmcp-remote"
|
||||
PY
|
||||
|
|
|
|||
157
.github/workflows/run-upgrade-checks.yml
vendored
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
name: Upgrade checks
|
||||
|
||||
env:
|
||||
PY_COLORS: 1
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "fastmcp_slim/**"
|
||||
- "tests/**"
|
||||
- "pyproject.toml"
|
||||
- "uv.lock"
|
||||
- ".github/workflows/**"
|
||||
|
||||
schedule:
|
||||
# Run daily at 2 AM UTC
|
||||
- cron: "0 2 * * *"
|
||||
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
static_analysis:
|
||||
name: Static analysis
|
||||
timeout-minutes: 2
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup uv (upgrade)
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
resolution: upgrade
|
||||
|
||||
- name: Run prek
|
||||
uses: j178/prek-action@v2
|
||||
env:
|
||||
SKIP: no-commit-to-branch
|
||||
|
||||
run_tests:
|
||||
name: "Tests: Python ${{ matrix.python-version }} on ${{ matrix.os }}"
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
python-version: ["3.10"]
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
python-version: "3.13"
|
||||
fail-fast: false
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup uv (upgrade)
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
resolution: upgrade
|
||||
|
||||
- name: Run unit tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
|
||||
- name: Run serial subprocess tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
with:
|
||||
test-type: client_process
|
||||
|
||||
run_integration_tests:
|
||||
name: "Integration tests"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup uv (upgrade)
|
||||
uses: ./.github/actions/setup-uv
|
||||
with:
|
||||
resolution: upgrade
|
||||
|
||||
- name: Run integration tests
|
||||
uses: ./.github/actions/run-pytest
|
||||
with:
|
||||
test-type: integration
|
||||
env:
|
||||
FASTMCP_GITHUB_TOKEN: ${{ secrets.FASTMCP_GITHUB_TOKEN }}
|
||||
FASTMCP_TEST_AUTH_GITHUB_CLIENT_ID: ${{ secrets.FASTMCP_TEST_AUTH_GITHUB_CLIENT_ID }}
|
||||
FASTMCP_TEST_AUTH_GITHUB_CLIENT_SECRET: ${{ secrets.FASTMCP_TEST_AUTH_GITHUB_CLIENT_SECRET }}
|
||||
|
||||
notify:
|
||||
name: Notify on failure
|
||||
needs: [static_analysis, run_tests, run_integration_tests]
|
||||
if: failure() && github.event.pull_request == null
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Create or update failure issue
|
||||
uses: jayqi/failed-build-issue-action@v1
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
label: "build failed"
|
||||
title-template: "Upgrade checks failing on main branch"
|
||||
body-template: |
|
||||
## Upgrade Checks Failure on Main Branch
|
||||
|
||||
The upgrade checks workflow has failed on the main branch.
|
||||
|
||||
**Workflow Run**: [#{{runNumber}}]({{serverUrl}}/{{repo.owner}}/{{repo.repo}}/actions/runs/{{runId}})
|
||||
**Commit**: {{sha}}
|
||||
**Branch**: {{ref}}
|
||||
**Event**: {{eventName}}
|
||||
|
||||
### Common causes
|
||||
|
||||
- **ty (type checker)**: New ty releases frequently add stricter checks that flag previously-accepted code. Run `uv run ty check` locally with the latest ty to reproduce. Fix the type errors or bump the ty version floor in `pyproject.toml`.
|
||||
- **ruff**: New lint rules or stricter defaults in a ruff upgrade.
|
||||
- **MCP SDK**: Breaking changes in the `mcp` package (new method signatures, renamed types).
|
||||
|
||||
### What to do
|
||||
|
||||
1. Check the workflow logs to identify which job failed (static analysis vs tests)
|
||||
2. Reproduce locally with `uv sync --upgrade && uv run prek run --all-files && uv run pytest -n auto`
|
||||
3. Fix the code or adjust dependency constraints as needed
|
||||
|
||||
---
|
||||
*This issue was automatically created by a GitHub Action.*
|
||||
|
||||
close-on-success:
|
||||
name: Close issue on success
|
||||
needs: [static_analysis, run_tests, run_integration_tests]
|
||||
if: success() && github.event.pull_request == null && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Close resolved failure issue
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
issue=$(gh issue list \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--label "build failed" \
|
||||
--state open \
|
||||
--json number \
|
||||
--jq '.[0].number // empty')
|
||||
|
||||
if [ -n "$issue" ]; then
|
||||
gh issue close "$issue" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--comment "Upgrade checks are passing again as of [\`${GITHUB_SHA::7}\`](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/commit/${GITHUB_SHA})."
|
||||
fi
|
||||
43
.github/workflows/update-config-schema.yml
vendored
|
|
@ -1,14 +1,14 @@
|
|||
name: Update MCPServerConfig Schema
|
||||
|
||||
# This workflow runs on merges to main to automatically update the config schema
|
||||
# by creating a PR when changes are needed.
|
||||
# Regenerates config schema on pushes to main and opens a long-lived PR
|
||||
# with the changes, so contributor PRs stay clean.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "src/fastmcp/utilities/mcp_server_config/**"
|
||||
- "!src/fastmcp/utilities/mcp_server_config/v1/schema.json" # Exclude the local schema file
|
||||
- "fastmcp_slim/fastmcp/utilities/mcp_server_config/**"
|
||||
- "!fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/schema.json"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
|
@ -21,15 +21,17 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
token: ${{ steps.marvin-token.outputs.token }}
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
|
|
@ -41,27 +43,11 @@ jobs:
|
|||
|
||||
- name: Generate config schema
|
||||
run: |
|
||||
echo "🔄 Generating fastmcp.json schema..."
|
||||
|
||||
# Generate schema in docs/public for web access
|
||||
uv run python -c "
|
||||
from fastmcp.utilities.mcp_server_config import generate_schema
|
||||
generate_schema('docs/public/schemas/fastmcp.json/latest.json')
|
||||
print('✅ Latest schema generated in docs/public')
|
||||
"
|
||||
|
||||
# Also update the v1 schema in docs/public
|
||||
uv run python -c "
|
||||
from fastmcp.utilities.mcp_server_config import generate_schema
|
||||
generate_schema('docs/public/schemas/fastmcp.json/v1.json')
|
||||
print('✅ v1 schema generated in docs/public')
|
||||
"
|
||||
|
||||
# Generate schema in the source directory for local development
|
||||
uv run python -c "
|
||||
from fastmcp.utilities.mcp_server_config import generate_schema
|
||||
generate_schema('src/fastmcp/utilities/mcp_server_config/v1/schema.json')
|
||||
print('✅ Schema generated in utilities/mcp_server_config/v1/')
|
||||
generate_schema('fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/schema.json')
|
||||
"
|
||||
|
||||
- name: Create Pull Request
|
||||
|
|
@ -73,9 +59,9 @@ jobs:
|
|||
body: |
|
||||
This PR updates the fastmcp.json schema files to match the current source code.
|
||||
|
||||
The schema is automatically generated from `src/fastmcp/utilities/mcp_server_config/` to ensure consistency.
|
||||
The schema is automatically generated from `fastmcp_slim/fastmcp/utilities/mcp_server_config/` to ensure consistency.
|
||||
|
||||
**Note:** This PR is fully automated and will update itself with any subsequent changes to the schema, or close automatically if the schema becomes up-to-date through other means. Feel free to leave it open until you're ready to merge.
|
||||
**Note:** This PR is fully automated and will update itself with any subsequent changes to the schema, or close automatically if the schema becomes up-to-date through other means.
|
||||
|
||||
🤖 Generated by Marvin
|
||||
branch: marvin/update-config-schema
|
||||
|
|
@ -84,8 +70,3 @@ jobs:
|
|||
delete-branch: true
|
||||
author: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
|
||||
committer: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
echo "✅ Config schema generation workflow completed"
|
||||
echo "PR will be created if there are changes, or closed if schema is already up to date"
|
||||
|
|
|
|||
25
.github/workflows/update-sdk-docs.yml
vendored
|
|
@ -1,13 +1,13 @@
|
|||
name: Update SDK Documentation
|
||||
|
||||
# This workflow runs on merges to main to automatically update SDK docs
|
||||
# by creating a PR when changes are needed.
|
||||
# Regenerates SDK docs on pushes to main and opens a long-lived PR
|
||||
# with the changes, so contributor PRs stay clean.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "fastmcp_slim/**"
|
||||
- "pyproject.toml"
|
||||
workflow_dispatch:
|
||||
|
||||
|
|
@ -21,15 +21,17 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Generate Marvin App token
|
||||
id: marvin-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
uses: actions/create-github-app-token@v3
|
||||
with:
|
||||
app-id: ${{ secrets.MARVIN_APP_ID }}
|
||||
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
token: ${{ steps.marvin-token.outputs.token }}
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
|
|
@ -40,12 +42,10 @@ jobs:
|
|||
run: uv sync --python 3.12
|
||||
|
||||
- name: Install just
|
||||
uses: extractions/setup-just@v3
|
||||
uses: extractions/setup-just@v4
|
||||
|
||||
- name: Generate SDK documentation
|
||||
run: |
|
||||
echo "🔄 Generating SDK documentation..."
|
||||
just api-ref-all
|
||||
run: just api-ref-all
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v8
|
||||
|
|
@ -67,8 +67,3 @@ jobs:
|
|||
delete-branch: true
|
||||
author: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
|
||||
committer: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
echo "✅ SDK documentation generation workflow completed"
|
||||
echo "PR will be created if there are changes, or closed if documentation is already up to date"
|
||||
|
|
|
|||
2
.gitignore
vendored
|
|
@ -65,11 +65,13 @@ dmypy.json
|
|||
|
||||
# Claude worktree management
|
||||
.claude-wt/worktrees
|
||||
.claude/worktrees/
|
||||
|
||||
# Agents
|
||||
/PLAN.md
|
||||
/TODO.md
|
||||
/STATUS.md
|
||||
plans/
|
||||
|
||||
# Common FastMCP test files
|
||||
/test.py
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ repos:
|
|||
hooks:
|
||||
- id: validate-pyproject
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v3.1.0
|
||||
- repo: https://github.com/rbubley/mirrors-prettier
|
||||
rev: v3.8.4
|
||||
hooks:
|
||||
- id: prettier
|
||||
types_or: [yaml, json5]
|
||||
|
|
@ -29,7 +29,7 @@ repos:
|
|||
entry: uv run --isolated ty check
|
||||
language: system
|
||||
types: [python]
|
||||
files: ^src/|^tests/
|
||||
files: ^fastmcp_slim/|^tests/|^examples/
|
||||
pass_filenames: false
|
||||
require_serial: true
|
||||
|
||||
|
|
|
|||
114
AGENTS.md
|
|
@ -1,114 +0,0 @@
|
|||
# FastMCP Development Guidelines
|
||||
|
||||
> **Audience**: LLM-driven engineering agents and human developers
|
||||
|
||||
FastMCP is a comprehensive Python framework (Python ≥3.10) for building Model Context Protocol (MCP) servers and clients. This is the actively maintained v2.0 providing a complete toolkit for the MCP ecosystem.
|
||||
|
||||
## Required Development Workflow
|
||||
|
||||
**CRITICAL**: Always run these commands in sequence before committing.
|
||||
|
||||
```bash
|
||||
uv sync # Install dependencies
|
||||
uv run pytest -n auto # Run full test suite
|
||||
```
|
||||
|
||||
In addition, you must pass static checks. This is generally done as a pre-commit hook with `prek` but you can run it manually with:
|
||||
|
||||
```bash
|
||||
uv run prek run --all-files # Ruff + Prettier + ty
|
||||
```
|
||||
|
||||
**Tests must pass and lint/typing must be clean before committing.**
|
||||
|
||||
## Repository Structure
|
||||
|
||||
| Path | Purpose |
|
||||
| ----------------- | -------------------------------------- |
|
||||
| `src/fastmcp/` | Library source code |
|
||||
| `├─server/` | Server implementation |
|
||||
| `│ ├─auth/` | Authentication providers |
|
||||
| `│ └─middleware/` | Error handling, logging, rate limiting |
|
||||
| `├─client/` | Client SDK |
|
||||
| `│ └─auth/` | Client authentication |
|
||||
| `├─tools/` | Tool definitions |
|
||||
| `├─resources/` | Resources and resource templates |
|
||||
| `├─prompts/` | Prompt templates |
|
||||
| `├─cli/` | CLI commands |
|
||||
| `└─utilities/` | Shared utilities |
|
||||
| `tests/` | Pytest suite |
|
||||
| `docs/` | Mintlify docs (gofastmcp.com) |
|
||||
|
||||
## Core MCP Objects
|
||||
|
||||
When modifying MCP functionality, changes typically need to be applied across all object types:
|
||||
|
||||
- **Tools** (`src/tools/`)
|
||||
- **Resources** (`src/resources/`)
|
||||
- **Resource Templates** (`src/resources/`)
|
||||
- **Prompts** (`src/prompts/`)
|
||||
|
||||
## Development Rules
|
||||
|
||||
### Git & CI
|
||||
|
||||
- Prek hooks are required (run automatically on commits)
|
||||
- Never amend commits to fix prek failures
|
||||
- Apply PR labels: bugs/breaking/enhancements/features
|
||||
- Improvements = enhancements (not features) unless specified
|
||||
- **NEVER** force-push on collaborative repos
|
||||
- **ALWAYS** run prek before PRs
|
||||
- **NEVER** create a release, comment on an issue, or open a PR unless specifically instructed to do so.
|
||||
|
||||
### Commit Messages and Agent Attribution
|
||||
|
||||
- **Agents NOT acting on behalf of @jlowin MUST identify themselves** (e.g., "🤖 Generated with Claude Code" in commits/PRs)
|
||||
- Keep commit messages brief - ideally just headlines, not detailed messages
|
||||
- Focus on what changed, not how or why
|
||||
- Always read issue comments for follow-up information (treat maintainers as authoritative)
|
||||
|
||||
### PR Messages - Required Structure
|
||||
|
||||
- 1-2 paragraphs: problem/tension + solution (PRs are documentation!)
|
||||
- Focused code example showing key capability
|
||||
- **Avoid:** bullet summaries, exhaustive change lists, verbose closes/fixes, marketing language
|
||||
- **Do:** Be opinionated about why change matters, show before/after scenarios
|
||||
- Minor fixes: keep body short and concise
|
||||
- No "test plan" sections or testing summaries
|
||||
|
||||
### Code Standards
|
||||
|
||||
- Python ≥ 3.10 with full type annotations
|
||||
- Follow existing patterns and maintain consistency
|
||||
- **Prioritize readable, understandable code** - clarity over cleverness
|
||||
- Avoid obfuscated or confusing patterns even if they're shorter
|
||||
- Each feature needs corresponding tests
|
||||
|
||||
### Module Exports
|
||||
|
||||
- **Be intentional about re-exports** - don't blindly re-export everything to parent namespaces
|
||||
- Core types that define a module's purpose should be exported (e.g., `Middleware` from `fastmcp.server.middleware`)
|
||||
- Specialized features can live in submodules (e.g., `fastmcp.server.middleware.dynamic`)
|
||||
- Only re-export to `fastmcp.*` for the most fundamental types (e.g., `FastMCP`, `Client`)
|
||||
- When in doubt, prefer users importing from the specific submodule over re-exporting
|
||||
|
||||
### Documentation
|
||||
|
||||
- Uses Mintlify framework
|
||||
- Files must be in docs.json to be included
|
||||
- Never modify `docs/python-sdk/**` (auto-generated)
|
||||
- **Core Principle:** A feature doesn't exist unless it is documented!
|
||||
|
||||
### Documentation Guidelines
|
||||
|
||||
- **Code Examples:** Explain before showing code, make blocks fully runnable (include imports)
|
||||
- **Structure:** Headers form navigation guide, logical H2/H3 hierarchy
|
||||
- **Content:** User-focused sections, motivate features (why) before mechanics (how)
|
||||
- **Style:** Prose over code comments for important information
|
||||
|
||||
## Critical Patterns
|
||||
|
||||
- Never use bare `except` - be specific with exception types
|
||||
- File sizes enforced by [loq](https://github.com/jlowin/loq). Edit `loq.toml` to raise limits; `loq baseline` to ratchet down.
|
||||
- Always `uv sync` first when debugging build issues
|
||||
- Default test timeout is 5s - optimize or mark as integration tests
|
||||
1
AGENTS.md
Symbolic link
|
|
@ -0,0 +1 @@
|
|||
CLAUDE.md
|
||||
|
|
@ -1 +0,0 @@
|
|||
AGENTS.md
|
||||
210
CLAUDE.md
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
# FastMCP Development Guidelines
|
||||
|
||||
> **Audience**: LLM-driven engineering agents and human developers
|
||||
|
||||
> **Note**: `AGENTS.md` is a symlink to this file. Edit `CLAUDE.md` directly.
|
||||
|
||||
FastMCP is a comprehensive Python framework (Python ≥3.10) for building Model Context Protocol (MCP) servers and clients. This is the actively maintained v2.0 providing a complete toolkit for the MCP ecosystem.
|
||||
|
||||
## Required Development Workflow
|
||||
|
||||
**CRITICAL**: Always run these commands in sequence before committing.
|
||||
|
||||
```bash
|
||||
uv sync # Install dependencies
|
||||
uv run pytest -n auto # Run full test suite
|
||||
```
|
||||
|
||||
In addition, you must pass static checks. This is generally done as a pre-commit hook with `prek` but you can run it manually with:
|
||||
|
||||
```bash
|
||||
uv run prek run --all-files # Ruff + Prettier + ty
|
||||
```
|
||||
|
||||
**Tests must pass and lint/typing must be clean before committing.**
|
||||
|
||||
## Repository Structure
|
||||
|
||||
| Path | Purpose |
|
||||
| ----------------- | -------------------------------------- |
|
||||
| `fastmcp_slim/fastmcp/` | Library source code |
|
||||
| `├─server/` | Server implementation |
|
||||
| `│ ├─auth/` | Authentication providers |
|
||||
| `│ └─middleware/` | Error handling, logging, rate limiting |
|
||||
| `├─client/` | Client SDK |
|
||||
| `│ └─auth/` | Client authentication |
|
||||
| `├─tools/` | Tool definitions |
|
||||
| `├─resources/` | Resources and resource templates |
|
||||
| `├─prompts/` | Prompt templates |
|
||||
| `├─cli/` | CLI commands |
|
||||
| `└─utilities/` | Shared utilities |
|
||||
| `tests/` | Pytest suite |
|
||||
| `docs/` | Mintlify docs (gofastmcp.com) |
|
||||
|
||||
## Core MCP Objects
|
||||
|
||||
When modifying MCP functionality, changes typically need to be applied across all object types:
|
||||
|
||||
- **Tools** (`src/tools/`)
|
||||
- **Resources** (`src/resources/`)
|
||||
- **Resource Templates** (`src/resources/`)
|
||||
- **Prompts** (`src/prompts/`)
|
||||
|
||||
**Before writing cross-component logic (dedupe, grouping, lookups, identity checks), read `FastMCPComponent` in `fastmcp_slim/fastmcp/utilities/components.py`.** The base class defines the shared surface — `name`, `version`, `tags`, `meta`, and critically the `key` property which is the canonical MCP identity (encodes type, identifier, and version). Prefer `item.key` over ad-hoc `name or uri or uri_template` fallbacks; overrides in `Resource` and `ResourceTemplate` already handle URI-based identity, and `.key` includes the version suffix so variants of the same component don't falsely collide.
|
||||
|
||||
## Development Rules
|
||||
|
||||
**Read `CONTRIBUTING.md` before opening issues or PRs.** It describes when PRs are appropriate, what we expect from enhancement proposals, and what we'll close without review.
|
||||
|
||||
**Review closed contributor PRs.** When reviewing an issue, inspect every associated non-maintainer PR, including closed PRs. External PRs may be closed as part of the issue-link and assignment workflow, so closure alone is not a negative signal. Read `CONTRIBUTING.md` and the PR timeline and comments to understand its status before evaluating it.
|
||||
|
||||
### Git & CI
|
||||
|
||||
- Prek hooks are required (run automatically on commits)
|
||||
- Never amend commits to fix prek failures
|
||||
- Never apply labels manually or invent new ones — issues and PRs are auto-labeled by a bot based on title/body/code changes. Don't note a "suggested" or "appropriate" label anywhere in the PR body either. See the review-pr skill.
|
||||
- Improvements = enhancements (not features) unless specified
|
||||
- **NEVER** force-push on collaborative repos
|
||||
- **ALWAYS** run prek before PRs
|
||||
- **NEVER** create a release, comment on an issue, or open a PR unless specifically instructed to do so.
|
||||
- **NEVER** merge a PR marked as do-not-merge or draft. Check title, body, AND labels for `[DNM]`, `DNM`, `DO NOT MERGE`, `DON'T MERGE`, `DONT MERGE`, `do-not-merge`, `dont-merge`, `[DRAFT]`, or `DRAFT` (case-insensitive, any variation — some authors use `[DRAFT]` in the title even when `isDraft` is false). Authors use these as hard stops — respect them even if CI is green and review looks clean. When triaging a batch of PRs, filter these out up front AND re-check each one's labels immediately before merging, since labels can change mid-session.
|
||||
- **ALWAYS** read review-bot comments before approving a PR. CodeRabbit and chatgpt-codex-connector (Codex) leave substantive review comments on most PRs in this repo — these bots have read the diff and often flag real issues that aren't in the PR description. Use `gh pr view <num> --comments` and read the bot feedback as part of review. Unlike proposed solutions from issue reporters, review-bot feedback should be evaluated on its merits, not discounted.
|
||||
- **Be constructively skeptical of bot review comments on your own PRs.** CodeRabbit, Codex, and claude[bot] run a fresh review pass on every push, which means a PR with active churn can accumulate bot comments in a stream that never really ends — each fix surfaces a new edge case the next pass can flag. Most of the early feedback is real and worth acting on; diminishing returns set in fast. Evaluate each comment on its merits, the same way you would a human reviewer: is this a real bug users will hit, or a hypothetical that requires an adversarial setup? Does the fix introduce more complexity than the problem? Has the bot missed context that's obvious to a human reader (a `*,` keyword-only marker, a design decision documented elsewhere, something already resolved on a later commit)? When a comment is pedantic, a false positive, or flagging something already fixed, reply on the thread explaining the reasoning and move on — don't keep iterating just because more comments arrive. If you find yourself three rounds deep and the feedback is shifting toward "what if someone does X" hypotheticals, you're past the point where each fix is improving the PR. Stop, document the contract as-is, and ship.
|
||||
- **Resolve a review thread when you fix it; reply when you're declining it.** A fix explains itself through the commit, so resolving is enough — and it leaves unresolved threads meaning unfinished business, which is the signal worth having. A decline needs a one-line reason in a reply, because resolving collapses the thread and a hidden objection is worse than a visible one. Doing both is noise. Get thread ids from the GraphQL `reviewThreads` field, then resolve:
|
||||
|
||||
```bash
|
||||
gh api graphql -f query='query($n:Int!){repository(owner:"PrefectHQ",name:"fastmcp"){pullRequest(number:$n){reviewThreads(first:50){nodes{id isResolved path}}}}}' -F n=<pr-number>
|
||||
gh api graphql -f query='mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{isResolved}}}' -F id=PRRT_...
|
||||
```
|
||||
|
||||
### Outbound Comments and Shell Interpolation
|
||||
|
||||
- Never pass GitHub, Linear, or Slack comment bodies inline through shell arguments when the body contains `$`, `${...}`, backticks, `$(...)`, environment-variable examples, secrets, or config interpolation examples.
|
||||
- Use a body file or structured API payload for outbound comments, then inspect the exact outgoing text before posting. Prefer `gh ... --body-file /path/to/comment.md` over `--body "..."`.
|
||||
- When explaining environment interpolation, use placeholders and fenced code blocks. Never include raw `.env` contents in outbound comments.
|
||||
|
||||
### Releases
|
||||
|
||||
Only cut releases when the maintainer explicitly asks. Tags follow `v<version>` (e.g., `v3.2.0`). Always pass `--generate-notes` so the auto-generated changelog appears at the bottom.
|
||||
|
||||
**The title pun is critical.** Titles follow `v<version>: <pun>` where the pun relates to the most important theme of the release. Propose multiple options and let the maintainer choose — never pick one yourself. Look at recent releases for tone (e.g., "Code to Joy" for the code mode release, "Three at Last" for 3.0).
|
||||
|
||||
Write the maintainer-approved handwritten notes to a temporary file, then create the release. `--generate-notes` appends the auto-generated changelog after the handwritten content.
|
||||
|
||||
```bash
|
||||
gh release create v4.0.0 --target main --title "v4.0.0: Theme Here" --generate-notes --notes-start-tag v3.4.4 --notes-file /tmp/release-notes.md
|
||||
```
|
||||
|
||||
**Always pass `--notes-start-tag <last-stable-tag>`.** Without it, `--generate-notes` picks the most recent prior tag as the changelog start point — and if a prerelease exists (e.g. `v3.4.0b1`), it starts from *that*, silently truncating the PR list to only the commits since the beta. Pin it to the last stable release (e.g. `v3.3.1` when cutting `v3.4.0`). Verify after: the compare link at the bottom of the generated notes should read `v<last-stable>...v<new>`.
|
||||
|
||||
Use the branch that owns the release line as the target: current-major releases target `main`, 3.x maintenance releases target `release/3.x`, and 2.x maintenance releases target `release/2.x`. Confirm the target with the maintainer if there's any ambiguity. For example, cut a 3.4.4 maintenance release with `--target release/3.x`, not `main`.
|
||||
|
||||
The handwritten notes are prepended above the auto-generated changelog and are the part that matters. Do not include a title in the notes body — the release title (`v{version}: {pun}`) already serves as the heading. Work with the maintainer to draft the notes — propose a draft, get feedback, iterate. Do not publish without the maintainer's sign-off.
|
||||
|
||||
**Before drafting, always read recent existing releases** (`gh release list` then `gh release view <tag>`) to absorb the voice, structure, and level of detail. Each release builds on the tone of previous ones — don't guess at the style from these instructions alone.
|
||||
|
||||
**To preview what PRs will be in the release** before it's cut, call the GitHub generate-notes API. This returns the exact auto-generated changelog that `--generate-notes` would append, so you can see the full PR list — useful for picking a pun theme and making sure nothing's been missed:
|
||||
|
||||
```bash
|
||||
gh api -X POST repos/PrefectHQ/fastmcp/releases/generate-notes \
|
||||
-f tag_name=v3.2.3 \
|
||||
-f target_commitish=main \
|
||||
-f previous_tag_name=v3.2.2 \
|
||||
--jq '.body'
|
||||
```
|
||||
|
||||
Set `target_commitish` to the same branch that will receive the release tag. For maintenance releases, use the maintenance branch (for example, `release/3.x`) so the preview matches the release notes GitHub will generate.
|
||||
|
||||
**Point releases** (3.0, 3.1, 3.2) get narrative prose: open with the theme of the release, then walk through headline features conceptually — what they enable, why they matter, how they fit together. Write it the way a blog post reads, not a changelog. Multiple paragraphs, code examples where they clarify.
|
||||
|
||||
**Patch releases** (3.1.1, 3.0.2) get 1-2 sentences explaining what broke and what the fix does. Keep it minimal — the auto-generated changelog has the details.
|
||||
|
||||
**Publish docs through a PR.** The `published-docs` branch serves gofastmcp.com, and repository rules reject direct pushes and force-pushes to it. Stable releases from `main` automatically open a publication PR after PyPI succeeds. For prereleases and later docs follow-ups, create the same PR manually: start a temporary branch from the current `published-docs`, make a single commit whose tree exactly matches the desired commit on `main`, and use `published-docs` as the PR base. Merging publishes to production. Never push directly to `published-docs`.
|
||||
|
||||
**Merge the docs changelog PR *before* cutting the release, not after.** The post-publish `update-published-docs` job opens a PR that syncs `published-docs` to the released commit for stable releases on the default branch, so the changelog entry only reaches the live site if it's already in the commit being tagged. Land the docs PR on the release target branch first, then cut the release from that branch. If you tag first and merge docs after, this release's publication PR will not include the changelog; publish `main` manually through the PR flow above or wait for the next default-branch stable release. Maintenance releases from `release/3.x` or `release/2.x` publish packages and GitHub notes without repointing `published-docs`; add their changelog entries on the maintenance branch, slotted into the matching major-version section. Two hand-maintained files mirror the GitHub release and must get a new entry for every version, newest at the top (these are `.mdx` and are not covered by the prek Prettier hook, which only runs on `yaml`/`json5` — match the existing entries' style by hand):
|
||||
|
||||
- `docs/changelog.mdx` is the full mirror. Add an `<Update label="v<version>" description="YYYY-MM-DD">` block with: a bold linked title (`**[v<version>: <pun>](<release-url>)**`), a condensed 1-paragraph intro (one sentence for patches), the full categorized PR list reformatted from the `--generate-notes` output (`* <title> by [@user](https://github.com/user) in [#NNNN](<pull-url>)`), a `## New Contributors` list (plain `@user`, linked PR), and a `**Full Changelog**: [vA...vB](<compare-url>)` line.
|
||||
- `docs/updates.mdx` is the skimmable card feed. Add an `<Update label="FastMCP <version>" description="Month DD, YYYY" tags={["Releases"]}>` wrapping a `<Card>` that links to the GitHub release, with a 1-2 sentence summary and (for point releases) a handful of emoji-bulleted highlights.
|
||||
|
||||
Because the docs land *before* the tag exists, derive the entry from the maintainer-approved handwritten notes (intro/summary) and the `--generate-notes` API *preview* (the PR-list body — see the generate-notes API call above, which returns the exact changelog without cutting anything). Scripting the link reformatting is reliable for long PR lists. The release-URL, tag, and compare links follow the known pattern (`/releases/tag/v<version>`, `compare/v<last-stable>...v<version>`) and will 404 only during the short window between merging the docs PR and cutting the release minutes later — they resolve before the release workflow completes. For this reason, create and merge the docs PR *immediately* before cutting the release — treat the two as one tight back-to-back sequence, not independent steps — so the links are valid by the time the release publishes rather than dangling for any longer than necessary.
|
||||
|
||||
### Commit Messages and Agent Attribution
|
||||
|
||||
- **Agents NOT acting on behalf of @jlowin MUST identify themselves** (e.g., "🤖 Generated with Claude Code" in commits/PRs)
|
||||
- Keep commit messages brief - ideally just headlines, not detailed messages
|
||||
- Focus on what changed, not how or why
|
||||
- Always read issue comments for follow-up information (treat maintainers as authoritative)
|
||||
- **Treat proposed solutions in issues skeptically.** This applies to solutions proposed by *users* in issue reports — not to feedback from configured review bots (CodeRabbit, chatgpt-codex-connector, etc.), which should be evaluated on their merits. The ideal issue contains a concise problem description and an MRE — nothing more. Proposed solutions are only worth considering if they clearly reflect genuine, non-obvious investigation of the codebase. If a solution reads like speculation, or like it was generated by an LLM without deep framework knowledge, ignore it and diagnose from the repro. Most reporters — human or AI — do not have sufficient understanding of FastMCP internals to correctly diagnose anything beyond a trivial bug. We can ask the same questions of an LLM when implementing; we don't need the reporter to do it for us, and a wrong diagnosis is worse than none.
|
||||
|
||||
### PR Messages - Required Structure
|
||||
|
||||
- 1-2 paragraphs: problem/tension + solution (PRs are documentation!)
|
||||
- Focused code example showing key capability
|
||||
- **Avoid:** bullet summaries, exhaustive change lists, verbose closes/fixes, marketing language
|
||||
- **Do:** Be opinionated about why change matters, show before/after scenarios
|
||||
- Minor fixes: keep body short and concise
|
||||
- No "test plan" sections or testing summaries
|
||||
|
||||
### Code Review Guidelines
|
||||
|
||||
- **Fix causes, not symptoms.** When a PR works around a problem instead of addressing why it occurs, that's a red flag. A side-channel that compensates for a missing step adds permanent complexity. If the fix doesn't change the code path where the bug actually happens, ask why not.
|
||||
- Focus on API design and naming clarity
|
||||
- Identify confusing patterns (e.g., parameter values that contradict defaults) or non-idiomatic code (mutable defaults, etc.). Contributed code will need to be maintained indefinitely, and by someone other than the author (unless the author is a maintainer).
|
||||
- Suggest specific improvements, not generic "add more tests" comments
|
||||
- Think about API ergonomics from a user perspective
|
||||
|
||||
### Code Standards
|
||||
|
||||
- Python ≥ 3.10 with full type annotations
|
||||
- Follow existing patterns and maintain consistency
|
||||
- **Prioritize readable, understandable code** - clarity over cleverness
|
||||
- Avoid obfuscated or confusing patterns even if they're shorter
|
||||
- Each feature needs corresponding tests
|
||||
|
||||
### Module Exports
|
||||
|
||||
- **Do not create overeager `__init__.py` files.** Package initializers should not import heavy submodules, provider stacks, optional integrations, or modules that can point back into the package. Overeager re-exports make the framework sprawl and create circular imports that only appear in fresh interpreters or clean installs.
|
||||
- **Be intentional about re-exports** - don't blindly re-export everything to parent namespaces
|
||||
- Core types that define a module's purpose should be exported (e.g., `Middleware` from `fastmcp.server.middleware`)
|
||||
- Specialized features can live in submodules (e.g., `fastmcp.server.middleware.dynamic`)
|
||||
- Only re-export to `fastmcp.*` for the most fundamental types (e.g., `FastMCP`, `Client`)
|
||||
- When in doubt, prefer users importing from the specific submodule over re-exporting
|
||||
|
||||
### Documentation
|
||||
|
||||
- Uses Mintlify framework
|
||||
- Files must be in docs.json to be included
|
||||
- Do not manually modify `docs/python-sdk/**` — these files are auto-generated from source code by a bot and maintained via a long-lived PR. Do not include changes to these files in contributor PRs.
|
||||
- Do not manually modify `docs/public/schemas/**` or `fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/schema.json` — these are auto-generated and maintained via a long-lived PR.
|
||||
- **Core Principle:** A feature doesn't exist unless it is documented!
|
||||
- When adding or modifying settings in `fastmcp_slim/fastmcp/settings.py`, update `docs/more/settings.mdx` to match.
|
||||
|
||||
### Documentation Guidelines
|
||||
|
||||
- **Code Examples:** Explain before showing code, make blocks fully runnable (include imports)
|
||||
- **Code Formatting:** Keep code blocks visually clean — avoid deeply nested function calls. Extract intermediate values into named variables rather than inlining everything into one expression. Code in docs is read more than it's run; optimize for scannability.
|
||||
- **Structure:** Headers form navigation guide, logical H2/H3 hierarchy
|
||||
- **Content:** User-focused sections, motivate features (why) before mechanics (how)
|
||||
- **Style:** Prose over code comments for important information
|
||||
- **Docstrings:** FastMCP docstrings are automatically compiled into MDX documents. Use markdown (single backticks, fenced code blocks), not RST (no double backticks). Bare `{}` in examples will be interpreted as JSX — wrap in backticks instead.
|
||||
|
||||
## Code Review Rules
|
||||
|
||||
### Framework regressions and root causes
|
||||
|
||||
- Review changes carefully for regressions in supported framework behavior, including interactions beyond the immediate diff. Trace relevant callers, shared abstractions, protocol and public API contracts, and all affected MCP component types. Determine whether a change fixes the causal code path or merely compensates for the symptom; side channels and special cases that leave the root cause intact should be treated as suspect.
|
||||
|
||||
### Comprehensive first pass
|
||||
|
||||
- Review the entire pull request diff against the merge base, not only the latest commits. Inspect every changed file and the relevant surrounding code, collect all independent, substantiated consequential findings before submitting the review, and report the complete set in one review whenever possible. Do not stop after finding the first few issues or defer other already-visible findings to later review cycles.
|
||||
|
||||
### Prior discussion and proportionality
|
||||
|
||||
- When prior review threads and author or maintainer replies are available, read them before commenting. Evaluate responses on their merits and do not repeat a resolved or convincingly rebutted finding without new evidence. Avoid fixating on speculative edge cases: report an edge case only when it is reachable under supported usage or a credible threat model and has meaningful impact; otherwise omit it or clearly treat it as non-blocking.
|
||||
|
||||
## Critical Patterns
|
||||
|
||||
- Never use bare `except` - be specific with exception types
|
||||
- File sizes enforced by [loq](https://github.com/jakekaplan/loq). Edit `loq.toml` to raise limits; `loq baseline` to ratchet down.
|
||||
- Always `uv sync` first when debugging build issues
|
||||
- Default test timeout is 5s - optimize or mark as integration tests
|
||||
66
CONTRIBUTING.md
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
# Contributing to FastMCP
|
||||
|
||||
FastMCP is an actively maintained, high-traffic project. We welcome contributions — but the most impactful way to contribute might not be what you expect.
|
||||
|
||||
Participation is governed by our [Code of Conduct](CODE_OF_CONDUCT.md), and contributions are licensed under [Apache 2.0](LICENSE).
|
||||
|
||||
## The best contribution is a great issue
|
||||
|
||||
FastMCP is an opinionated framework, and its maintainers use AI-assisted tooling that is deeply tuned to those opinions — the design philosophy, the API patterns, the way the framework is meant to evolve. A well-written issue with a clear problem description is often more valuable than a pull request, because it lets maintainers produce a solution that isn't just correct, but consistent with how the framework wants to work. That matters more than speed, though it's faster too.
|
||||
|
||||
**A great issue looks like this:**
|
||||
|
||||
1. A short, motivating description of the problem or gap
|
||||
2. A minimal reproducible example (for bugs) or a concrete use case (for enhancements)
|
||||
3. A brief note on expected vs. actual behavior
|
||||
|
||||
That's it. No need to diagnose root causes, propose API designs, or suggest implementations. If you've done genuine investigation and have a non-obvious insight, include it.
|
||||
|
||||
## Using AI to contribute
|
||||
|
||||
We encourage you to use LLMs to help identify bugs, write MREs, and prepare contributions. But if you do, your LLM must take into account the conventions and contributing guidelines of this repo — including how we want issues formatted and when it's appropriate to open a PR. Generic LLM output that ignores these guidelines tells us the contribution wasn't made thoughtfully, and we will close it. A good AI-assisted contribution is indistinguishable from a good human one. A bad one is obvious.
|
||||
|
||||
If you're driving an agent: do **not** have it post comments asking to be assigned to an issue or announcing that it intends to work on one. Those comments are ignored. If the agent intends to contribute, open a PR instead — it will be gated on assignment (see below). Comment on an issue only to propose a genuinely novel, differentiated solution, never to claim a task that's already described.
|
||||
|
||||
## When to open a pull request
|
||||
|
||||
An open issue is not an invitation to submit a PR, and it is not a queue you join by commenting. Issues track problems; who implements them and how is a separate decision maintainers make, and whoever opened the issue has first claim on it.
|
||||
|
||||
**Don't post drive-by comments claiming an issue** — "can I work on this?", "please assign me", "I'll take this." They don't affect who gets assigned, they're the most common form of noise we get, and automated versions are ignored. Whoever opens the issue has first claim on it; if that's you, a maintainer will assign you. If you want to implement something someone else reported, just open a PR — you don't need permission to try, and competing PRs are fine — but it's reviewed only if a maintainer assigns you to the issue, which usually won't happen if the reporter intends to handle it. The one comment worth posting is a genuinely different approach worth discussing; a substantive design proposal is welcome, a bare claim on the task is not.
|
||||
|
||||
**Issues labeled `prs welcome` skip the assignment gate.** When we apply that label, we're saying the reporter isn't implementing it and we'd take a PR from anyone. Open one directly — no assignment needed, and it won't be auto-closed. Still reference the issue (`Fixes #123`), since that's how the check knows which issue to look at.
|
||||
|
||||
**What assignment means.** Being assigned is a commitment on both sides: we'll review your work seriously, and you'll see it through. That means responding to review feedback yourself and being able to explain any part of your change and why you made it that way. Use whatever tooling you like to get there — but if you can't answer a question about your own diff, we'll unassign the issue so someone else can pick it up.
|
||||
|
||||
**Bug fixes** — PRs are welcome for simple, well-scoped bug fixes where the problem and solution are both straightforward. "The function raises `TypeError` when passed `None` because of a missing guard" is a good candidate. If the fix requires design decisions or touches multiple subsystems, open an issue with a design proposal instead.
|
||||
|
||||
**Documentation** — Typo fixes, clarifications, and improvements to examples are always welcome as PRs.
|
||||
|
||||
**Enhancements and features** — We welcome enhancement PRs, but our experience is that most contributors — even when using LLMs — implement fixes that address the one instance of a problem they encountered rather than understanding why the framework produces that problem and fixing it at the right layer. This creates branching, patch-style code that's difficult to maintain and makes it impossible to reason about the framework as a coherent system. For this reason, enhancements need a design proposal in the issue before code is written. The proposal doesn't need to be long — just enough to show you've thought about how the change fits into the framework, not just how it solves your immediate case.
|
||||
|
||||
**Integrations** — FastMCP generally does not accept PRs that add third-party integrations (custom middleware, provider-specific adapters, etc.). If you're building something for your users, ship it as a standalone package — that's a feature, not a limitation. Authentication providers are an exception, since auth is tightly coupled to the framework.
|
||||
|
||||
## PR guidelines
|
||||
|
||||
If you do open a PR:
|
||||
|
||||
- **Reference an issue you're assigned to.** Every PR must reference a tracked issue using an auto-close keyword (`Fixes #123`, `Closes #123`, or `Resolves #123`), and the referenced issue must be assigned to you — unless it's labeled `prs welcome`, which waives the assignment requirement. If there isn't an issue, open one. This lets us deconflict effort and steer the approach before you invest time in code. External PRs that don't meet these conditions are automatically labeled `missing-issue-link` and closed; they reopen automatically once the link is present and you're assigned.
|
||||
- **Leave "Allow edits by maintainers" enabled.** We frequently take a PR the last few steps ourselves rather than block on another round trip — tightening a test, adjusting naming, rebasing. It's enabled by default on PRs from personal forks; leave it that way. GitHub doesn't allow it at all for forks owned by an organization, so if you're contributing from one, expect us to land the final changes separately.
|
||||
- **Target the right branch.** Open against `main` unless you're fixing something specific to a maintenance line, in which case target that branch directly (`release/3.x`, `release/2.x`).
|
||||
- **If your PR was auto-closed, don't open a new one.** Edit the *existing* PR to add the issue link, get assigned to that issue, and it reopens on its own — the branch and history are preserved. A duplicate PR just starts you over and adds to the triage pile.
|
||||
- **Keep it focused.** One logical change per PR. Don't bundle unrelated fixes or refactors.
|
||||
- **Match existing patterns.** Follow the code style, type annotation conventions, and test patterns you see in the codebase. Run `uv run prek run --all-files` before submitting.
|
||||
- **Write tests.** Bug fixes should include a test that fails without the fix. Enhancements should include tests for the new behavior.
|
||||
- **Fix the cause, not the symptom.** If the bug is that a code path skips a step, the fix should make it stop skipping that step — not add compensation elsewhere. Workaround-style fixes will be sent back for revision.
|
||||
- **Don't submit generated boilerplate.** We review every line. PRs that read like unedited LLM output — verbose descriptions, speculative changes, shotgun-style fixes — will be closed.
|
||||
|
||||
## What we'll close without review
|
||||
|
||||
To keep the project maintainable, we will close PRs that:
|
||||
|
||||
- Don't reference an issue or address a clearly self-evident bug
|
||||
- Make sweeping changes without prior discussion
|
||||
- Add third-party integrations that belong in a separate package
|
||||
- Are difficult to review due to size, scope, or generated content
|
||||
|
||||
This isn't personal — contributing to a framework is different from contributing to an application. In an application, a fix that works is a good fix. In a framework, a fix that works but doesn't fit the framework's design creates maintenance burden that compounds over time. Every patch that works around a problem instead of solving it at the right layer makes the system harder for *everyone* to reason about — maintainers, contributors, and users. We hold contributions to this standard because the alternative is a codebase that's a series of patches rather than a coherent system. A good issue is often the best thing you can do for the project.
|
||||
80
README.md
|
|
@ -3,9 +3,9 @@
|
|||
<!-- omit in toc -->
|
||||
|
||||
<picture>
|
||||
<source width="550" media="(prefers-color-scheme: dark)" srcset="docs/assets/brand/f-watercolor-waves-dark-2.png">
|
||||
<source width="550" media="(prefers-color-scheme: light)" srcset="docs/assets/brand/f-watercolor-waves-2.png">
|
||||
<img width="550" alt="FastMCP Logo" src="docs/assets/brand/f-watercolor-waves-2.png">
|
||||
<source width="550" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/PrefectHQ/fastmcp/main/docs/assets/brand/f-watercolor-waves-4-dark.png">
|
||||
<source width="550" media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/PrefectHQ/fastmcp/main/docs/assets/brand/f-watercolor-waves-4.png">
|
||||
<img width="550" alt="FastMCP Logo" src="https://raw.githubusercontent.com/PrefectHQ/fastmcp/main/docs/assets/brand/f-watercolor-waves-2.png">
|
||||
</picture>
|
||||
|
||||
# FastMCP 🚀
|
||||
|
|
@ -17,15 +17,16 @@
|
|||
[](https://gofastmcp.com)
|
||||
[](https://discord.gg/uu8dJCgttd)
|
||||
[](https://pypi.org/project/fastmcp)
|
||||
[](https://github.com/jlowin/fastmcp/actions/workflows/run-tests.yml)
|
||||
[](https://github.com/jlowin/fastmcp/blob/main/LICENSE)
|
||||
[](https://github.com/PrefectHQ/fastmcp-ts)
|
||||
[](https://github.com/PrefectHQ/fastmcp/actions/workflows/run-tests.yml)
|
||||
[](https://github.com/PrefectHQ/fastmcp/blob/main/LICENSE)
|
||||
|
||||
<a href="https://trendshift.io/repositories/13266" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13266" alt="jlowin%2Ffastmcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
<a href="https://trendshift.io/repositories/21461" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21461" alt="prefecthq%2Ffastmcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io) (MCP) provides a standardized way to connect AI agents to tools and data. FastMCP makes it easy to build MCP applications with clean, Pythonic code:
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) connects LLMs to tools and data. FastMCP is a full MCP application framework for servers, clients, and interactive apps. A server starts with ordinary Python:
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
|
|
@ -43,39 +44,70 @@ if __name__ == "__main__":
|
|||
|
||||
## Why FastMCP
|
||||
|
||||
MCP lets you give agents access to your tools and data. But building an effective MCP server is harder than it looks.
|
||||
Building an effective MCP application is harder than it looks. FastMCP handles all of it. Declare a tool with a Python function, and the schema, validation, and documentation are generated automatically. Connect to a server with a URL, and transport negotiation, authentication, and protocol lifecycle are managed for you. You focus on your logic, and the MCP part just works: **with FastMCP, best practices are built in.**
|
||||
|
||||
Give your agent too much—hundreds of tools, verbose responses—and it gets overwhelmed. Give it too little and it can't do its job. The protocol itself is complex, with layers of serialization, validation, and error handling that have nothing to do with your business logic. And the spec keeps evolving; what worked last month might already need updating.
|
||||
**That's why FastMCP is the standard framework for working with MCP.** FastMCP 1.0 was incorporated into the official MCP Python SDK in 2024. Today, the actively maintained standalone project is downloaded a million times a day, and some version of FastMCP powers 70% of MCP servers across all languages.
|
||||
|
||||
The real challenge isn't implementing the protocol. It's delivering **the right information at the right time**.
|
||||
FastMCP has three pillars:
|
||||
|
||||
That's the problem FastMCP solves—and why it's become the standard. FastMCP 1.0 was incorporated into the official MCP SDK in 2024. Today, the actively maintained standalone project is downloaded a million times a day, and some version of FastMCP powers 70% of MCP servers across all languages.
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="33%">
|
||||
<a href="https://gofastmcp.com/servers/server">
|
||||
<img src="https://raw.githubusercontent.com/PrefectHQ/fastmcp/main/docs/assets/images/servers-card.png" alt="Servers" />
|
||||
<br /><strong>Servers</strong>
|
||||
</a>
|
||||
<br />Expose tools, resources, and prompts to LLMs.
|
||||
</td>
|
||||
<td align="center" valign="top" width="33%">
|
||||
<a href="https://gofastmcp.com/apps/overview">
|
||||
<img src="https://raw.githubusercontent.com/PrefectHQ/fastmcp/main/docs/assets/images/apps-card.png" alt="Apps" />
|
||||
<br /><strong>Apps</strong>
|
||||
</a>
|
||||
<br />Give your tools interactive UIs rendered directly in the conversation.
|
||||
</td>
|
||||
<td align="center" valign="top" width="33%">
|
||||
<a href="https://gofastmcp.com/clients/client">
|
||||
<img src="https://raw.githubusercontent.com/PrefectHQ/fastmcp/main/docs/assets/images/clients-card.png" alt="Clients" />
|
||||
<br /><strong>Clients</strong>
|
||||
</a>
|
||||
<br />Connect to any MCP server — local or remote, programmatic or CLI.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
The framework is built on three abstractions that map to the decisions you actually need to make:
|
||||
**[Servers](https://gofastmcp.com/servers/server)** wrap your Python functions into MCP-compliant tools, resources, and prompts. **[Clients](https://gofastmcp.com/clients/client)** connect to any server with full protocol support. And **[Apps](https://gofastmcp.com/apps/overview)** give your tools interactive UIs rendered directly in the conversation.
|
||||
|
||||
- **Components** are what you expose: tools, resources, and prompts. Wrap a Python function, and FastMCP handles the schema, validation, and docs.
|
||||
- **Providers** are where components come from: decorated functions, files on disk, OpenAPI specs, remote servers—your logic can live anywhere.
|
||||
- **Transforms** shape what clients see: namespacing, filtering, authorization, versioning. The same server can present differently to different users.
|
||||
**Building in TypeScript?** [FastMCP for TypeScript](https://github.com/PrefectHQ/fastmcp-ts) is the official counterpart, built and maintained by the same team. Same pillars, same ideas, `npm install @prefecthq/fastmcp-ts`.
|
||||
|
||||
These compose cleanly, so complex patterns don't require complex code. And because FastMCP is opinionated about the details, like serialization, error handling, and protocol compliance, **best practices are the path of least resistance**. You focus on your logic; the MCP part just works.
|
||||
Ready to build? Start with the [installation guide](https://gofastmcp.com/getting-started/installation) or jump straight to the [quickstart](https://gofastmcp.com/getting-started/quickstart).
|
||||
|
||||
**Move fast and make things.**
|
||||
## Scale MCP with Horizon
|
||||
|
||||
FastMCP handles the MCP application layer. **[Prefect Horizon](https://www.prefect.io/horizon?utm_source=github&utm_medium=readme&utm_campaign=readme_horizon&utm_content=readme_body)** is the enterprise MCP gateway for scaling servers and tools across teams, with centralized governance over how they are deployed, discovered, secured, and used.
|
||||
|
||||
FastMCP and Horizon are built by the same team at [Prefect](https://www.prefect.io/).
|
||||
|
||||
Deploy FastMCP servers from GitHub with branch previews and instant rollback. Create a private registry of every MCP your company uses. Secure access with SSO and tool-level RBAC. Get audit logs, observability, and governance across your MCP stack. Remix approved tools into purpose-built endpoints for teams and agents.
|
||||
|
||||
Start with FastMCP. [Scale with Horizon →](https://www.prefect.io/horizon?utm_source=github&utm_medium=readme&utm_campaign=readme_horizon&utm_content=readme_cta)
|
||||
|
||||
## Installation
|
||||
|
||||
> [!Note]
|
||||
> FastMCP 3.0 is currently in beta. Install with: `pip install fastmcp==3.0.0b1`
|
||||
>
|
||||
> For production systems requiring stability, pin to v2: `pip install 'fastmcp<3'`
|
||||
|
||||
We recommend installing FastMCP with [uv](https://docs.astral.sh/uv/):
|
||||
We recommend adding FastMCP to your project with [uv](https://docs.astral.sh/uv/):
|
||||
|
||||
```bash
|
||||
uv pip install fastmcp
|
||||
uv add fastmcp
|
||||
```
|
||||
|
||||
For full installation instructions, including verification and upgrading, see the [**Installation Guide**](https://gofastmcp.com/getting-started/installation).
|
||||
|
||||
**Upgrading?** We have guides for:
|
||||
- [Upgrading from FastMCP 3](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-3)
|
||||
- [Upgrading from FastMCP 2](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-2)
|
||||
- [Upgrading from MCP SDK v1](https://gofastmcp.com/getting-started/upgrading/from-mcp-sdk-v1) or [v2](https://gofastmcp.com/getting-started/upgrading/from-mcp-sdk-v2)
|
||||
- [Upgrading from the low-level SDK v1](https://gofastmcp.com/getting-started/upgrading/from-low-level-sdk-v1) or [v2](https://gofastmcp.com/getting-started/upgrading/from-low-level-sdk-v2)
|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
FastMCP's complete documentation is available at **[gofastmcp.com](https://gofastmcp.com)**, including detailed guides, API references, and advanced patterns.
|
||||
|
|
|
|||
30
SECURITY.md
|
|
@ -2,15 +2,33 @@
|
|||
|
||||
## Supported Versions
|
||||
|
||||
FastMCP v2.x receives security updates. Earlier versions are no longer supported.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 2.x | :white_check_mark: |
|
||||
| < 2.0 | :x: |
|
||||
| 3.x | :white_check_mark: |
|
||||
| 2.x | :x: |
|
||||
| 1.x | :x: |
|
||||
| 0.x | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please report security vulnerabilities privately using [GitHub's security advisory feature](https://github.com/jlowin/fastmcp/security/advisories/new).
|
||||
Please report security vulnerabilities privately using [GitHub's security advisory feature](https://github.com/PrefectHQ/fastmcp/security/advisories/new). Do not open public issues for security concerns.
|
||||
|
||||
Do not open public issues for security concerns.
|
||||
## Scope
|
||||
|
||||
We accept reports for vulnerabilities in FastMCP itself — the library code in this repository.
|
||||
|
||||
The following are **out of scope**:
|
||||
|
||||
- Vulnerabilities in third-party dependencies or the MCP SDK itself. We'll bump version floors for known CVEs, but the fix belongs upstream.
|
||||
- Limitations of upstream identity providers that FastMCP cannot control.
|
||||
- Issues that require the attacker to already have server-side access or control of the MCP server configuration.
|
||||
|
||||
## Disclosure Process
|
||||
|
||||
When we receive a valid report:
|
||||
|
||||
1. We triage the report and determine whether it affects FastMCP directly.
|
||||
2. We develop and test a fix on a private branch.
|
||||
3. We coordinate CVE assignment through GitHub's advisory process when warranted.
|
||||
4. We publish the advisory and release a patched version.
|
||||
5. We credit the reporter in the advisory (unless they prefer otherwise).
|
||||
|
|
|
|||
61
dev-docs/v3-notes/get-methods-consolidation.md
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
# Consolidating Discovery Methods
|
||||
|
||||
This document captures the design decisions around component listing methods in FastMCP 3.0.
|
||||
|
||||
## Problem
|
||||
|
||||
The server had parallel implementations for listing components:
|
||||
- `get_tools()` / `_list_tools()`
|
||||
- `get_resources()` / `_list_resources()`
|
||||
- `get_prompts()` / `_list_prompts()`
|
||||
- `get_resource_templates()` / `_list_resource_templates()`
|
||||
|
||||
These were nearly identical but with subtle differences in dedup keys, logging, and return types. The `_list_*` methods were internal and used by the MCP protocol handlers, while `get_*` methods were the public API.
|
||||
|
||||
## Solution
|
||||
|
||||
The duplicate methods were consolidated into a single set of `list_*` methods. The old `get_*` plural methods and `_list_*` internal methods were both removed.
|
||||
|
||||
This happened in two phases:
|
||||
|
||||
1. **Consolidation** (Dec 2025): Merged `get_*` and `_list_*` into a single `get_*` method with an `apply_middleware` parameter.
|
||||
2. **Rename** (Jan 2026): When `FastMCP` was refactored to inherit from `Provider`, the methods were renamed to `list_*` to align with the `Provider` interface. The `apply_middleware` parameter was renamed to `run_middleware` with a default of `True`.
|
||||
|
||||
```python
|
||||
async def list_tools(self, *, run_middleware: bool = True) -> Sequence[Tool]:
|
||||
"""Canonical method for listing tools."""
|
||||
...
|
||||
```
|
||||
|
||||
## Key Changes
|
||||
|
||||
### Return Type: dict → list
|
||||
|
||||
The dict return type was removed because the key was redundant—components already have `.name` or `.uri` attributes.
|
||||
|
||||
```python
|
||||
# Before (v2.x)
|
||||
tools = await server.get_tools()
|
||||
tool = tools["my_tool"]
|
||||
|
||||
# After (v3.0)
|
||||
tools = await server.list_tools()
|
||||
tool = next(t for t in tools if t.name == "my_tool")
|
||||
```
|
||||
|
||||
### Middleware via Parameter
|
||||
|
||||
The `run_middleware=True` parameter (default) applies the middleware chain. This replaces the separate `_list_*_middleware()` methods.
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Single source of truth** - One method, not two
|
||||
2. **Consistent behavior** - Same dedup key, same visibility filtering
|
||||
3. **Clearer API** - Public method with explicit middleware opt-in
|
||||
4. **Provider alignment** - `FastMCP.list_tools()` overrides `Provider.list_tools()`
|
||||
5. **Less code** - Deleted ~200 lines of duplicate implementation
|
||||
|
||||
## Implementation Files
|
||||
|
||||
- `src/fastmcp/server/server.py` - Canonical `list_*` methods
|
||||
- `src/fastmcp/server/providers/` - Provider base class defines the interface
|
||||
1481
dev-docs/v3-notes/v3-features.md
Normal file
153
dev-docs/v4-notes/background-tasks.md
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
---
|
||||
title: Background Tasks (SEP-2663)
|
||||
---
|
||||
|
||||
**Status: Shipped (#4602, #4603).** This page is the approved design for rebuilding FastMCP's background-task support on the `io.modelcontextprotocol/tasks` extension. It supersedes the earlier "delete the task machinery" direction recorded during the SDK v2 migration. The [Feature Program](feature-program.md#background-tasks-sep-2663) carries the one-line status; user-facing usage is documented at [Background Tasks](https://gofastmcp.com/servers/tasks) and [Background Tasks (client)](https://gofastmcp.com/clients/tasks).
|
||||
|
||||
## TL;DR
|
||||
|
||||
Background tasks live on. The MCP spec moved them out of core and into a **Final, merged** extension — `io.modelcontextprotocol/tasks` (SEP-2663) — that keeps the polling model FastMCP already implements. **No SDK, in any language, ships a runtime for it yet.** FastMCP owns the only production-shaped execution engine (Docket/Redis) built for a near-identical protocol.
|
||||
|
||||
The plan: **rebuild task support on SEP-2663 as `fastmcp-tasks`, an in-repo optional package**, gated by `task=True` exactly as MCP Apps is gated by `app=True`. Remove the SEP-1686 *wire layer*; keep and re-home the *execution engine*. Along the way, introduce a **FastMCP-native server extension API** so tasks (and later Apps) plug in through one documented mechanism instead of bespoke surgery on core.
|
||||
|
||||
Net effect: a server that already uses `@mcp.tool(task=True)` needs **no code change**, and FastMCP plausibly becomes the first runtime implementation of the tasks extension anywhere.
|
||||
|
||||
## Background: where tasks stand today
|
||||
|
||||
FastMCP 3 shipped background tasks against **SEP-1686**, the task protocol that briefly lived in the core MCP spec. The implementation is ~4,000 lines across server, client, CLI, and an SDK shim, split into two very different halves:
|
||||
|
||||
- **A wire layer** — capability advertisement, the `tasks/get|result|list|cancel` handlers, a `CreateTaskResult` on augmented `tools/call`, and a Redis-backed *push* relay that lets a worker reach a client to deliver notifications and elicitation requests.
|
||||
- **An execution engine** — [Docket](https://github.com/chrisguidry/docket) (queue, worker, result store, TTL, `memory://` or `redis://` backends) plus FastMCP-built durability: auth-scoped compound keys that isolate task access by caller, request-context snapshot/restore across worker processes, argument-coercion parity with the sync path, and the `fastmcp tasks worker` CLI.
|
||||
|
||||
The SDK v2 migration removed SEP-1686 from the core spec. The v4 design notes, until now, recorded the consequence as "delete the task machinery; users who need tasks stay on FastMCP 3." That was the right call **given the information at the time** — the assumption was that the successor protocol either didn't exist or wasn't implementable. Both halves of that assumption turned out to be wrong.
|
||||
|
||||
## What changed upstream: SEP-2663
|
||||
|
||||
Tasks were reworked, not removed. **SEP-2663 ("Tasks Extension") is Final and was merged upstream on 2026-05-15**, superseding SEP-1686. It defines the `io.modelcontextprotocol/tasks` extension, a capability-negotiated feature layered on the SEP-2133 extensions mechanism. It keeps SEP-1686's polling core and tightens it.
|
||||
|
||||
**The wire shape:**
|
||||
|
||||
1. Client advertises the tasks capability (per-request, in `_meta`). This is *consent* — "I can handle a task result" — not a request to run one.
|
||||
2. Client issues a normal `tools/call`. **The server decides** whether to run it as a task.
|
||||
3. If tasked, the server returns a `CreateTaskResult` (a claimed result shape carrying `resultType: "task"`) with a **server-generated** `taskId`.
|
||||
4. Client polls `tasks/get` until the status is terminal; the result is **inlined** into that response.
|
||||
5. In-task input (elicit/sample/roots requested *during* execution) is **poll-based**: status flips to `input_required`, outstanding requests appear in an `inputRequests` map, and the client answers via `tasks/update`.
|
||||
6. `tasks/cancel` is cooperative. Optional push exists (`notifications/tasks` over `subscriptions/listen`) but servers need not send it.
|
||||
|
||||
**Delta from SEP-1686** — and the striking thing is that most of it is *deletion*, because the spec moved toward what FastMCP already built:
|
||||
|
||||
| Dimension | SEP-1686 (old) | SEP-2663 (new) | FastMCP today |
|
||||
| --- | --- | --- | --- |
|
||||
| Task-id generation | Client-generated | **Server**-generated | Already server-generated |
|
||||
| `tasks/list` | Present | **Removed** (enumeration risk) | Already a stub returning `[]` |
|
||||
| Result retrieval | Separate `tasks/result` | **Inlined** into `tasks/get` | Merge two handlers into one |
|
||||
| `tasks/delete` | Present | **Removed** (rely on TTL) | TTL is Docket-native |
|
||||
| Creation race | `notifications/tasks/created` | **Durable-creation MUST** | One read-your-writes check away |
|
||||
| In-task input | Push relay + `_meta` tagging | **Poll**: `input_required` + `tasks/update` | Replaces the hairiest module |
|
||||
| Statuses | 7 (incl. `submitted`, `unknown`) | 5 | Shrinks a mapping table |
|
||||
| Augmentable requests | Any | **`tools/call` only** | Tools-only surface (see scope) |
|
||||
| LB routing | Unspecified | `Mcp-Name: <taskId>` header | Moot with shared Redis |
|
||||
|
||||
**Critically: no runtime exists.** The `ext-tasks` repo is schema + prose only. The TypeScript and Python SDKs carry the wire types and conformance fixtures — no client/server implementation. The field is open.
|
||||
|
||||
## The decision
|
||||
|
||||
**Build it.** Two facts flip the earlier "delete and wait" call:
|
||||
|
||||
1. **The spec is what FastMCP already implements**, minus a push relay it can now shed. The rebuild is dominated by deletion and a thin new wire adapter, not a from-scratch effort.
|
||||
2. **FastMCP is uniquely positioned.** SEP-2663 *assumes* a durable server-side store, server-minted high-entropy ids, eventual-consistency-aware creation, and multi-node routing — precisely what Docket/Redis provides. No other framework has this built.
|
||||
|
||||
Maintaining the SEP-1686 machinery through the migration is dead weight (it's the sole reason for the `_sdk_patches.py` shim, the `TaskNotificationHandler`, and a cluster of protocol-era xfails). Rebuilding on SEP-2663 clears that debt *and* produces a flagship v4 capability with a zero-code-change migration story.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Engine and wire split
|
||||
|
||||
The existing code already separates cleanly along this line; the rebuild makes the boundary a package boundary.
|
||||
|
||||
- **Removed:** the SEP-1686 wire layer — capability advertisement, the four CRUD handlers, and (the big win) the entire Redis push relay (`server/tasks/elicitation.py`, `notifications.py`), which existed only because SEP-1686 had no poll-based in-task input channel. SEP-2663's `input_required`/`tasks/update` replaces it; the request/response store survives, the push envelope does not.
|
||||
- **Kept and re-homed:** the Docket execution engine, the auth-scoped key encoding (this is our *authorization* layer for `tasks/get`/`update`/`cancel` — stronger than the spec's "taskIds may be bearer tokens"), context snapshot/restore, argument coercion, and the worker CLI. All of it is wire-agnostic.
|
||||
- **New:** a thin SEP-2663 wire adapter — capability, the `tasks/get`/`update`/`cancel` methods, and a `tools/call` interceptor that decides-and-tasks.
|
||||
|
||||
### Packaging
|
||||
|
||||
`fastmcp-tasks` becomes an in-repo `uv` workspace member on the `fastmcp_remote` template (own `pyproject.toml`, lockstep-versioned, re-exported through the `fastmcp` metapackage). The DX parallel with MCP Apps is exact:
|
||||
|
||||
| Concern | MCP Apps | Background tasks |
|
||||
| --- | --- | --- |
|
||||
| Authoring flag (core) | `@mcp.tool(app=True)` | `@mcp.tool(task=True)` |
|
||||
| Optional package | `prefab-ui` | `fastmcp-tasks` |
|
||||
| Extra | `fastmcp[apps]` | `fastmcp[tasks]` |
|
||||
| Missing-package behavior | Loud install hint | Loud install hint at server build |
|
||||
|
||||
**Core keeps only the declaration:** `task=True` / `TaskConfig` is metadata on a component, with no engine import. Everything else — engine and wire adapter — lives in the `fastmcp-tasks` package. The existing `[tasks]` extra re-points from the SEP-1686 machinery to `fastmcp-tasks`, so `pip install fastmcp[tasks]` and `task=True` keep working with modern wire underneath.
|
||||
|
||||
Activation stays **implicit-but-loud** (the existing `require_docket()` pattern, not silent degradation): `task=True` anywhere triggers a lazy import of `fastmcp-tasks` at build time; a missing install raises immediately. A tool the author marked as a task silently running inline would be a correctness bug, not a graceful fallback.
|
||||
|
||||
### The extension API
|
||||
|
||||
MCP extensions (SEP-2133) are a **genuinely new abstraction in SDK v2** — they did not exist in v1. So MCP Apps hand-rolling its integration wasn't a wrong choice; it predates the tool. Today FastMCP's **server** bypasses the SDK's `Extension` class entirely (it hand-splices the `ui` capability onto the low-level server and walks tool metadata directly), while the **client** forwards `ClientExtension` natively. Every new protocol extension currently means bespoke core surgery.
|
||||
|
||||
Tasks is the forcing function to fix that. The design adds a single registration point:
|
||||
|
||||
```python test="skip"
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp_tasks import TasksExtension
|
||||
|
||||
mcp = FastMCP("Server")
|
||||
mcp.add_extension(TasksExtension(url="redis://...")) # required to enable tasks
|
||||
|
||||
|
||||
@mcp.tool(task=True) # intent: this tool CAN run as a task
|
||||
async def crunch(dataset: str) -> str:
|
||||
...
|
||||
```
|
||||
|
||||
`add_extension` is **required** for `task=True` to work — it is not autodetected from the presence of `task=True` flags. This is deliberate. The extension needs configuration that has to live somewhere (backend URL, worker concurrency, TTL defaults), and `add_extension(TasksExtension(...))` is its natural home; autodetection would only scatter that config into settings/env and hide the moment of enablement. Requiring it also keeps capability advertisement honest — the server advertises the `tasks` capability iff the extension is registered — and removes the worst footgun, a tool silently running on an in-memory backend in production because nobody configured Redis. The two concerns stay cleanly separated: `task=True` is per-component intent ("this tool *can* be a task"); `add_extension` is server-wide enablement and config ("this server *runs* tasks, here's how"). Using `task=True` with no extension registered is a loud build-time error.
|
||||
|
||||
The extension API contributes a negotiated capability, additive request methods, and a `tools/call` interceptor — with access to FastMCP-level constructs the SDK's `Extension` withholds (the component registry, `Context`, auth scope). It is **designed against tasks** because tasks exercises the full surface (capability + methods + interception + client claims + notifications), where Apps exercises only a subset. Apps migrates onto the extension API as a fast-follow, deleting the hand-rolled splices and confirming the design generalizes.
|
||||
|
||||
**Extension vs. middleware** — the discriminator, so we do not over-apply this: an extension is a *negotiated contract change the client must understand*; middleware is *unilateral server behavior the client never sees*. PII detection, auth, rate limiting → [middleware](https://gofastmcp.com/servers/middleware). Tasks, Apps → extensions. Litmus test: delete the capability advertisement — if nothing about the client's behavior changes, it was middleware.
|
||||
|
||||
### Client experience
|
||||
|
||||
SEP-2663 removed the client-side "make this a task" flag — the server decides. That maps onto FastMCP's existing two-tier client surface, the **friendly** `call_tool` vs the **low-level** `call_tool_mcp`, so there is almost no new API:
|
||||
|
||||
- **`call_tool(name, args)` (friendly)** — advertises the capability and, if the server tasks the call, **transparently drives the poll loop** and returns the finished result. Whether the server tasked it is invisible. The machinery already exists: the migration wired claim-resolution through `call_tool_mcp`'s `allow_claimed` path, so a returned `CreateTaskResult` is finished into an ordinary `CallToolResult`. In-task `input_required` routes through the client's **existing elicitation handler**, answered via `tasks/update` — so background elicitation looks identical to foreground elicitation, with zero new client API.
|
||||
- **`call_tool_mcp(...)` (low-level)** — hands back the raw `CreateTaskResult` claimed shape for callers managing the task themselves.
|
||||
- **A "return quickly" flag on the friendly interface** yields the `Task` handle (`.status()`, `.wait()`, `.cancel()`, awaitable) without blocking — the escape hatch for progress and cancellation.
|
||||
|
||||
Server-side, `TaskConfig` modes translate directly: `required` → always task (`-32003` for non-declaring clients), `optional` → task iff the client declared, `forbidden` → never.
|
||||
|
||||
## Sequencing
|
||||
|
||||
1. **Design + unit-test the extension API** against tasks' full surface (capability, methods, interception, client claims/notifications) — as its own testable layer, proven in isolation with a trivial in-test extension before any tasks logic lands on it.
|
||||
2. **Build `fastmcp-tasks`** — extract the engine from the removed SEP-1686 layer, write the SEP-2663 adapter, port the client half.
|
||||
3. **Migrate MCP Apps onto the extension API** — fast-follow, off the critical path, with Apps' existing green tests as the regression net.
|
||||
|
||||
Tasks leads because only it exercises the full API surface; leading with the Apps subset would design us into a corner. Apps becomes the second consumer that confirms generality.
|
||||
|
||||
## Scope for v1 (non-goals)
|
||||
|
||||
- **Polling only.** The optional `notifications/tasks` push and `subscriptions/listen` integration are deferred to a later `fastmcp-tasks` version. This lets the second Redis notification queue die rather than be ported.
|
||||
- **`tools/call` only — do not lead the spec.** SEP-2663 augments `tools/call` only. FastMCP 3 offered `task=True` on prompts and resources *ahead* of the SDK under SEP-1686, and that was a mistake: it produced wire-inexpressible capability, a permanent xfail cluster, and the sdk-feedback #3 gap. The rebuild does **not** repeat it — `task=` is a tools-only surface, and the generic prompt/resource task spine is dropped rather than carried. If the spec extends augmentation later, the surface grows with it.
|
||||
- **Ship experimental.** The `ext-tasks` schema is labeled experimental with no releases; `fastmcp-tasks` ships labeled experimental initially and revs on its own cadence when the schema moves.
|
||||
|
||||
## Risks
|
||||
|
||||
| Risk | Mitigation |
|
||||
| --- | --- |
|
||||
| **Spec churn** (extension is experimental) | Thin wire adapter over a wire-agnostic engine; ship experimental; SEP itself is Final, so the polling model is stable even if field names move. |
|
||||
| **Era gating** — SDK strips `capabilities.extensions` at pre-2026 negotiated versions (sdk-feedback #2) | Advertisement effectively requires the 2026-07-28 era. FastMCP 3 covers legacy tasks. **#2 now gates a flagship feature → escalate upstream.** |
|
||||
| **Co-developing a new abstraction + greenfield feature** | Build and unit-test the extension API in isolation first (step 1) before tasks logic lands on it. |
|
||||
| **Naming confusion** — `[tasks]` extra re-points under the same name | Deliberate changelog note; user code and the extra name are unchanged, only the wire modernizes. |
|
||||
|
||||
## Design decisions (resolved)
|
||||
|
||||
These were the open forks; the maintainer has settled them. Recorded here so the direction is unambiguous going into implementation.
|
||||
|
||||
1. **Wire adapter location — in the `fastmcp-tasks` package.** The engine *and* the SEP-2663 wire adapter live in the package; core carries only the `task=True` declaration. This isolates the experimental schema's churn from core, at the cost of diverging from the Apps precedent (where the `ui` wire glue lives in core today — Apps will converge onto this model when it migrates to the extension API).
|
||||
2. **Extension API shape — a FastMCP-native `mcp.add_extension()`, required to enable tasks.** Chosen over a thin pass-through to the SDK's `MCPServer(extensions=...)` because the FastMCP-native API can hand extensions the `Context`, component registry, and auth scope the SDK's `Extension` withholds. `add_extension` is **required** for `task=True` (not autodetected) — it is the single home for backend config and the honest source of capability advertisement. See [The extension API](#the-extension-api).
|
||||
3. **Client default — transparent completion on the friendly interface.** `call_tool` drives the poll loop and returns the finished result; `call_tool_mcp` exposes the raw `CreateTaskResult`; a "return quickly" flag yields the `Task` handle. See [Client experience](#client-experience).
|
||||
4. **Experimental labeling — yes.** `fastmcp-tasks` ships labeled experimental for at least one minor cycle, tracking the experimental `ext-tasks` schema.
|
||||
5. **Resource/prompt spine — dropped; tools-only.** The rebuild does not lead the SDK on augmentable request types, correcting the SEP-1686-era mistake. See [Scope for v1](#scope-for-v1-non-goals).
|
||||
595
dev-docs/v4-notes/change-register.md
Normal file
|
|
@ -0,0 +1,595 @@
|
|||
---
|
||||
title: Change Register
|
||||
---
|
||||
|
||||
This is the complete register of user-facing changes from the MCP Python SDK v2 migration ([PR #4437](https://github.com/PrefectHQ/fastmcp/pull/4437)), organized by subsystem. It doubles as a review lens: take one subsystem, read its claimed changes, and verify each against the diff.
|
||||
|
||||
Each entry is tagged **Absorbed** (public surface unchanged), **Bridged** (shim keeps old code working, usually warning), **Breaking** (user code must change), or **Deprecated** (works, warns, slated for removal). See the [overview](index.md) for what each disposition means.
|
||||
|
||||
**Empirical validation (WS2 upgrade reality-check).** The register's compatibility claims are verified, not predicted. Running unchanged 3.x-era code against this branch, all 11 upgrade scenarios pass or warn — the only failures were the two predicted breaks, user `mcp.types` imports and positional `McpError(ErrorData(...))` construction — and the first of those went away when the stable SDK restored `mcp.types` (below). Cross-version wire interop between a 3.4.3 peer and this branch is bidirectionally clean across 9 operations (3.4.3 client ↔ v4 server and v4 client ↔ 3.4.3 server over HTTP). All 29 `_ALIASES` bridge entries warn correctly with actionable messages.
|
||||
|
||||
## Environment
|
||||
|
||||
### Dependency floors: pydantic >= 2.12, Starlette >= 1.0 — Breaking (environment)
|
||||
|
||||
The SDK v2 raises FastMCP's dependency floors. Projects pinning an older pydantic (e.g. `2.11.*`) hit an unsatisfiable-resolution error at install time and must bump their pin; unpinned projects get pydantic upgraded silently. The server extra floors Starlette at `>=1.0.1` — modern FastAPI (0.11x+) already runs Starlette 1.x, so coexistence is clean (verified with FastAPI 0.138.2); only very old FastAPI pinned below Starlette 1.0 conflicts. Both are documented in the [upgrade guide's Environment requirements](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-3#environment-requirements).
|
||||
|
||||
*Verify:* `fastmcp_slim/pyproject.toml` (`pydantic[email]>=2.12.0` core, `starlette>=1.0.1` server extra); WS2 environment-upgrade scenario.
|
||||
|
||||
## Types and imports
|
||||
|
||||
The SDK v2 moved protocol types into a standalone `mcp_types` package — still importable as `mcp.types` — and renamed every model field from camelCase to snake_case in Python. The wire format is unchanged: the models keep their camelCase aliases and the SDK serializes with `by_alias=True`, so this renames the attributes code reads, not the JSON on the connection. This is the single largest source of user-facing change, and FastMCP absorbs nearly all of it.
|
||||
|
||||
### `mcp.types` split into `mcp_types` — Breaking (by omission)
|
||||
|
||||
<Note>
|
||||
Superseded by the stable SDK — see "`mcp.types` restored as a permanent alias" below. The betas this section was written against had no `mcp.types`; `2.0.0` brought it back, so the break never reached a release.
|
||||
</Note>
|
||||
|
||||
The `mcp.types` module no longer exists. Any `from mcp.types import X` or `import mcp.types` in user code raises `ImportError`. This is the one import change users cannot avoid.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/types.py`, and grep the diff for the doc migration `from mcp.types import` → `from fastmcp.types import` (30 sites).
|
||||
|
||||
### `mcp.types` restored as a permanent alias — Absorbed (stable-SDK change)
|
||||
|
||||
The SDK betas removed `mcp.types` outright, which made user imports the one unavoidable break in the migration. SDK `2.0.0` reintroduced it as a permanent alias for `mcp_types`: a wildcard mirror where every name is the *same object* (`mcp.types.Tool is mcp_types.Tool`), with matching `__all__` and the same snake_case fields. It is not a v1 restoration — only the import path came back. So `from mcp.types import X` keeps working, and the break is gone.
|
||||
|
||||
This leaves the two spellings pointing at one package, and FastMCP uses each in a different place on purpose:
|
||||
|
||||
- **User-facing docs and examples use `mcp.types`.** Anyone installing `fastmcp` gets the full SDK (`fastmcp` → `fastmcp-slim[client,server]` → `[mcp]` → `mcp`), so the aliased path always resolves and is the spelling the SDK prefers. It also means a user's own dependency list needs only `mcp`, without naming `mcp-types` to satisfy a linter.
|
||||
- **FastMCP's own source uses `mcp_types`.** `mcp.types` is a submodule of `mcp`, so importing it requires the whole SDK. `mcp-types` is a *core* `fastmcp-slim` dependency while `mcp` sits behind the `[mcp]` extra, and a bare `fastmcp-slim` install must import without the SDK present — a guarantee `test_bare_slim_import_needs_only_mcp_types` pins. Reaching for `mcp.types` in core modules (`exceptions.py`, `_compat.py`, `tools/`, `resources/`) would pull the full SDK into the slim floor and break it.
|
||||
|
||||
The rule of thumb: import `mcp_types` in library code, write `mcp.types` in anything a user copies. Both resolve to the same objects, so neither choice constrains the other.
|
||||
|
||||
*Verify:* `.venv/.../mcp/types/__init__.py` (the wildcard mirror), `fastmcp_slim/pyproject.toml` (`mcp-types` core vs `mcp` in the `[mcp]` extra), `tests/client/test_slim_package_boundaries.py::test_bare_slim_import_needs_only_mcp_types`, and `tests/test_upgrade_from_v3.py::TestRemovedSurfacesFailLoudly::test_mcp_types_import_path_restored_by_stable_sdk`.
|
||||
|
||||
### `fastmcp.types` is the stable home — Bridged
|
||||
|
||||
<Note>
|
||||
Superseded before release — see "`fastmcp.types` trimmed to FastMCP-unique types only" below. This section documents the re-export set as it existed mid-migration; none of it ever shipped.
|
||||
</Note>
|
||||
|
||||
FastMCP re-exports the protocol types users are most likely to touch from `fastmcp.types`, sourced from `mcp_types` (the `mcp` root package lacks most of them):
|
||||
|
||||
```python test="skip"
|
||||
from fastmcp.types import TextContent, Tool, ToolAnnotations, ErrorData
|
||||
```
|
||||
|
||||
The re-export set is deliberately limited to names that trace to a documented user import: `TextContent`, `ImageContent`, `AudioContent`, `EmbeddedResource`, `ResourceLink`, `ContentBlock`, `Tool`, `Resource`, `ResourceTemplate`, `Prompt`, `PromptMessage`, `CallToolResult`, `GetPromptResult`, `ReadResourceResult`, `TextResourceContents`, `BlobResourceContents`, `SamplingMessage`, `CreateMessageResult`, `SamplingCapability`, `Root`, `ErrorData`, `Completion`, `Annotations`, `ToolAnnotations`, `Icon`, `ToolResultContent`, plus the pre-existing `Textarea`. Notification and request wrapper types (e.g. `ToolListChangedNotification`) are not re-exported — import those from `mcp_types` directly.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/types.py` `__all__`.
|
||||
|
||||
### `fastmcp.types` trimmed to FastMCP-unique types only — Absorbed (post-review cleanup)
|
||||
|
||||
The re-export set above never shipped in a release, so it was cut before 4.0 rather than deprecated. `fastmcp.types` now holds only types FastMCP defines itself — `Textarea` — and every bare `mcp_types` mirror (`TextContent`, `Tool`, `ToolAnnotations`, `ErrorData`, and the rest of the 29-name list) is gone. Code that imported those from `fastmcp.types` now imports them from `mcp_types` directly:
|
||||
|
||||
```python
|
||||
from mcp_types import TextContent, Tool, ToolAnnotations, ErrorData
|
||||
```
|
||||
|
||||
Because `fastmcp.types.__all__` was `["Textarea"]` as of the last stable release (v3.4.4) and the mirrors were added only in this unreleased migration work, removing them breaks no released user — there is no bridge or deprecation warning to write.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/types.py` `__all__` (back down to `["Textarea"]`).
|
||||
|
||||
### camelCase field reads are bridged — Bridged (deprecated)
|
||||
|
||||
Objects FastMCP hands back — results of `client.list_tools()`, `client.call_tool_mcp()`, `client.read_resource()`, and the parameter objects passed to sampling and elicitation handlers — are SDK v2 objects with snake_case fields. A compatibility bridge installed at import time routes the old camelCase names to their snake_case fields, warning once per read:
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
|
||||
|
||||
async def read_schema():
|
||||
async with Client("my_mcp_server.py") as client:
|
||||
tools = await client.list_tools()
|
||||
return tools[0].inputSchema # works, warns; prefer .input_schema
|
||||
```
|
||||
|
||||
The bridged fields are exactly those users read, data-driven from an `_ALIASES` table: `inputSchema`/`outputSchema` (Tool); `readOnlyHint`/`destructiveHint`/`idempotentHint`/`openWorldHint` (ToolAnnotations); `mimeType` (Resource, ResourceTemplate, TextResourceContents, BlobResourceContents, ImageContent, AudioContent) and `uriTemplate` (ResourceTemplate); `isError`/`structuredContent` (CallToolResult); `hasMore` (Completion); `serverInfo`/`protocolVersion` (InitializeResult); `nextCursor`/`resourceTemplates` (List\*Result); `systemPrompt`/`maxTokens`/`stopSequences`/`modelPreferences`/`toolChoice` (CreateMessageRequestParams); `requestedSchema` (ElicitRequestFormParams). WS2 verified all 29 alias entries warn correctly with actionable messages.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/_compat.py` (the `_ALIASES` table and `install()`).
|
||||
|
||||
### The bridge is a genuine runtime toggle — Absorbed (post-review fix)
|
||||
|
||||
The bridge properties install unconditionally, and each getter reads the live `mcp_camelcase_compat` setting on every access: warn-and-return when enabled, raise `AttributeError` when disabled. An earlier version installed the bridge once at import, so flipping the setting afterward did nothing — commit `d9659453` fixed this so the toggle works at runtime:
|
||||
|
||||
```python
|
||||
import fastmcp
|
||||
|
||||
fastmcp.settings.mcp_camelcase_compat = False # now takes effect immediately
|
||||
```
|
||||
|
||||
The setting is documented in [Settings](https://gofastmcp.com/more/settings) as `FASTMCP_MCP_CAMELCASE_COMPAT`.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/settings.py` (setting), `fastmcp_slim/fastmcp/_compat.py` (per-read gate), commit `d9659453`.
|
||||
|
||||
### `mcp-types` is now a core slim dependency — Absorbed (post-review fix)
|
||||
|
||||
Bare `import fastmcp` loads `mcp_types` via `_sdk_patches` and `_compat`, so a bare `fastmcp-slim` install (without the `[mcp]` extra) hit `ModuleNotFoundError`. Because `mcp-types` only pulls `pydantic` and `typing-extensions` (already core), it was promoted to a core dependency while the full `mcp` SDK stays in the `[mcp]` extra.
|
||||
|
||||
*Verify:* `fastmcp_slim/pyproject.toml` (`mcp-types==2.0.0b1` in core dependencies), commit `e16ffad4`.
|
||||
|
||||
### `McpError` is an alias; construction changed — Bridged (catch) / Breaking (construct)
|
||||
|
||||
`fastmcp.exceptions.McpError` is a plain alias of the SDK's `MCPError` — a plain alias, not a subclass, so `except McpError` still catches SDK-raised errors and `err.error.code` still reads:
|
||||
|
||||
```python
|
||||
from fastmcp.exceptions import McpError
|
||||
|
||||
try:
|
||||
...
|
||||
except McpError as err:
|
||||
print(err.error.code) # unchanged
|
||||
```
|
||||
|
||||
Construction is the one unavoidable behavior break. The v1 pattern of wrapping an `ErrorData` positionally raises `TypeError` under v2; construct with keywords instead:
|
||||
|
||||
```python
|
||||
from fastmcp.exceptions import McpError
|
||||
|
||||
# Before (raises TypeError under SDK v2):
|
||||
# raise McpError(ErrorData(code=-32000, message="Client not supported"))
|
||||
|
||||
raise McpError(code=-32000, message="Client not supported")
|
||||
```
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/exceptions.py` (`McpError = MCPError`).
|
||||
|
||||
## Server core
|
||||
|
||||
The SDK v2 rewrote the server request-handling model. FastMCP's handler layer is the most heavily rewritten part of the migration, but the public server API is unchanged.
|
||||
|
||||
### Handler adapters — Absorbed
|
||||
|
||||
Handlers are now registered by method string via `add_request_handler(method, params_type, handler)`, take a uniform `(ctx, params)` signature, and return the **bare** result model (no `ServerResult` wrapper). FastMCP's `_setup_handlers` builds one thin adapter per method (`tools/list`, `tools/call`, `resources/read`, `prompts/get`, `logging/setLevel`, …) that binds the request context, adapts params to the existing handler body, and returns the bare result. The v1 decorator overrides and `_wrap_list_handler` are deleted.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (462 lines changed), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py`.
|
||||
|
||||
### FastMCP-owned request context — Absorbed
|
||||
|
||||
The SDK's `request_ctx` ContextVar is gone; the SDK passes context to handlers as an argument only. FastMCP owns its own `fastmcp_request_ctx` ContextVar, set at the top of every adapter. It stores a FastMCP-owned `FastMCPRequestContext` wrapper rather than the raw SDK context, because the raw `ServerRequestContext.meta` is a bare `TypedDict` carrying only `progress_token` — the full `_meta` block (which holds `_meta.fastmcp.version` and the distributed-trace parent) has to be lifted out of the raw params dict. `Context.request_context` and its consumers (`report_progress`, `session_id`, telemetry trace extraction, `get_http_request`) all read through the wrapper.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/dependencies.py`, `server/context.py`, `server/telemetry.py`.
|
||||
|
||||
### `ServerMiddleware` bridge for `initialize` — Absorbed
|
||||
|
||||
Server-side middleware is a new first-class SDK concept: `Server.middleware` is a list of `ServerMiddleware` composed around every request and notification, including `initialize`. FastMCP no longer subclasses `ServerSession` (the runner constructs it), so the old `MiddlewareServerSession._received_request` override is gone. A `FastMCPServerMiddleware` is appended to the SDK's middleware list (preserving the SDK's own OpenTelemetry middleware) and intercepts `initialize` to run FastMCP's middleware chain. The v2 interface is cleaner — `call_next(ctx)` returns the serialized result directly, so the old `capturing_respond` machinery is deleted.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (`FastMCPServerMiddleware`).
|
||||
|
||||
### Middleware observes every inbound message — New (coverage)
|
||||
|
||||
FastMCP's `Middleware` chain used to begin *inside* the per-method handlers, so `on_message`/`on_request`/`on_notification` only fired for messages that reached a tool/resource/prompt handler. Notifications, cancellations, and malformed or unroutable requests were invisible to middleware. `FastMCPServerMiddleware` — FastMCP's entry in the SDK's own middleware list — is now the dispatch root: it runs the `on_message`/`on_request`/`on_notification` pass for every message the interior handlers do not dispatch (all notifications including `notifications/cancelled`, `ping`, `logging/setLevel`, unknown methods, and component requests that fail validation before the handler runs). The component methods keep their interior dispatch unchanged, so `on_call_tool` and friends still receive the typed component result and a tool exception still propagates through `on_message`/`on_request` exactly where the built-in error/logging/timing middleware expect it — each hook fires exactly once per message. Multi-round (SEP-2322) calls compose cleanly with this: each round is a complete request→response cycle through the full chain, and an asking round's `call_next` returns the ask as an ordinary `InputRequiredToolResult` value (see the MRTR entry below). All thirteen built-in middleware pass their suites unmodified. See [What middleware sees](https://gofastmcp.com/servers/middleware#what-middleware-sees).
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (`FastMCPServerMiddleware` root dispatch, `_INTERIOR_METHODS`), `fastmcp_slim/fastmcp/server/middleware/middleware.py` (`MiddlewarePhase`, `mark_interior_dispatched`), `fastmcp_slim/fastmcp/server/server.py` (`_dispatch_component_middleware`), `tests/server/middleware/test_message_visibility.py`.
|
||||
|
||||
### Per-session state re-homed to the connection — Absorbed
|
||||
|
||||
Because `ServerSession` is now per-request, per-session state can no longer live on the session object. The minimum logging level is re-homed to a FastMCP-side map keyed by session id (via `connection.session_id`), and `client_supports_extension` becomes a free function reading `session.client_params.capabilities`.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py`, `server/context.py` (`_log_to_server_and_client`).
|
||||
|
||||
### `extensions` capability read from the real field — Absorbed (post-review fix)
|
||||
|
||||
SDK v2 declares `extensions` as a real field on `ClientCapabilities`, so a client sending `ClientCapabilities(extensions={...})` populates the field, not `model_extra`. `client_supports_extension` now reads `caps.extensions` first and falls back to `model_extra` only for legacy-serialized clients.
|
||||
|
||||
*Verify:* commit `96ca0092`, `server/low_level.py` / `server/context.py`.
|
||||
|
||||
### Task protocol and the `_sdk_patches` shim — Absorbed (with an upstream gap)
|
||||
|
||||
The SEP-1686 task CRUD protocol (`tasks/get`, `tasks/result`, `tasks/list`, `tasks/cancel`) is entirely FastMCP-owned — the SDK ships no task store. Task detection moves to a params field: `params.task is not None` on `CallToolRequestParams`, with `ttl` from `params.task.ttl`. The four task handlers port to `add_request_handler`.
|
||||
|
||||
The SDK has a real gap here (see [Known Gaps](known-gaps.md) and sdk-feedback #1): it ships the task result types but omits them from the method registries, so a background-task `tools/call` returning a `CreateTaskResult` fails validation. FastMCP installs a registry-widening shim in `_sdk_patches.py` that adds `CreateTaskResult` to the `tools/call` result union and registers the `tasks/*` rows. It is a temporary patch with a self-documented removal trigger.
|
||||
|
||||
Resources and prompts have **no `task` field** on their params in b1, so task-augmented resource reads and prompt gets are not wire-expressible — a documented capability regression, tracked by xfails, not a bug FastMCP fixes.
|
||||
|
||||
This section records the migration's *handling* of the SEP-1686 wire layer as it stood at merge. That layer is not the end state: it is slated for removal and rebuild on the `io.modelcontextprotocol/tasks` extension (SEP-2663) as the `fastmcp-tasks` package. See [Background Tasks (SEP-2663)](background-tasks.md) for the forward plan; the `_sdk_patches.py` shim and the `server/tasks/*` wire handlers described here go away with it, while the Docket execution engine moves into `fastmcp-tasks`.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/_sdk_patches.py`, `server/tasks/*`.
|
||||
|
||||
### Single SERVER span per request — Absorbed (post-migration fix)
|
||||
|
||||
SDK v2 seeds an `OpenTelemetryMiddleware` into every lowlevel `Server`, so each inbound request already emits a SERVER span. FastMCP emits its own richer SERVER span per request (with `fastmcp.*` and auth/session attributes), so a server with an OTel exporter installed would export **two** SERVER spans per request under different attribute conventions. `LowLevelServer.__init__` now drops the SDK's seeded `OpenTelemetryMiddleware` (matched by type, not position, leaving any other seeded middleware intact) and keeps FastMCP's spans. Inbound W3C trace-context extraction is unaffected — FastMCP's telemetry reads `traceparent` from `_meta` itself, so distributed traces still link client to server. Client-side is not double-counted: the SDK's `ClientSession` emits a low-level `MCP send <method>` CLIENT span that nests *under* FastMCP's high-level client span, a legitimate parent/child hierarchy rather than a duplicate.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (the `OpenTelemetryMiddleware` filter); `tests/server/telemetry/test_server_tracing.py::TestSingleServerSpan`.
|
||||
|
||||
### Telemetry on by default, with a three-way mode setting — Absorbed
|
||||
|
||||
FastMCP's OpenTelemetry instrumentation is on by default. Because FastMCP uses only the OpenTelemetry API, span creation is a no-op with negligible overhead (the API's `NonRecordingSpan`) unless the user configures an SDK and exporter — so being always-on costs nothing until you opt into collection. `FASTMCP_TELEMETRY_MODE` (`fastmcp.settings.telemetry_mode`, default `native`) controls how much is active: `native` emits spans and propagates trace context; `propagation_only` emits no FastMCP spans but still extracts the incoming `_meta` context and attaches it, so downstream spans are parented to the calling trace; `off` is a full pass-through that touches neither spans nor context. The setting governs FastMCP's own spans (all SERVER spans, plus FastMCP's high-level CLIENT span); the SDK's low-level `mcp-python-sdk` `MCP send <method>` CLIENT spans are governed by the user's OpenTelemetry SDK, not this setting. `suppress_fastmcp_telemetry()` applies `propagation_only` semantics to a single block for library authors who own the MCP hierarchy for one operation rather than process-wide; it cannot override `off`. FastMCP's SERVER span now also carries `mcp.protocol.version` — the attribute the dropped SDK `OpenTelemetryMiddleware` set — restoring parity with the SDK's semantic conventions.
|
||||
|
||||
`propagation_only` is applied at the seam span, which is where the incoming `_meta` parent context is established for the whole request; suppressing only the deeper `server_span` would leave the per-request SERVER span intact and defeat the mode.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/settings.py` (`telemetry_mode`); `fastmcp_slim/fastmcp/telemetry.py` (`telemetry_mode`, `get_tracer`, `suppress_fastmcp_telemetry`); `fastmcp_slim/fastmcp/server/telemetry.py` (`_propagation_only_span`, `seam_span`, `get_protocol_span_attributes`); `tests/server/telemetry/test_server_tracing.py::TestTelemetryEnabledByDefault`, `::TestProtocolVersionAttribute`; `tests/telemetry/test_interop.py`.
|
||||
|
||||
### Spec-correct error codes via a central translator — Breaking (wire error code)
|
||||
|
||||
Resource-not-found responses from the core `resources/read` handler previously used `-32002`. SEP-2164 (and the SDK's own mcpserver, which maps `ResourceNotFoundError` → `INVALID_PARAMS`) makes this `-32602`. The per-adapter `MCPError(code=..., ...)` literals in `server/mixins/mcp_operations.py` are replaced by a single `fastmcp.exceptions.to_mcp_error()` translator that maps FastMCP's public exceptions to the `mcp_types` code constants (`NotFoundError`/`DisabledError`/`ValidationError` → `INVALID_PARAMS`, else `INTERNAL_ERROR`). Clients that string-matched on the old `-32002` for resource-not-found must switch to `-32602`; the human-readable message ("Resource not found: ...") is unchanged. The opt-in `ErrorHandlingMiddleware`, which has its own documented per-method-prefix code mapping, is intentionally left as-is.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/exceptions.py` (`to_mcp_error`); `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py`; `tests/test_exceptions.py`.
|
||||
|
||||
### `Cachable*` response-cache models renamed to `Cacheable*` — Breaking (rename) <!-- codespell:ignore -->
|
||||
|
||||
The response-caching middleware's Pydantic wrapper models — used to serialize cached tool, resource, and prompt results for `ResponseCachingMiddleware` — carried a spelling typo. `CachableToolResult`, `CachableResourceContent`, `CachableResourceResult`, `CachableMessage`, and `CachablePromptResult` are renamed to `CacheableToolResult`, `CacheableResourceContent`, `CacheableResourceResult`, `CacheableMessage`, and `CacheablePromptResult`. None of these classes are re-exported from `fastmcp` or any package `__init__.py`, so the realistic blast radius is limited to code that imported the old names directly from `fastmcp.server.middleware.caching`:
|
||||
|
||||
```python
|
||||
# Before (now raises ImportError):
|
||||
# from fastmcp.server.middleware.caching import CachableToolResult
|
||||
|
||||
# After
|
||||
from fastmcp.server.middleware.caching import CacheableToolResult
|
||||
```
|
||||
|
||||
There is deliberately no compatibility alias for the old spelling.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/middleware/caching.py`.
|
||||
|
||||
### Server-side argument completion — New (opt-in feature)
|
||||
|
||||
A FastMCP server can now answer `completion/complete` requests, suggesting values for prompt arguments and resource-template parameters as a user types. Previously a FastMCP *client* could call `complete()` but a FastMCP *server* had no way to respond — the method was unregistered, so it returned `-32601` (method-not-found) on both eras. The new `@mcp.completion` decorator registers a single server-level handler that receives the reference (a `PromptReference` or `ResourceTemplateReference`), the `CompletionArgument` being completed, and the optional `CompletionContext` of already-supplied argument values, and returns candidates — a list of strings, a `Completion` (to carry the `total`/`has_more` pagination hints), or `None`/empty for a reference it does not recognize (which yields an empty completion, not an error).
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
from mcp_types import PromptReference
|
||||
|
||||
mcp = FastMCP("Completion Server")
|
||||
|
||||
|
||||
@mcp.prompt
|
||||
def write_poem(theme: str) -> str:
|
||||
return f"Write a poem about {theme}"
|
||||
|
||||
|
||||
@mcp.completion
|
||||
def complete(ref, argument, context):
|
||||
if isinstance(ref, PromptReference) and argument.name == "theme":
|
||||
options = ["nature", "love", "adventure"]
|
||||
return [o for o in options if o.startswith(argument.value)]
|
||||
return None
|
||||
```
|
||||
|
||||
The completions capability is declared exactly when a handler exists: `add_completion_handler` registers the low-level `completion/complete` handler, and the SDK derives the capability from that handler's presence — a server with no completion handler does not advertise it. FastMCP does not hand-set the capability. The single-handler shape mirrors the SDK's own `completion/complete` surface and FastMCP's existing client-side `Client.complete()`, and it slots into the `@mcp.tool`/`@mcp.prompt`/`@mcp.resource` decorator lineup as another server-level `@mcp.<verb>` registration rather than inventing a per-argument sub-decorator idiom. It works identically on the handshake and modern (`2026-07-28`) eras, since `completion/complete` is a request/response method that flows on every era. The authoring types — `PromptReference`, `ResourceTemplateReference`, `CompletionArgument`, `CompletionContext`, and `Completion` — are imported from `mcp_types`, not `fastmcp.types`.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/completions.py` (handler type + `normalize_completion`), `fastmcp_slim/fastmcp/server/server.py` (`completion` decorator, `add_completion_handler`), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_complete`), `tests/server/test_completions.py`, `docs/servers/completions.mdx`.
|
||||
|
||||
## Client
|
||||
|
||||
The `fastmcp.Client` public API is largely preserved. The client stays a wrapper around `mcp.ClientSession`; the first-class `mcp.client.Client` is deliberately not adopted. Two client-surface changes are called out below: the connection `mode` default flips to `"auto"`, and `extensions=` / `result_claims=` are newly surfaced.
|
||||
|
||||
### Connection `mode` defaults to `"auto"` — Breaking (behavior)
|
||||
|
||||
`Client(mode=...)` now defaults to `"auto"` instead of `"legacy"`. The client probes `server/discover` and adopts the modern (`2026-07-28`) era when the server responds, denylist-falling-back to the initialize handshake for any server that is not positive evidence of a modern peer. Against a FastMCP server (which serves both eras), an ordinary `Client(url)` now negotiates the modern era by default, where the legacy-only Context push features are unavailable per the per-feature era matrix (see the *Protocol eras* section below) — server-initiated sampling/elicitation/roots, `ping`, session ids, and FastMCP task submission all require the legacy era. The one-line revert is `Client(..., mode="legacy")`, which restores byte-identical pre-v4 negotiation.
|
||||
|
||||
The SSE transport is legacy-only (it cannot carry the sessionless modern era), so a client connecting over SSE negotiates the legacy handshake even under `mode="auto"` — expressed by a `ClientTransport.legacy_only` flag set on `SSETransport`. `MCPConfigTransport` reports `legacy_only` as a property: a multi-server config is legacy-only (each backend is mounted behind a legacy-era proxy), while a single-server config mirrors its one backend transport's era so a modern Streamable HTTP backend stays modern-capable. Two internal library clients that are inherently handshake-based are pinned to legacy so the flip does not break them: the `ProxyClient` backend (which forwards the initialize handshake and server-initiated features) defaults to `mode="legacy"`, and the `inspect` utility (which reads the full `server_info` only the handshake carries) connects legacy.
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
|
||||
client = Client("https://example.com/mcp") # now negotiates "auto"
|
||||
client = Client("https://example.com/mcp", mode="legacy") # opt back into the handshake
|
||||
```
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (`mode` default, `_negotiate` `legacy_only` shortcut), `fastmcp_slim/fastmcp/client/transports/{base,sse,config}.py` (`legacy_only`), `fastmcp_slim/fastmcp/server/providers/proxy.py` (`ProxyClient` legacy default), `fastmcp_slim/fastmcp/mcp_config.py` and `fastmcp_slim/fastmcp/utilities/inspect.py` (legacy inner clients), `tests/client/client/test_mode_negotiation.py` (default, clean discover-rejection fallback, legacy-only transport), `tests/test_mcp_config.py` (single- vs multi-server `legacy_only`), `docs/clients/client.mdx`.
|
||||
|
||||
### `extensions=` / `result_claims=` surfaced — New (opt-in feature)
|
||||
|
||||
`fastmcp.Client` now accepts `extensions=` (a sequence of SEP-2133 `ClientExtension` instances) and `result_claims=` (extra `ResultClaim`s keyed by an advertised extension's identifier). Each extension's capability advertisement, result claims, and notification bindings are folded into the underlying `ClientSession` on every transport. User-supplied notification bindings **compose** with FastMCP's internal task-status binding rather than clobbering it: the task binding always leads, and a user extension that binds the same method surfaces a clear duplicate-method error at connect time rather than silently winning. Result claims are wired end-to-end: `call_tool()` / `call_tool_mcp()` pass `allow_claimed=True` and resolve a claimed result through the owning claim's resolver (`ClaimContext`), so a server-emitted claimed shape is finished into an ordinary `CallToolResult` instead of raising `UnexpectedClaimedResult`. Claimed shapes are modern-only, so they are inert on a legacy connection.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (`_build_extension_kwargs`, `_resolve_claimed_result`, `new()`), `fastmcp_slim/fastmcp/client/mixins/tools.py` (`call_tool_mcp` claim resolution), `fastmcp_slim/fastmcp/client/transports/base.py` (`SessionKwargs.extensions`/`result_claims`), `tests/client/test_client_extensions.py` (fold, composition, live both-bindings-fire, end-to-end claim resolution).
|
||||
|
||||
### Protocol helpers delegated to the SDK — Absorbed (internal)
|
||||
|
||||
`fastmcp.Client` carried forked copies of three SDK helpers — `_fold_extensions` (with its `_FoldedExtensions` dataclass), `_evicting_message_handler`, and `_synthesize_discover` — written when the SDK had not yet stabilized them. It now imports the SDK's implementations directly. The forks had already drifted: FastMCP's `_fold_extensions` was missing the SEP-2133 `validate_extension_identifier` check, so a non-reverse-DNS extension identifier that the SDK rejects was silently accepted. Adopting the SDK's version closes that gap. No public surface moves; the SDK returns `None` rather than empty collections for the folded claims and bindings, absorbed at the two call sites in `_build_extension_kwargs`.
|
||||
|
||||
Full composition — `fastmcp.Client` holding an `mcp.Client` and delegating the connection lifecycle to it — remains blocked upstream. `mcp.Client._build_session` hardcodes `ClientSession(...)` with no override hook, but FastMCP's `TransportOptions.session_class` is load-bearing: `ProxyClient` supplies a `_ForwardingClientSession` that skips output-schema validation so a backend's schema bug surfaces at the end client rather than as a proxy error. Separately, `mcp.Client.__aenter__` raises on reentry, while FastMCP's refcounted reentrant context manager is depended on by proxy session reuse. Both would need an upstream `session_factory=` hook (the same shape as the `notification_bindings=` ask that unblocked extension composition) before the lifecycle itself can be delegated.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (imports from `mcp.client.client`; no local helper definitions), `fastmcp_slim/fastmcp/client/transports/base.py` (`TransportOptions.session_class`), `fastmcp_slim/fastmcp/server/providers/proxy.py` (`_ForwardingClientSession`, `PROXY_TRANSPORT_OPTIONS`).
|
||||
|
||||
### Transports yield 2-tuples — Absorbed
|
||||
|
||||
All SDK transports (`streamable_http_client`, `sse_client`, `stdio_client`) now yield a 2-tuple `(read, write)` instead of exposing a third `get_session_id` element. HTTP configuration flows through a caller-supplied `http_client=`. Only the tuple unpack changed on the FastMCP side.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/transports/http.py`, `transports/sse.py`, `transports/stdio.py`.
|
||||
|
||||
### Float timeouts; `timedelta` still accepted — Absorbed
|
||||
|
||||
The SDK session and call timeouts are now plain floats. FastMCP's public `Client(timeout=...)` still accepts a `timedelta`, a plain float, or an int, normalizing through the existing `normalize_timeout_to_seconds` at the `SessionKwargs` chokepoint:
|
||||
|
||||
```python
|
||||
from datetime import timedelta
|
||||
|
||||
from fastmcp import Client
|
||||
|
||||
client = Client("my_mcp_server.py", timeout=timedelta(seconds=30)) # still works
|
||||
client = Client("my_mcp_server.py", timeout=30.0) # also works
|
||||
```
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/transports/base.py` (`SessionKwargs.read_timeout_seconds: float | None`), `client/client.py`.
|
||||
|
||||
### Connection settings passed to `connect_session` — Breaking (custom transports)
|
||||
|
||||
`ClientTransport.connect_session` takes a new keyword-only `transport_options: TransportOptions | None`, describing how the connecting client wants its session built: which `ClientSession` class to instantiate, and whether to forward the caller's authorization header upstream. Proxies use it to relay backend results without enforcing their output schema (see [Proxy Servers](https://gofastmcp.com/servers/providers/proxy#tool-results-are-relayed-not-inspected)).
|
||||
|
||||
These settings previously lived on the transport instance, so a transport shared between clients leaked one client's configuration into another — including credential forwarding, which `create_proxy(some_client)` would silently enable on the caller's own client. They now travel with the client that wants them, and `forward_incoming_headers` is no longer a settable transport attribute.
|
||||
|
||||
A client only passes the argument when it wants non-default settings, so an ordinary `Client` is unaffected and transports that don't accept it keep working. A custom `ClientTransport` used as a *proxy backend* must accept and honor it:
|
||||
|
||||
```python
|
||||
import contextlib
|
||||
|
||||
from fastmcp.client.transports.base import ClientTransport, TransportOptions
|
||||
|
||||
class MyTransport(ClientTransport):
|
||||
@contextlib.asynccontextmanager
|
||||
async def connect_session(self, *, transport_options=None, **session_kwargs):
|
||||
options = transport_options or TransportOptions()
|
||||
async with options.session_class(read, write, **session_kwargs) as session:
|
||||
yield session
|
||||
```
|
||||
|
||||
A transport that wraps others must pass it along; `MCPConfigTransport` forwards it to both its single-server delegate and its composite server.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/transports/base.py` (`TransportOptions`), the four built-in transports, `transports/config.py`, and `tests/server/providers/proxy/test_proxy_server.py`.
|
||||
|
||||
### `get_session_id` via header sniff — Bridged
|
||||
|
||||
The SDK dropped `get_session_id` from the streamable-HTTP transport with no replacement (the SDK source has an author TODO acknowledging it breaks the Transport protocol). FastMCP reconstructs it by registering an httpx2 response event hook on the client it owns, capturing the `mcp-session-id` response header (httpx2 preserves httpx's `event_hooks` API). The removal trigger is the upstream TODO.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/transports/http.py` (`_capture_session_id`, `get_session_id`).
|
||||
|
||||
### Pagination via `params=` — Absorbed
|
||||
|
||||
The SDK's `cursor=` kwarg on `list_*` is gone; pagination now flows through `params=PaginatedRequestParams(cursor=...)`. FastMCP's public `cursor=` on the `list_*_mcp` methods is preserved and translated internally.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/mixins/{tools,resources,prompts}.py`.
|
||||
|
||||
### OAuth `callback_handler` returns `AuthorizationCodeResult` — Breaking (advanced)
|
||||
|
||||
The one OAuth break: a custom `callback_handler` must return an `AuthorizationCodeResult` (fields `code`, `state`, `iss`) instead of the old `tuple[str, str | None]`. Everything else in the OAuth surface — `OAuthClientProvider` kwargs, `TokenStorage`, `async_auth_flow` — is unchanged.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/auth/oauth.py`.
|
||||
|
||||
### Notification dispatch unwrapped — Absorbed
|
||||
|
||||
The client's notification handling was reworked for the v2 message model. Custom server-to-client notifications (like SEP-1686 `notifications/tasks/status`) are no longer tee'd to a user `message_handler` — the SDK routes them only through `NotificationBinding` (see sdk-feedback #8). FastMCP registers a binding so task-status updates reach the Task registry.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/messages.py`, `client/tasks.py`.
|
||||
|
||||
### `SDKServer` alias — Absorbed (post-review rename)
|
||||
|
||||
The in-memory transport resolves the low-level server per server type. The alias for the SDK's own `MCPServer` was renamed from the misleading `FastMCP1Server` / `FastMCP1x` to `SDKServer`, since it names the SDK v2 server, not a FastMCP 1.x object.
|
||||
|
||||
*Verify:* commit `5c3b82e4`; `client/client.py`, `client/transports/memory.py`, `server/providers/proxy.py`, `cli/run.py`.
|
||||
|
||||
### Proxy request-context stash — Absorbed (post-review fix)
|
||||
|
||||
Proxy forwarding handlers stash the request context so a backend that issues a server-initiated request (list_roots/sampling/elicitation) can relay it back to the proxy's own client. This stash was initially applied only on the tool path; commit `1ac166bd` extended it to proxied resources, templates, and prompts.
|
||||
|
||||
*Verify:* commit `1ac166bd`, `server/providers/proxy.py`.
|
||||
|
||||
### Shared response cache via `KeyValueResponseCacheStore` — New
|
||||
|
||||
The SDK's client response cache (SEP-2549) reads and writes through a pluggable `ResponseCacheStore`; the default is a per-client in-memory LRU. FastMCP adds `KeyValueResponseCacheStore`, an adapter over the same `AsyncKeyValue` key-value abstraction the event store and OAuth proxy already use, so a fleet of clients (e.g. proxy replicas) can share one Redis-backed response cache. Pass it via `CacheConfig(store=...)`; a custom store requires an explicit `partition` (SDK) and `target_id` (FastMCP). Results serialize through a type-tagged envelope validated against an allowlist of cacheable result models — an unknown tag is a cache miss, never an import-by-name — and each adapter owns its own collection so `clear()` never touches another tenant.
|
||||
|
||||
```python
|
||||
from fastmcp.client.caching import KeyValueResponseCacheStore
|
||||
from mcp.client.caching import CacheConfig
|
||||
from key_value.aio.stores.redis import RedisStore
|
||||
|
||||
store = KeyValueResponseCacheStore(storage=RedisStore(url="redis://localhost"))
|
||||
config = CacheConfig(store=store, partition="tenant-a", target_id="weather-api")
|
||||
```
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/caching.py`, `tests/client/client/test_kv_response_cache.py`.
|
||||
|
||||
### Machine-to-machine client auth — New (feature)
|
||||
|
||||
`fastmcp.client.auth` gains two browser-free auth providers for the OAuth 2.0 `client_credentials` grant, closing the most common client-auth gap (previously only interactive `OAuth` and static `BearerAuth` were available). `ClientCredentialsOAuthProvider(client_id=..., client_secret=...)` authenticates with a client ID and secret; `PrivateKeyJWTOAuthProvider(client_id=..., assertion_provider=...)` uses an RFC 7523 `private_key_jwt` assertion (workload identity federation or a locally signed JWT via the re-exported `SignedJWTParameters` / `static_assertion_provider` helpers). Both are thin wrappers over the SDK's `mcp.client.auth.extensions.client_credentials` providers and implement `httpx2.Auth`, so they slot into the same `Client(auth=...)` path as every other provider. Like interactive `OAuth`, they take the MCP server URL (the token endpoint is discovered from OAuth metadata) and bind to it lazily — omit `mcp_url` and the transport supplies it. In-memory token storage is the default with no warning, since a lost M2M token is re-acquired in one non-interactive request.
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.auth import ClientCredentialsOAuthProvider
|
||||
|
||||
auth = ClientCredentialsOAuthProvider(client_id="id", client_secret="secret")
|
||||
async with Client("https://example.com/mcp", auth=auth) as client:
|
||||
await client.list_tools()
|
||||
```
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/auth/client_credentials.py`, `fastmcp_slim/fastmcp/client/transports/{http,sse}.py`, `tests/client/auth/test_client_credentials.py`.
|
||||
|
||||
## HTTP
|
||||
|
||||
The maintainer asked whether FastMCP can now delete its custom HTTP app and let the SDK's `Server.streamable_http_app()` handle everything. The answer for this PR is **no** — every override earns its keep. Convergence is a v4 project gated on three upstream additions (see [Feature Program](feature-program.md)).
|
||||
|
||||
### Kept overrides — Absorbed
|
||||
|
||||
Four overrides survive, each for a concrete reason:
|
||||
|
||||
1. **Event-store session scoping.** The SDK hands every per-session transport the *same* `event_store` object, one stream-ID keyspace shared across sessions. FastMCP's `FastMCPStreamableHTTPSessionManager` returns a fresh `SessionScopedEventStore(shared, session_id=…)` per session, so resumability events don't leak across sessions.
|
||||
2. **Lifespan reconciliation.** The SDK builder enters the bare lowlevel `Server.lifespan` (which yields `{}`). FastMCP drives its own `_lifespan_manager` — ref-counted for mounts, Ctrl-C-shielded, docket-aware. The SDK path silently skips all of it, so FastMCP sets the server lifespan to delegate to `_lifespan_manager` and lets the manager enter it once.
|
||||
3. **Graceful transport termination.** FastMCP's lifespan `finally` drains the manager's server instances via `transport.terminate()` before task-group cancel, fixing the Uvicorn "returned without completing response" edge (#3025). The SDK just cancels.
|
||||
4. **User ASGI middleware hook.** The SDK builder hardcodes an empty middleware list and only appends auth. FastMCP's `http_app(middleware=...)` and `RequestContextMiddleware` have nowhere to go in the SDK path.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/http.py`, `server/event_store.py`, `server/mixins/lifespan.py`.
|
||||
|
||||
### DNS-rebinding ownership — Absorbed (security)
|
||||
|
||||
FastMCP owns DNS-rebinding protection through its `HostOriginGuardMiddleware`, which is more expressive than the SDK's and is the documented surface. To avoid two allowlists double-blocking with confusing errors from two layers, FastMCP **always** disables the SDK's layer by passing `TransportSecuritySettings(enable_dns_rebinding_protection=False)` to the manager — both when FastMCP's protection is on (so they don't double-block) and when it's off (so the SDK's default-on flip can't silently re-enable it).
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/http.py` (`enable_dns_rebinding_protection=False`, `HostOriginGuardMiddleware`).
|
||||
|
||||
### httpx2 replaces httpx — Breaking (custom client/factory, typing) / Absorbed (everything else)
|
||||
|
||||
SDK v2.0.0b2 replaces `httpx` + `httpx-sse` with [httpx2](https://pypi.org/project/httpx2/) (`>=2.5.0`), a next-generation httpx fork with built-in SSE. httpx2 is a near drop-in fork: the public API (`AsyncClient`, `Auth`, `Request`, `Response`, `Timeout`, `MockTransport`, exception hierarchy, `event_hooks`) matches httpx name-for-name. The SDK duck-types the client you hand it — `streamable_http_client(http_client=...)` and `sse_client(httpx_client_factory=...)` are type-hinted `httpx2.AsyncClient` with no `isinstance` gate — but the objects that cross into the SDK must be httpx2.
|
||||
|
||||
FastMCP now uses **httpx2 exclusively** and no longer depends on `httpx`. Every FastMCP-owned HTTP path moves to httpx2: the client transports (`client/transports/{base,http,sse}.py`), client auth (`client/auth/{oauth,bearer}.py` — `BearerAuth`/`OAuth` subclass `httpx2.Auth`), the client-side exception-group handler (`utilities/exceptions.py`), the proxy's upstream client (`server/providers/proxy.py`), the `MCPConfig` client-auth field (`mcp_config.py`), **and** all the server-side code that the earlier migration pass had left on httpx — the ~15 server auth providers' upstream IdP calls, the OpenAPI provider, `from_openapi`/`from_fastapi`, `version_check`, `resources/types.py`, the SSRF download guard, and the `apps_dev` CLI. `httpx` is dropped from the `mcp` extra entirely (it may still arrive transitively via other libraries, but FastMCP never imports it). The ~170 `httpx_mock` calls across the security-critical server-auth test files are ported to a local httpx2-backed `httpx_mock` fixture (`tests/utilities/httpx2_mock.py`) that preserves the `add_response`/`add_exception`/`get_request(s)` API verbatim, so `pytest-httpx` is dropped too.
|
||||
|
||||
User-visible deltas:
|
||||
|
||||
- **Custom client factory / client.** `StreamableHttpTransport(httpx_client_factory=...)`, `SSETransport(httpx_client_factory=...)`, and `OAuth(httpx_client_factory=...)` factories must now return `httpx2.AsyncClient`; a custom `httpx.Auth` passed as `Client(auth=...)` should become `httpx2.Auth`. httpx2 is a drop-in fork, so the change is an import swap (`import httpx` → `import httpx2`). This is a typing break; at runtime a duck-compatible httpx client still satisfies the SDK, but mixing `httpx.Timeout`/`httpx.Auth` with an httpx2 client is unsupported.
|
||||
- **OpenAPI client.** `FastMCP.from_openapi(client=...)` and `OpenAPIProvider(client=...)` are now type-hinted `httpx2.AsyncClient`. There is no `isinstance` gate, so an existing `httpx.AsyncClient` still works at runtime via duck-typing this release; the typing nudges you to httpx2.
|
||||
- **TLS trust store.** httpx2 verifies TLS against the OS trust store via `truststore` (honoring `SSL_CERT_FILE`/`SSL_CERT_DIR` first) instead of the bundled certifi CA set. This now applies to **all** FastMCP HTTP, including server-auth upstream IdP calls — not just the client path. Corporate-CA and certifi-pinned setups may see different trust behavior.
|
||||
- **Logger renames.** FastMCP HTTP now logs under `httpx2` and `httpcore2.*` (was `httpx`/`httpcore.*`). Anyone filtering FastMCP HTTP logs by logger name must update the names.
|
||||
|
||||
The session-id header hook (below) works unchanged: httpx2 keeps httpx's `event_hooks` API. FastMCP's tool/resource/prompt handlers still map upstream 429/timeout errors to actionable `ToolError`/`ResourceError`; because a user's own tool may raise from either library, `server/server.py` catches both `httpx2` and (if installed) legacy `httpx` `HTTPStatusError`/`TimeoutException` via a defensive `try: import httpx` shim.
|
||||
|
||||
*Verify:* `fastmcp_slim/pyproject.toml` (`mcp` extra lists only `httpx2`); no FastMCP source imports `httpx` except the documented defensive shim in `server/server.py`.
|
||||
|
||||
## Protocol eras
|
||||
|
||||
The SDK v2 serves multiple protocol eras from one server, and FastMCP formally embraces this.
|
||||
|
||||
### Dual-era serving — Absorbed (supersedes "latest only")
|
||||
|
||||
A single FastMCP server now handles clients across the protocol transition: the session-based handshake eras (through 2025-11-25) and the sessionless `2026-07-28` era (capability discovery via `server/discover`) simultaneously. This supersedes FastMCP's earlier "latest protocol only" stance.
|
||||
|
||||
### Per-feature era matrix — Breaking (feature availability by era)
|
||||
|
||||
The push-style Context features that require the server to call back into the client are unavailable on the sessionless `2026-07-28` era, because that era removes server-initiated requests (SEP-2577). The request/response features flow on every era.
|
||||
|
||||
| Context feature | Session-based eras | `2026-07-28` (sessionless) |
|
||||
| --- | --- | --- |
|
||||
| `ctx.info` / logging notifications | Supported | Supported |
|
||||
| Tools, resources, prompts, completions | Supported | Supported |
|
||||
| `ctx.elicit` (imperative) | Supported | Not on the back-channel — use [elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol) |
|
||||
| `ctx.sample` / `ctx.sample_step` | Not in the API | Not in the API — call an LLM server-side |
|
||||
| `ctx.list_roots` | Not in the API | Not in the API — take paths as arguments, or use the [guard pattern](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol) |
|
||||
| `client.set_logging_level()` | Supported | Raises — `logging/setLevel` is absent from the era's registry |
|
||||
| Background tasks (`task=True`) | Runs synchronously — never tasked | Supported via the tasks extension |
|
||||
|
||||
Tools that rely on `ctx.elicit` continue to work against clients on the session-based eras; on the modern era, elicitation is reachable through the multi-round "guard" pattern instead (a tool returns an `InputRequiredResult`; see the New entry below). Sampling and roots have no era row to speak of — they left the server API entirely (see the Removed entry below).
|
||||
|
||||
Ordinary `ctx.info` usage emits an SDK-level `MCPDeprecationWarning` ("The logging capability is deprecated as of 2026-07-28 (SEP-2577)"). That warning comes from the SDK, not FastMCP, and is benign — logging *notifications* ride the request's own stream and work on every era, including the modern one. The upgrade guide calls it out explicitly.
|
||||
|
||||
Wire interop across the transition is verified: a 3.4.3 client against a v4 server and a v4 client against a 3.4.3 server are bidirectionally clean across 9 operations over HTTP (WS2).
|
||||
|
||||
*Verify:* `docs/getting-started/upgrading/from-fastmcp-3.mdx` (the published matrix and SDK-warning note), `tests/server/test_protocol_eras.py`.
|
||||
|
||||
### Server-initiated sampling and roots removed from the server API — Breaking
|
||||
|
||||
FastMCP 4 is a modern MCP toolkit, so the capabilities the modern protocol removed are not in its server-authoring API. `Context.sample()`, `Context.sample_step()`, and `Context.list_roots()` are gone, along with the whole `fastmcp/server/sampling/` package (`SamplingTool`, `SampleStep`, `SamplingResult`, the tool loop, structured-result sampling) and the server-side handler arguments `FastMCP(sampling_handler=..., sampling_handler_behavior=...)`. These were previously deprecated-and-era-gated; they are now absent. Calling them raises `AttributeError`; the constructor kwargs raise a `TypeError` naming SEP-2577 and the migration.
|
||||
|
||||
The motivating failure is that the gate had become the default experience. `Client` now defaults to `mode="auto"`, which negotiates `2026-07-28` against a FastMCP server, so an unmodified `ctx.sample()` server failed on an ordinary client connection. Four shipped examples (`examples/sampling/`) were broken by that flip; they are deleted rather than ported, and remain available on `release/3.x`.
|
||||
|
||||
Server-initiated sampling and roots are *requests* — the server sends one and blocks for the answer — which needs a back-channel the sessionless protocol does not have. What the protocol removed is the *pushing*, not the asking: both capabilities remain reachable through the guard pattern, where a tool returns an `InputRequiredResult` whose `input_requests` map carries a `CreateMessageRequest` or a `ListRootsRequest`, the client answers it, and the tool re-runs and reads `ctx.input_responses`. `Client._drive_input_required()` dispatches those to the same `sampling_handler` / `roots` handler a handshake-era server would have pushed to, and `tests/conformance/server.py` exercises both routes. For roots that guard round is the recommended modern path. For generation it is available but usually the wrong tool — each round is a full request-response cycle, so an agentic loop exhausts the round-trip budget — and the recommended migration stays a direct LLM call from the server.
|
||||
|
||||
**What is deliberately kept.** Client-side `Client(sampling_handler=..., roots=...)` and the provider handlers (anthropic/openai/google_genai) stay: a FastMCP client must still answer a legacy server's requests, and removing them would break interop with older servers. `docs/clients/sampling.mdx` and `docs/clients/roots.mdx` stay as real documentation. Logging is untouched — `ctx.log`/`info`/`debug`/`warning`/`error` are notifications that ride the request's own stream and work on every era.
|
||||
|
||||
**Proxy relay.** `ProxyClient`'s default `roots` and `sampling_handler` are client-side handlers that relay a handshake-era backend's requests to the proxy's own front client. They are kept, because a proxy is a client to its backend and falls squarely under the interop guarantee above. They no longer route through the removed `Context` methods: both now call the SDK session directly (`ctx.session.list_roots()` / `ctx.session.create_message()`), an internal path with no public authoring surface. The relay is reachable only when both legs speak the handshake era.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/context.py` (no `sample`/`sample_step`/`list_roots`), `fastmcp_slim/fastmcp/server/server.py` (`_REMOVED_KWARGS`), `fastmcp_slim/fastmcp/server/providers/proxy.py` (`default_proxy_roots_handler`, `default_proxy_sampling_handler`), `docs/servers/sampling.mdx` (rewritten in place as the explainer), `tests/server/test_protocol_eras.py` (`test_removed_server_initiated_methods_are_absent`), `tests/server/providers/proxy/test_proxy_client.py` (relay still green).
|
||||
|
||||
### `client.set_logging_level()` era-gated — Breaking (modern era)
|
||||
|
||||
`logging/setLevel` asks a server to remember a level for the rest of the session, and it is absent from the `2026-07-28` method registry because that era has no session to remember it in. It previously surfaced the SDK's opaque "Method not found". `Client.set_logging_level()` now raises a `RuntimeError` naming the era and pointing at level-filtering in the client's `log_handler`; it is unchanged on handshake-era connections. It is never a silent no-op.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (`set_logging_level`), `tests/server/test_protocol_eras.py` (`test_set_logging_level_is_era_gated_on_modern`).
|
||||
|
||||
### Push-feature degradation quality — Resolved (was sdk-feedback #10)
|
||||
|
||||
On a `2026-07-28` connection `ctx.elicit` used to surface a bare "Method not found", because it attaches a `related_request_id` and reaches client dispatch before failing. FastMCP now era-gates `ctx.elicit` to raise a clear, era-aware `ToolError` before the wire ("elicitation via server-initiated requests is unavailable on 2026-07-28 connections."). The strict xfail that captured #10 is flipped to a passing test. The sampling half of #10 is moot: `ctx.sample` no longer exists.
|
||||
|
||||
*Verify:* `tests/server/test_protocol_eras.py` (`test_elicit_degradation_message_is_clear_on_modern`, now a real test), `server/context.py` (era gate).
|
||||
|
||||
### Server-level cache hints (SEP-2549) — New (opt-in feature)
|
||||
|
||||
A FastMCP server can emit SEP-2549 freshness hints so a caching client (`fastmcp.Client(cache=...)`) may reuse a response without a wire round-trip. Two constructor params carry it: `FastMCP(cache_ttl=300, cache_scope="public")`, where `cache_ttl` is in seconds and `cache_scope` is `"public"` or `"private"` (default `"private"` when a TTL is set). The hint is uniform by construction — one server-level value applies to every SDK-cacheable method (`tools/list`, `prompts/list`, `resources/list`, `resources/templates/list`, `resources/read`, and `server/discover`) with no per-component surface and no aggregation. FastMCP does not hand-set the wire fields: it passes the hint through to the SDK low-level `Server(cache_hints=...)`, whose runner fills `ttlMs`/`cacheScope` on every cacheable result via `apply_cache_hint`, leaving any field a handler set explicitly untouched. `cache_ttl` must be positive, and a `cache_scope` without a `cache_ttl` is rejected at construction (a scope alone does not enable caching, since the client gates on the TTL's presence). Absent both params, no hint is emitted. Honoring is modern-only (the SDK client reads hints only at `2026-07-28`) and opt-in on the client, so a hinted server is inert unless the client passes `cache=`.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/caching.py` (`build_cache_hints`), `fastmcp_slim/fastmcp/server/server.py` (constructor params passed to `LowLevelServer(cache_hints=...)`), `tests/server/test_cache_hints.py` (unit validation + end-to-end interop with `fastmcp.Client(cache=True)`).
|
||||
|
||||
### Elicitation on the modern protocol (SEP-2322), guard form — New (opt-in feature)
|
||||
|
||||
A tool can gather client input across rounds on a `2026-07-28` call by returning an `InputRequiredResult` (see [Elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)). Each round is a complete request→response cycle: the tool re-runs per round and reads the client's answers off two new `Context` properties, `ctx.input_responses` (`None` on the first round) and `ctx.request_state` (the echoed opaque state) — thin passthroughs matching the SDK's mcpserver semantics. This is the modern-era elicitation path the earlier per-feature matrix flagged as "MRTR rewrite pending"; it mirrors the SDK's base guard model exactly (tool re-runs, checks whether answers are present, returns to ask for more), with no FastMCP-invented resolver or annotation layer. For authoring these requests, `InputRequiredResult`, `ElicitRequest`, and `ElicitRequestFormParams` import from `mcp_types`. The `request_state` channel is sealed by the framework, not the author: FastMCP installs the SDK's `RequestStateBoundary` middleware on its low-level server, which seals every outgoing `request_state` and unseals and verifies every inbound echo before a tool runs — so a tool only ever sees plaintext and a tampered, expired, or foreign token is rejected with a frozen wire error. `FastMCP(request_state_security=RequestStateSecurity(keys=[...]))` supplies shared keys for multi-replica deployments; omitted, each process seals under an ephemeral key (correct single-process). Returning this result on a handshake-era (≤ 2025-11-25) connection raises a clear era error naming the mismatch rather than failing as a generic invalid result. The client half (`fastmcp.Client` at `mode="auto"`) drives the loop through its existing elicitation/sampling/roots handlers, capped by `input_required_max_rounds`.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/context.py` (`input_responses`/`request_state` properties), `fastmcp_slim/fastmcp/server/low_level.py` (`RequestStateBoundary` install), `fastmcp_slim/fastmcp/server/server.py` (`request_state_security` param), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_call_tool` input-required passthrough + era gate), `fastmcp_slim/fastmcp/tools/base.py` (`InputRequiredToolResult`), `tests/server/test_mrtr_guards.py`.
|
||||
|
||||
### Proxy era mirroring — New (behavior)
|
||||
|
||||
A proxy is a server on its front and a client on its back, and the two eras have mutually exclusive interaction models on a single session: the handshake era pushes server-initiated requests (sampling/elicitation/roots) that the proxy forwards to its client, while the modern era forbids those and round-trips a guard tool's `InputRequiredResult` as a result instead. A proxy created from a non-Client target with no explicit `mode` now MIRRORS the front connection's negotiated era onto its backend session per request, so the whole chain speaks one era end-to-end — a modern client reaches a modern backend (guard round-trips work), a handshake client reaches a handshake backend (push-forwarding works), and the same proxy serves both without a backend session ever crossing eras. Because the default factory builds a fresh backend client per request and derives its `mode` from the front era at call time, only the metadata-only component caches are shared across eras. An explicit `create_proxy(target, mode=...)` still pins the backend era regardless of the front, overriding mirroring for a backend that only speaks one era; the resulting cross-era feature mismatches surface through the existing era gates. `ProxyInitializeMiddleware` no longer force-calls the handshake-only `client.initialize()` when the backend negotiated the modern era, so an explicit modern pin behind a handshake front no longer crashes on connect. The mirrored era carries through a multi-server `MCPConfig` target as well: that form mounts one proxy per configured server onto a composite router, and `TransportOptions.backend_mode` hands the era down to those mounted legs so every real backend negotiates it, not just the router in front of them. That router is also now sealed under a policy held on the transport rather than a fresh per-router ephemeral key, so a guard tool's `request_state` survives the router being rebuilt between rounds.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/providers/proxy.py` (`_mirror_front_era_mode`, the `_create_client_factory` non-Client branch, the era guard in `ProxyInitializeMiddleware.on_initialize`), `fastmcp_slim/fastmcp/client/transports/base.py` (`TransportOptions.backend_mode`), `fastmcp_slim/fastmcp/client/transports/config.py` (`MCPConfigTransport.connect_session` / `_create_proxy`), `fastmcp_slim/fastmcp/server/server.py` (`create_proxy` docstring), `tests/server/test_mrtr_guards.py` (`TestProxyEraMirroring`, `TestMultiServerConfigEraMirroring`).
|
||||
|
||||
### Resource and prompt errors survive the modern era — Absorbed (defect fix)
|
||||
|
||||
`_on_call_tool` returns a `ResourceError`-equivalent as an error result, but `_on_read_resource` and `_on_get_prompt` caught only `DisabledError`/`NotFoundError`, so a `ResourceError`, `PromptError`, or an argument-conversion failure on a resource template escaped as a raw handler exception. On the handshake eras that reached the wire as `str(exc)`, which is survivable; on `2026-07-28` the runner masks anything that is not an `MCPError` or `ValidationError` as a generic `"Internal server error"`, so a legitimate client-input error became indistinguishable from a server bug. Both handlers now translate a `FastMCPError` through `to_mcp_error` the way tools already do. Masking is unchanged — `mask_error_details` is still applied inside `read_resource`/`render_prompt`, so these paths leak no more than tools do.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_read_resource`, `_on_get_prompt`), `tests/server/test_protocol_eras.py`.
|
||||
|
||||
### Proxies forward upstream instructions on the modern era — Absorbed (defect fix)
|
||||
|
||||
`ProxyInitializeMiddleware` forwards an upstream server's `instructions` by patching the `InitializeResult`, but `on_initialize` only fires for the handshake era. A modern client negotiates via `server/discover`, which the SDK builds from the low-level server's own `instructions`, so a proxy silently dropped its upstream's instructions for every modern client. `FastMCPProxy` now registers a `server/discover` handler (the same `add_request_handler` hook it already uses for `ping`, and a replacement the SDK explicitly sanctions) that delegates to the SDK's own implementation and fills in only the instructions that would otherwise be lost. The proxy's lazy-connect contract is unchanged: the backend is contacted when a client asks, never at construction. Because era mirroring pins a modern backend to an exact version — and a pinned version adopts a synthesized `DiscoverResult` rather than probing the wire — this read negotiates with `mode="auto"`; instructions are metadata with no back-channel, so they do not need the era consistency mirroring exists to protect.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/providers/proxy.py` (`FastMCPProxy._setup_proxy_discover_handler`), `tests/server/providers/proxy/test_proxy_server.py` (`TestProxyModernEraInstructions`).
|
||||
|
||||
### Proxy list methods raise `MCPError` on backend failure — Breaking (in-process error type)
|
||||
|
||||
`ProxyProvider`'s four `_list_*` methods caught only `MCPError`, so a failed backend connection escaped as the `RuntimeError` the client wraps it in (or a raw `httpx2.ConnectError`). On the handshake eras that reached the wire as `str(exc)` and named the real failure; on `2026-07-28` it was masked as `"Internal server error"`, leaving a modern client unable to tell a dead backend from a server bug. The list methods now normalize transport failures through `_proxy_upstream_error`, matching `ProxyInitializeMiddleware.on_initialize`. Code calling a proxy's `list_tools()` (and friends) in-process must now catch `MCPError` rather than `RuntimeError`; the over-the-wire error type is unchanged.
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/providers/proxy.py` (`_PROXY_TRANSPORT_ERRORS` and the four `_list_*` methods), `tests/server/providers/proxy/test_proxy_server.py` (`TestProxyProviderTransportErrors`).
|
||||
|
||||
### The xfail register — Known gap
|
||||
|
||||
Roughly forty `xfail` markers across the test tree (concentrated in `tests/server/tasks/`, `tests/client/tasks/`, and `test_protocol_eras.py`) are the built-in beta tracker: each names the SDK gap it waits on. They are enumerated and mapped to sdk-feedback findings on the [Known Gaps](known-gaps.md) page.
|
||||
|
||||
## Security
|
||||
|
||||
FastMCP retains hardening that is not yet upstream and does not remove it during the migration.
|
||||
|
||||
### Retained OAuth / DCR hardening — Absorbed
|
||||
|
||||
FastMCP keeps its own DCR redirect-URI hardening (PRs #4419, #4408) regardless of the SDK's validation, which still accepts unsafe `javascript:`/`data:` redirect schemes at the model level (sdk-feedback #4). The streamable-HTTP DNS-rebinding protection above is a second retained security surface.
|
||||
|
||||
*Verify:* recent commits `67527c1f` (block unsafe OAuth redirect schemes), `57a27992` (DNS rebinding), `cccb529f` (DCR redirect URI validation) on `main`.
|
||||
|
||||
### Identity assertion (SEP-990 ID-JAG) — Added (beta)
|
||||
|
||||
`OAuthProxy` (and `OIDCProxy`, which inherits it) accepts an optional `identity_assertion=IdentityAssertion(trusted_issuers=[...])`. When configured, the token endpoint accepts the RFC 7523 `urn:ietf:params:oauth:grant-type:jwt-bearer` grant carrying an enterprise IdP-issued ID-JAG, validates it (signature against the trusted issuer's JWKS, `iss`/`aud`/`exp`, `typ` of `oauth-id-jag+jwt`, mandatory `sub`, signed `client_id`/`resource` binding, and `jti` replay rejection), and mints a short-lived FastMCP access token carrying the asserted subject with no refresh token. Authorization server metadata advertises the `jwt-bearer` grant type and the `urn:ietf:params:oauth:grant-profile:id-jag` profile when enabled. This is server-side only; the client-side wrapper ships separately. See [Identity Assertion](https://gofastmcp.com/servers/auth/oauth-proxy#identity-assertion-sep-990).
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/server/auth/identity_assertion.py`, the `exchange_identity_assertion` and `get_routes` changes in `fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py`, and the jwt-bearer dispatch in `fastmcp_slim/fastmcp/server/auth/auth.py` (`TokenHandler._maybe_handle_id_jag`).
|
||||
|
||||
### Templated resource parameters are path-screened by default — Breaking (behavior)
|
||||
|
||||
Every templated resource now has its extracted parameter values screened for path-traversal (`..` segments), absolute paths, and null bytes **before the handler runs** — on by default, at the server's read chokepoint, covering local and provider-sourced (mounted/proxied) templates alike. Previously these payloads reached handlers raw; a template whose parameter flowed into a filesystem path or upstream URL was exposed unless the author added their own check. A rejected read now surfaces a non-leaky "resource not found" error (`-32602`) and a debug log.
|
||||
|
||||
The check is component-based, matching the SDK's `contains_path_traversal`: only a standalone `..` segment is traversal, so values that merely contain dots (`HEAD~3..HEAD`, `file.tar.gz`) and dotfiles (`.env`) still pass. This can break a template that legitimately accepts `..`-bearing or absolute values — exempt the parameter with `ResourceSecurity(exempt_params={...})`, disable per-component with `security=None`, or set a server-wide default with `FastMCP(resource_security=...)`. See [Resources → Path Security](https://gofastmcp.com/servers/resources#path-security).
|
||||
|
||||
*Verify:* `fastmcp_slim/fastmcp/resources/security.py` (`ResourceSecurity`), the screening block in `FastMCP.read_resource` (`fastmcp_slim/fastmcp/server/server.py`), and `tests/resources/test_resource_security.py`.
|
||||
|
||||
## Removed in 4.0
|
||||
|
||||
Deprecations that warned in 3.x are removed in 4.0. Each entry below is a hard removal — the old surface raises `TypeError` / `AttributeError` rather than warning, unless noted otherwise.
|
||||
|
||||
### Module and class shims
|
||||
|
||||
- **`fastmcp.server.proxy`** (deprecated 3.0) — Breaking. Import proxy classes (`FastMCPProxy`, `ProxyClient`, etc.) from `fastmcp.server.providers.proxy` instead.
|
||||
- **`fastmcp.server.openapi`** and its submodules (`server`, `components`, `routing`), including the **`FastMCPOpenAPI`** class (deprecated 3.0) — Breaking. Use `FastMCP` with an `OpenAPIProvider` from `fastmcp.server.providers.openapi` instead.
|
||||
- **`fastmcp.experimental.server.openapi`** and **`fastmcp.experimental.utilities.openapi`** shims (deprecated 2.14) — Breaking. Import from `fastmcp.server.providers.openapi` and `fastmcp.utilities.openapi` respectively.
|
||||
- **`fastmcp.server.apps`** and **`fastmcp.server.app`** shims (deprecated 3.2) — Breaking. Import from `fastmcp.apps` (e.g. `AppConfig`) or `fastmcp` (`FastMCPApp`) instead.
|
||||
- **`PromptToolMiddleware`** and **`ResourceToolMiddleware`** (deprecated 3.1) — Breaking. Use the `PromptsAsTools` / `ResourcesAsTools` transforms from `fastmcp.server.transforms` instead. The non-deprecated `ToolInjectionMiddleware` base class is retained.
|
||||
- **`StreamableHttpTransport(sse_read_timeout=...)`** (deprecated no-op) — Breaking. The parameter had no effect under the SDK v2 client; configure timeouts via `read_timeout_seconds` in `session_kwargs` or on the httpx2 client via `httpx_client_factory`. `SSETransport` still accepts `sse_read_timeout`.
|
||||
|
||||
### `FastMCP` server methods and `mount()` kwargs
|
||||
|
||||
The following `FastMCP` methods and parameters, deprecated since 3.0, are removed:
|
||||
|
||||
- `FastMCP.as_proxy(...)` → `create_proxy(...)` (`from fastmcp.server import create_proxy`)
|
||||
- `FastMCP.import_server(sub)` → `mount(sub)`
|
||||
- `mount(prefix=...)` → `mount(namespace=...)`
|
||||
- `mount(as_proxy=...)` — removed; mounts always invoke the child's lifespan and middleware, so the flag was already meaningless. To proxy a server, wrap it with `create_proxy()` before mounting.
|
||||
- `FastMCP.add_tool_transformation(name, config)` → `add_transform(ToolTransform({name: config}))`
|
||||
- `FastMCP.remove_tool_transformation(name)` — removed; it was a no-op that only warned (transforms are immutable once added). Use `server.disable(keys=[...])` to hide tools.
|
||||
- `FastMCP.remove_tool(name)` → `mcp.local_provider.remove_tool(name)`
|
||||
|
||||
The `_REMOVED_KWARGS` constructor shim (which raises helpful `TypeError`s for kwargs removed in 3.0) is retained through 4.0.
|
||||
|
||||
### Tool and component parameters
|
||||
|
||||
- **Tool-level `serializer` parameter** — removed from `@tool` / `mcp.tool()`, `Tool.from_function`, `Tool.from_tool`, `TransformedTool.from_tool`, the OpenAPI `OpenAPITool`, and the `mcp_mixin` tool decorator. Return a `ToolResult` from your tool for full control over serialization instead (see [Custom Serialization](https://gofastmcp.com/servers/tools#custom-serialization)). The server-level `tool_serializer` constructor kwarg was already removed in 3.0.
|
||||
- **Tool `exclude_args` parameter** — removed from the tool decorator and its plumbing (`ParsedFunction.from_function`, `Tool.from_function`, `mcp.tool()`). Use dependency injection with `Depends()` to hide parameters from the tool schema instead.
|
||||
- **`decorator_mode` setting** (`FASTMCP_DECORATOR_MODE`) and its `"object"` mode — removed. Decorators always return the original function with metadata attached; the object-returning machinery is gone. Access component objects through the server (e.g. `await mcp.get_tool("name")`) rather than the decorated function.
|
||||
- **Component-import compatibility shims** — Breaking. `fastmcp.tools.tool`, `fastmcp.resources.resource`, and `fastmcp.prompts.prompt` no longer exist as modules. Two separate mechanisms kept them alive and both are now gone: the `__getattr__` shims that re-exported `FunctionTool` / `ParsedFunction` / `tool`, `FunctionResource` / `resource`, and `FunctionPrompt` / `prompt`; and the `sys.modules` aliases that pointed each old module name at its renamed `base.py`. Import the component types from the package itself — `from fastmcp.tools import Tool, ToolResult` — and the function-backed classes from their canonical modules (`fastmcp.tools.function_tool`, `fastmcp.resources.function_resource`, `fastmcp.prompts.function_prompt`).
|
||||
- **`fastmcp.experimental.sampling`** and **`fastmcp.experimental.sampling.handlers`** (2.x-era re-export shims) — Breaking. These aliased the client-side sampling handlers without warning. Import from `fastmcp.client.sampling.handlers.openai` instead. Note this is unrelated to the SEP-2577 removal of *server-initiated* sampling: a FastMCP client still answers a legacy-era server's sampling requests, so `Client(sampling_handler=...)` and the Anthropic / OpenAI / Google GenAI handlers under `fastmcp.client.sampling.handlers` remain fully supported.
|
||||
- **`fastmcp.server.auth.authorization`** (3.0-era re-export shim) — Breaking. The module was a pass-through sitting between the `fastmcp.server.auth` package and the real implementation in `fastmcp.utilities.authorization`, and FastMCP's own middleware and local-provider decorators imported through it. Everything internal now imports from `fastmcp.utilities.authorization` directly. The documented public path is unchanged: `from fastmcp.server.auth import require_scopes, require_roles, restrict_tag, run_auth_checks, AuthCheck, AuthContext`. Two names the old module also exported — `run_auth_checks_with_shortfall` and `scope_requirements` — are *not* re-exported from `fastmcp.server.auth` and must be imported from `fastmcp.utilities.authorization`. They are middleware plumbing with no documented user-facing use, so they were deliberately not widened onto the auth package's surface; the upgrade guide names the utilities path for them explicitly.
|
||||
- **`SkillsProvider`** (3.0-era rename alias) — Breaking. Use `SkillsDirectoryProvider` from `fastmcp.server.providers.skills`. The alias was also re-exported from `fastmcp.server.providers`; both are gone.
|
||||
- **`ctx.elicit()` without `response_type`** (deprecated 3.2, warned through 3.4.4) — Breaking. The parameter is now required, and passing `None` explicitly raises `TypeError`. The empty-object schema it produced was ambiguous under the MCP spec and left some clients (e.g. VS Code) rendering an empty, non-functional form. Pass a type describing the data you expect back; `bool` covers confirmations. This is the server-authoring API only — the *client* elicitation handler still receives `response_type=None` for URL requests and for empty schemas sent by other servers, which is unchanged.
|
||||
|
||||
*Verify:* deletions of `fastmcp_slim/fastmcp/server/proxy.py`, `fastmcp_slim/fastmcp/server/openapi/`, `fastmcp_slim/fastmcp/experimental/server/openapi/`, `fastmcp_slim/fastmcp/experimental/utilities/openapi/`, `fastmcp_slim/fastmcp/server/apps.py`, `fastmcp_slim/fastmcp/server/app.py`; the removed classes in `fastmcp_slim/fastmcp/server/middleware/tool_injection.py`; the removed parameter in `fastmcp_slim/fastmcp/client/transports/http.py`; `fastmcp_slim/fastmcp/server/server.py`; `fastmcp_slim/fastmcp/tools/base.py`, `tools/function_tool.py`, `tools/tool_transform.py`, `tools/function_parsing.py`; `fastmcp_slim/fastmcp/settings.py`, `resources/function_resource.py`, `prompts/function_prompt.py`, and the local-provider decorators; `resources/base.py`, `prompts/base.py`.
|
||||
140
dev-docs/v4-notes/feature-program.md
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
---
|
||||
title: Feature Program
|
||||
---
|
||||
|
||||
The migration is the foundation. The forward v4 program is a sequence of post-merge PRs that build on it. Several have now merged. Each feature below carries an explicit status:
|
||||
|
||||
- **Shipped** — merged to `main`, with the PR cited.
|
||||
- **Designed** — the approach is settled and an API sketch exists; implementation has not started.
|
||||
- **Planned** — the shape is agreed but design details remain open.
|
||||
- **Not started** — identified as v4 scope, not yet designed.
|
||||
|
||||
Code blocks marked as sketches show the *intended* API and do not resolve against the current tree.
|
||||
|
||||
## Sampling removal
|
||||
|
||||
**Status: Shipped in 4.0.**
|
||||
|
||||
Sampling was the push-shaped API where a server borrows the client's model mid-call (`ctx.sample`, `ctx.sample_step`). The `2026-07-28` era removes server-initiated requests, so it cannot work on modern connections, and `Client`'s flip to `mode="auto"` made a modern connection the default — the era gate had become the default experience rather than an edge case. Background-task sampling was dead under v2 in any event: a worker's back-channel is gone once the submitting request returns, and no relay was ever built (sdk-feedback #9).
|
||||
|
||||
Deprecation and era-gating shipped in #4448. The removal completes the plan: `ctx.sample`, `ctx.sample_step`, `ctx.list_roots`, `server/sampling/` (including `SamplingTool` and structured-result sampling), `FastMCP(sampling_handler=..., sampling_handler_behavior=...)`, and `examples/sampling/` are all gone. The server-authoring API is now the modern protocol's API, with nothing in it that only works against old clients.
|
||||
|
||||
The migration story is honest: there is **no drop-in**. The guidance is architectural — call an LLM from your server directly, with your own API key, rather than borrowing the client's model. For roots, take paths as tool arguments or ask through the guard pattern, whose `input_requests` map still carries a `ListRootsRequest`.
|
||||
|
||||
The client-side provider handlers (Anthropic, OpenAI, Google GenAI) and `Client(sampling_handler=..., roots=...)` are **retained**: a FastMCP client still has to answer a legacy server's requests, and MRTR needs them from the client side. What is removed is the server-side push emitter. `ProxyClient`'s default relay handlers are retained for the same interop reason and now call the SDK session directly.
|
||||
|
||||
## MRTR elicitation
|
||||
|
||||
**Status: Guard form shipped (4.0). Declarative `Resolve` layer designed.**
|
||||
|
||||
Elicitation survives the modern era through multi-round-trip (MRTR). The 2026 wire envelope carries elicitation as a multi-round input-request: a tool returns an `InputRequiredResult` and re-runs per round, each round a complete request→response cycle. Imperative `ctx.elicit` relies on the session back-channel, which is gone on `2026-07-28` foreground calls; on the modern era, elicitation is reachable through MRTR instead.
|
||||
|
||||
The **guard form** of this is shipped in 4.0 (see [Elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)): a tool returns an `InputRequiredResult` and reads the client's answers off `ctx.input_responses` / `ctx.request_state`, re-running each round. It mirrors the SDK's base guard model exactly — no FastMCP-invented DX, the framework owns `request_state` sealing, and returning this result on a handshake-era connection produces a clear era error.
|
||||
|
||||
What remains is the declarative `Resolve(...)` layer that sits *on top of* that shipped primitive. It is designed, not built: a new `fastmcp.elicitation` module — `Resolve`, `Elicit`, and `ElicitationResult` — thin wrappers over the SDK's resolver, wired into FastMCP's own tool layer (FastMCP tools do not inherit the SDK's auto-resolver wiring). It would detect `Annotated[_, Resolve(...)]` parameters, build resolver plans, and return the SDK's `InputRequiredResult` instead of the tool body on the first round.
|
||||
|
||||
Imperative `ctx.elicit` is **not** re-plumbed to survive the modern era. It works on the legacy eras through the session back-channel, and on `2026-07-28` foreground calls it is era-gated to raise a clear error (shipped in #4448) pointing at the guard form. The earlier plan to keep imperative `ctx.elicit` alive on modern connections through a background-task relay is dead twice over: the guard model shipped in its place, and the 2025 task machinery the relay depended on is slated for removal (see [Known Gaps](known-gaps.md#the-xfail-register)).
|
||||
|
||||
The intended declarative DX (sketch — the module does not exist yet):
|
||||
|
||||
```python test="skip"
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from fastmcp import FastMCP, Context
|
||||
from fastmcp.elicitation import Resolve, Elicit, ElicitationResult
|
||||
|
||||
mcp = FastMCP("shipping")
|
||||
|
||||
|
||||
class Address(BaseModel):
|
||||
street: str
|
||||
city: str
|
||||
zip: str
|
||||
|
||||
|
||||
async def ask_address(ctx: Context) -> Elicit[Address]:
|
||||
return Elicit("Where should we ship this order?", Address)
|
||||
|
||||
|
||||
@mcp.tool
|
||||
async def create_shipment(
|
||||
order_id: str,
|
||||
address: Annotated[Address, Resolve(ask_address)], # unwrapped; decline -> ToolError
|
||||
) -> str:
|
||||
return f"Shipping {order_id} to {address.city}"
|
||||
|
||||
|
||||
@mcp.tool
|
||||
async def maybe_ship(
|
||||
order_id: str,
|
||||
address: Annotated[ElicitationResult[Address], Resolve(ask_address)], # full outcome
|
||||
) -> str:
|
||||
if address.action != "accept":
|
||||
return "cancelled"
|
||||
return f"Shipping {order_id} to {address.data.city}"
|
||||
```
|
||||
|
||||
The FastMCP client already dispatches input-requests through its elicitation callback; the remaining declarative work confirms the FastMCP client drives the input-required driver the way the SDK's own client does.
|
||||
|
||||
The divergence between elicitation and sampling on 2026 comes down to one fact: the SDK built the server-side emitter for elicitation (`Elicit`/`Resolve`) and not for sampling. The wire carries all three input-request types and the client dispatches all three; only elicitation can produce one server-side. That is why elicitation survives 4.0 via MRTR and push-sampling does not.
|
||||
|
||||
## Middleware root dispatch
|
||||
|
||||
**Status: Shipped (#4553).**
|
||||
|
||||
The migration already routed `initialize` interception through the SDK's `ServerMiddleware` list via `FastMCPServerMiddleware`. #4553 made that entry the root of middleware dispatch: FastMCP's method-agnostic hooks (`on_message`, `on_request`, `on_notification`) now fire for every inbound message — client cancellations, progress notifications, and requests that fail routing or validation — not only the ones that reach a component handler. The component methods keep running their own chain interior, and a method set plus a dispatch flag keep the two passes disjoint so each hook fires exactly once per message.
|
||||
|
||||
## First-class 2026 client
|
||||
|
||||
**Status: Partly shipped (#4572, #4574); full composition blocked upstream.**
|
||||
|
||||
`fastmcp.Client` now defaults to `mode="auto"` (#4572): it probes `server/discover`, falls back to the classic handshake, and answers multi-round-trip `input_required` requests through its existing handlers. The same PR surfaced `extensions=` and `result_claims=` (SEP-2133). The client also dropped its forked protocol helpers — extension folding, the evicting message handler, discover synthesis — in favor of the SDK's own (#4574).
|
||||
|
||||
The decision here was **compose, not wrap** (D16): rebuild `fastmcp.Client` on the SDK's high-level `mcp.Client` rather than wrapping `mcp.ClientSession`. The parts that compose cleanly have shipped. The rest is **blocked upstream on two counts**. First, `mcp.Client` constructs its `ClientSession` at a single hardcoded site with no injection hook, while FastMCP's `session_class` is load-bearing (`ProxyClient` substitutes a session that skips result validation so a backend's schema violation surfaces at the end client rather than becoming a proxy error) — a `session_factory=` hook on `mcp.Client`, the same shape as the `notification_bindings=` parameter added earlier, would solve this. Second, `mcp.Client.__aenter__` refuses reentry, but FastMCP's client is deliberately reentrant (its refcounted context manager exists to fix a proxy session-reuse deadlock), so the rebuild also needs the SDK client to tolerate reentrant entry. Both must land upstream before the full rebuild is possible; `session_factory=` alone is necessary but not sufficient.
|
||||
|
||||
This workstream also owns the server-side statelessness design holes — `ctx.session_id` / `set_state` round-tripping and stateful-proxy affinity — since they turn on the same "what is a session without a session?" question. See [Statelessness on 2026-07-28](known-gaps.md#statelessness-on-2026-07-28) for the full accounting.
|
||||
|
||||
## Subscriptions, cache hints, extensions, OTel
|
||||
|
||||
**Status: Mixed — cache hints and OTel shipped; subscriptions not started.**
|
||||
|
||||
A cluster of protocol features tracked for v4. Their statuses have diverged:
|
||||
|
||||
- **Cache hints — shipped (#4464).** Server-level authoring (`FastMCP(cache_ttl=..., cache_scope=...)`, SEP-2549) stamps every cacheable result, and the FastMCP client honors hints with an opt-in response cache.
|
||||
- **OpenTelemetry — shipped (#4481).** Spans are on by default (a no-op without an exporter), with SDK-aligned attributes and a `FASTMCP_TELEMETRY_MODE` setting (`native` / `propagation_only` / `off`).
|
||||
- **Extensions — client side shipped (#4572).** `Client(extensions=..., result_claims=...)` advertises opt-in client extensions (SEP-2133). The server side is a Designed workstream in its own right (see [FastMCP-native extension API](#fastmcp-native-extension-api)). The cross-era reconciliation of the `extensions` / MCP Apps capability advertisement is still open (the capability is stripped at pre-2026 negotiated versions — sdk-feedback #2).
|
||||
- **Subscriptions — not started.** A `subscriptions/listen` surface backed by a subscription bus.
|
||||
|
||||
## FastMCP-native extension API
|
||||
|
||||
**Status: Shipped (#4602).**
|
||||
|
||||
MCP extensions (SEP-2133) are optional, capability-negotiated protocol features identified by a reverse-DNS string — `io.modelcontextprotocol/ui` (MCP Apps), `io.modelcontextprotocol/tasks` (SEP-2663). They are a genuinely new abstraction in SDK v2; they did not exist in v1. The SDK exposes them through an `Extension` server class that contributes a capability, additive request methods, and a `tools/call` interceptor, plus a symmetric `ClientExtension` with result claims and notification bindings.
|
||||
|
||||
FastMCP already forwards `ClientExtension` natively (`Client(extensions=...)`, #4572). The **server** side does not use the SDK's `Extension` class at all: MCP Apps predates the abstraction, so FastMCP hand-splices the `ui` capability into `get_capabilities()` on the low-level server and walks tool metadata directly. That worked for one extension, but every new protocol extension currently means bespoke surgery on core.
|
||||
|
||||
The Designed work is a FastMCP-native server extension API — a single registration point (`mcp.add_extension(...)`) that contributes a negotiated capability, request methods, and a `tools/call` interceptor, with access to FastMCP-level constructs the SDK's `Extension` withholds (the component registry, `Context`, auth scope). It is designed against the SEP-2663 tasks extension because tasks exercises the full surface — capability *and* methods *and* interception *and* client claims/notifications — where MCP Apps exercises only a subset. Tasks is the pathfinder; MCP Apps migrates onto the extension API as a fast-follow, deleting the hand-rolled splices, and confirms the design generalizes. The discriminator that keeps the extension API distinct from [middleware](https://gofastmcp.com/servers/middleware): an extension is a *negotiated contract change* the client must understand, where middleware is unilateral server behavior the client never sees. Delete a capability advertisement and nothing about the client changes — that is middleware, not an extension.
|
||||
|
||||
## Background tasks (SEP-2663)
|
||||
|
||||
**Status: Shipped (#4603).**
|
||||
|
||||
Background tasks return to the modern era as `fastmcp-tasks`, an in-repo optional package rebuilt on the `io.modelcontextprotocol/tasks` extension (SEP-2663, Final, merged upstream 2026-05-15). SEP-2663 supersedes SEP-1686 but keeps its polling core: a client that advertises the tasks capability issues an augmented `tools/call`; the server decides whether to run it as a task and returns a `CreateTaskResult` carrying a server-generated task id; the client polls `tasks/get` until terminal and reads the result inlined there. FastMCP's existing SEP-1686 wire layer is removed while the Docket/Redis execution engine underneath moves into `fastmcp-tasks` intact — the spec moved toward what FastMCP already built, so the rebuild is mostly deletion plus a thin wire adapter. `task=True` stays the authoring surface (gated by the `fastmcp[tasks]` extra and an explicit `mcp.add_extension(TasksExtension(...))`, the first consumer of the [extension API](#fastmcp-native-extension-api) above), so a server that already uses tasks needs no code change. Scope for v1 is polling-only and `tools/call`-only.
|
||||
|
||||
The full design — wire delta, the engine/wire split, packaging, client experience, sequencing, risks, and the five resolved decisions — is on the dedicated [Background Tasks (SEP-2663)](background-tasks.md) page.
|
||||
|
||||
## SDK delegation, round two
|
||||
|
||||
**Status: Planned (gated on upstream).**
|
||||
|
||||
The real HTTP simplification is a v4 project, not this PR. FastMCP can collapse its `create_streamable_http_app` onto the SDK's `Server.streamable_http_app()` once upstream adds three things:
|
||||
|
||||
1. per-session event-store scoping,
|
||||
2. a user-middleware injection hook,
|
||||
3. a lifespan hook.
|
||||
|
||||
The payoff is not only less code — FastMCP would also inherit the SDK's session-owner credential enforcement, a security gain it lacks today. These are the three upstream feature requests to file (alongside the advisory dossier described in [Known Gaps](known-gaps.md)). Until they land, the four HTTP overrides in the [Change Register](change-register.md#http) stay.
|
||||
|
||||
One latent capability worth surfacing on FastMCP's side: `session_idle_timeout` is accepted by the manager but never set by `create_streamable_http_app` — a one-line plumb if FastMCP wants to expose it.
|
||||
49
dev-docs/v4-notes/index.md
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
---
|
||||
title: v4.0 Development Notes
|
||||
---
|
||||
|
||||
This directory is the working map of FastMCP v4.0: the complete register of user-facing changes from the MCP Python SDK v2 migration ([PR #4437](https://github.com/PrefectHQ/fastmcp/pull/4437)), plus the forward v4 feature program. It plays three roles at once.
|
||||
|
||||
1. **A change register.** Every user-visible change from the migration, organized by subsystem, with a note on how FastMCP handles it (absorbed, bridged, breaking, or deprecated) and where to find it in the diff. This is the [Change Register](change-register.md).
|
||||
2. **A feature program.** The forward v4 work — sampling removal, multi-round-trip elicitation, the first-class 2026 client, a FastMCP-native extension API, the SEP-2663 background-tasks rebuild, and the SDK-delegation round-two convergence — now a mix of shipped, designed, and pending. Multi-round-trip guard tools (#4544), the client's `mode="auto"` default with a partial SDK-composition (#4572/#4574, full composition blocked upstream), the extension API (#4602), and background tasks on SEP-2663 (#4603) have shipped; sampling removal and SDK delegation remain ahead. Each carries an explicit status in the [Feature Program](feature-program.md). The shipped side — what a v4 deployment provides on the modern protocol today, including the complete server-side SEP-990 identity assertion implementation — is cataloged in [2026-07-28 Protocol Support](protocol-2026.md).
|
||||
3. **A review lens.** Because the migration PR is too large to review line by line, the change register is organized so a reviewer can take one subsystem, read its claimed changes, and verify each against the diff. The [Known Gaps](known-gaps.md) page collects the deliberate xfails and the upstream dependencies that gate the follow-up work.
|
||||
|
||||
## Why v4 exists
|
||||
|
||||
FastMCP v4.0 is an engine swap. Three forces drive the major version:
|
||||
|
||||
**The MCP Python SDK v2 rebuild.** The SDK v2 makes two sweeping changes to the protocol layer: it splits the protocol types out of `mcp.types` into a standalone `mcp_types` package, and it renames every protocol field from camelCase to snake_case (`inputSchema` → `input_schema`, `mimeType` → `mime_type`, `isError` → `is_error`). It also rewrites the server request-handling model — handlers are now registered by method string and return bare result models, there is no `request_ctx` ContextVar, and server-side middleware is a first-class SDK concept. FastMCP absorbs almost all of this so that a typical server needs zero code changes.
|
||||
|
||||
**Protocol version 2026-07-28.** The SDK v2 serves multiple protocol eras from one server. Alongside the session-based handshake eras, it introduces the sessionless `2026-07-28` era, which discovers capabilities through `server/discover` and removes server-initiated requests (SEP-2577). This formally supersedes FastMCP's earlier "latest protocol only" stance: a single server now works with clients across the protocol transition.
|
||||
|
||||
**Sampling and roots removed from the server API.** The `2026-07-28` era removes the server's ability to push a request back to the client mid-call, which takes `ctx.sample`, `ctx.sample_step`, and `ctx.list_roots` off the table. Rather than leave them half-working against old clients only, 4.0 removes them from the server API entirely — a real architectural shift for servers that borrowed the client's model, and one that justifies the major bump. Client-side handlers stay, because a modern client still has to answer a legacy server.
|
||||
|
||||
## Release strategy
|
||||
|
||||
The migration merges to `main` and development continues there with subsequent PRs. Releases follow the SDK's own beta timeline:
|
||||
|
||||
- **`main` carries the beta pins.** While the SDK is on `mcp==2.0.0b1` / `mcp-types==2.0.0b1`, `main` cuts **pre-releases** (`4.0.0b1`, `4.0.0b2`, …). No stable PyPI release goes out until `mcp 2.0.0` reaches GA — at which point the pins swap to the stable SDK and `4.0.0` ships. The pin-swap is a tracked checklist item on the [Known Gaps](known-gaps.md) page.
|
||||
- **`release/3.x` is the maintenance line.** A `release/3.x` branch is cut from pre-merge `main`. It stays on the SDK v1 line, receives upstream security patches, and serves users who cannot move to the SDK v2 beta yet.
|
||||
|
||||
### Release codenames
|
||||
|
||||
Following the pun-title convention (`v<version>: <pun>`), the v4 line runs a single "four" motif across the whole cycle, holding the headline name for the stable release the way v3 did ("Three at Last" for `3.0.0`, stage puns for its betas):
|
||||
|
||||
| Release | Codename | The nod |
|
||||
| --- | --- | --- |
|
||||
| `4.0.0a1` (alpha) | **Fourst Contact** | _first contact_ — the first, cautious look at the new engine |
|
||||
| `4.0.0a2` (alpha) | **Back and Fourth** | _back and forth_ — the second pass, where background tasks and stateless state land |
|
||||
| `4.0.0b1` (beta) | **Fourgone Conclusion** | _foregone conclusion_ — once the MCP SDK went v2, v4 was inevitable |
|
||||
| `4.0.0b2` (beta) | **Fourmidable** | _formidable_ — held in reserve for a second beta if one is needed |
|
||||
| `4.0.0` (stable) | **Fast Fourward** | _fast forward_ — full speed onto the new foundation |
|
||||
|
||||
## How to read the register
|
||||
|
||||
Each subsystem section in the [Change Register](change-register.md) tags its changes with one of four dispositions:
|
||||
|
||||
- **Absorbed** — the SDK changed underneath, but FastMCP's public surface is identical. Nothing for users to do.
|
||||
- **Bridged** — a compatibility shim keeps old code working, usually with a `FastMCPDeprecationWarning`. Users should migrate but are not forced to.
|
||||
- **Breaking** — user code must change. These are the headline migration items.
|
||||
- **Deprecated** — still works, warns now, slated for removal in a later release.
|
||||
|
||||
The user-facing summary of the migration lives in the published [Upgrading from FastMCP 3](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-3) guide. These development notes are the exhaustive version behind it.
|
||||
85
dev-docs/v4-notes/known-gaps.md
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
---
|
||||
title: Known Gaps and Upstream Dependencies
|
||||
---
|
||||
|
||||
The migration ships with a set of deliberate gaps: temporary shims, xfailed tests, and pins that depend on the MCP Python SDK v2 reaching GA. Each is tracked here with its removal trigger. This page is the checklist for the beta-to-stable transition and the advisory relationship with the SDK team.
|
||||
|
||||
## The xfail register
|
||||
|
||||
Roughly forty `xfail` markers across the test tree name the SDK gaps and removed protocol surfaces they wait on. Re-running the suite against a new SDK beta surfaces which have closed (a strict xfail that starts passing fails the suite, prompting removal of the marker). They cluster in three areas — but the largest cluster is no longer a set of gaps to close.
|
||||
|
||||
**Task suite (`tests/server/tasks/`, `tests/client/tasks/`) — SEP-1686 wire layer being removed; engine rebuilt on SEP-2663.** The large majority. These cover the 2025 task protocol (SEP-1686), which left the core MCP spec and was reworked into the `io.modelcontextprotocol/tasks` extension (SEP-2663). FastMCP's SEP-1686 *wire* machinery (capability advertisement, the `tasks/get|result|list|cancel` handlers, the push notification/elicitation relay) is slated for removal, so the wire-protocol xfails disappear with the code they cover — they are not waiting on an SDK fix. The Docket/Redis *execution engine* underneath is not discarded: it is extracted into the planned `fastmcp-tasks` package and re-adapted to the SEP-2663 polling shape (see [Background Tasks (SEP-2663)](background-tasks.md)). The two SDK gaps these were originally filed against — **sdk-feedback #1** (SEP-1686 task result types omitted from the method registries) and **sdk-feedback #3** (no `task` field on `ReadResourceRequestParams` / `GetPromptRequestParams`) — are moot: they patched the SEP-1686 wire shape, which SEP-2663 replaces with a `CreateTaskResult` claimed on `tools/call`. The gap that matters for the rebuild is **sdk-feedback #2** (extensions capability stripped at pre-2026 negotiated versions) — it now gates a flagship feature and is escalated accordingly.
|
||||
|
||||
**Protocol eras (`tests/server/test_protocol_eras.py`).** One remaining strict xfail, and it too is task-related: the v2 SDK high-level client exposes no `task=` parameter on `call_tool`, so a SEP-1686 task-augmented `tools/call` cannot be submitted through it. It resolves with the SEP-1686 wire-layer removal above; the SEP-2663 rebuild submits tasks by advertising the extension capability and claiming a `CreateTaskResult`, not through a `task=` params field. The earlier strict xfail for the `ctx.elicit` / `ctx.sample` "Method not found" degradation (sdk-feedback #10) is **gone** — the era-gating shipped in #4448 flipped it to a passing test.
|
||||
|
||||
**MCP Apps (`tests/test_apps.py`).** Two xfails tied to **sdk-feedback #2** — the `extensions` capability is stripped by the pre-2026 version sieve, so the UI extension can't be advertised to legacy-era clients.
|
||||
|
||||
## Shims and their removal triggers
|
||||
|
||||
Every shim in the migration is temporary and carries a documented removal trigger.
|
||||
|
||||
| Shim | Location | Removal trigger |
|
||||
| --- | --- | --- |
|
||||
| `_sdk_patches.py` — task registry widening | `fastmcp_slim/fastmcp/_sdk_patches.py` | Removed with FastMCP's SEP-1686 wire machinery (`server/tasks/`), which is slated for removal now that the 2025 task protocol left the spec. The SEP-2663 rebuild does not need it — `CreateTaskResult` is claimed on `tools/call` through the extensions mechanism, which the SDK registries already admit. |
|
||||
| `_compat.py` — camelCase field bridge | `fastmcp_slim/fastmcp/_compat.py` | User-migration aid; removed in a future release after users migrate reads to snake_case. Users can preview removal with `mcp_camelcase_compat = False`. |
|
||||
| `FastMCPRequestContext` ContextVar | `fastmcp_slim/fastmcp/server/dependencies.py` | The SDK deliberately passes context as an argument with no ContextVar; FastMCP's public `get_context()` needs ambient access, and the shim also lifts `_meta`, which the SDK's `TypedDict` drops. No planned removal — this is a permanent boundary, not a beta gap. |
|
||||
| `FastMCPServerMiddleware` | `fastmcp_slim/fastmcp/server/low_level.py` | Already the native SDK `ServerMiddleware` path; no cleaner hook exists. Permanent. |
|
||||
| Client `get_session_id` header sniff | `fastmcp_slim/fastmcp/client/transports/http.py` | SDK exposes session id (or an `on_session_created` callback) from `streamable_http_client`, at parity with `sse_client` (sdk-feedback #5). |
|
||||
| `_sdk_context_shim.py` — generic handler aliases | `fastmcp_slim/fastmcp/client/_sdk_context_shim.py` | The SDK's `ClientRequestContext` is not subscriptable, so FastMCP keeps the public generic `SamplingHandler`/`RootsHandler`/`ElicitationHandler` aliases. Permanent unless the SDK makes the context subscriptable (sdk-feedback #7). |
|
||||
|
||||
The `TaskNotificationHandler` binding (sdk-feedback #8) is the client-side equivalent: it registers a `NotificationBinding` for the SEP-1686 `notifications/tasks/status` because the SDK no longer tees custom server notifications to the message handler. It goes away with the SEP-1686 wire machinery it serves; the `fastmcp-tasks` client half registers its own binding for the SEP-2663 `notifications/tasks` shape when it ships (push notifications are deferred to a later `fastmcp-tasks` version — v1 is polling-only).
|
||||
|
||||
## Statelessness on 2026-07-28
|
||||
|
||||
The `2026-07-28` era is stateless by protocol construction, and the recurring maintainer question is whether that statelessness has to be woven through FastMCP everywhere. It does not — but the honest accounting has three parts: features that are legacy-only because the protocol removed the mechanism, features that already work because they never relied on a session, and a short list of design holes where the current code *doesn't error* but also *doesn't work*. Everything below concerns `2026-07-28` connections only. Every client in the field today negotiates a handshake era, where all of this behaves exactly as it always has.
|
||||
|
||||
**The SDK ground truth.** On the modern paths the SDK's `Connection` is strictly per-request: a fresh `Connection` is built from each POST's envelope, its `exit_stack` unwinds when the request returns, `connection.session_id` is always `None`, and `connection.state` is a fresh dict per request. The manager's `stateless` flag never enters the picture — modern routing short-circuits ahead of it. There is no standing server→client stream: notifications emitted *during* a request ride that POST's own SSE sink, and anything emitted after the POST returns is dropped (`_NO_CHANNEL`); server→client *requests* raise `NoBackChannelError`. The only replacement is `subscriptions/listen`, which carries four list-changed / resource-updated event kinds and nothing else — no logging, progress, or task-status events, no resumability, and it is not yet wired into FastMCP. There is no `EventStore` or `Last-Event-ID` on modern paths at all; both belong to the legacy transport.
|
||||
|
||||
### Legacy-only by construction — document, don't build
|
||||
|
||||
These are not bugs. The protocol removed the mechanism they depend on, so they are simply out of scope on `2026-07-28`:
|
||||
|
||||
- **Per-session log levels.** `logging/setLevel` is absent from the 2026 method registry, so the `_client_log_levels` handler is unreachable. There is no per-session log-level state because there is no session.
|
||||
- **`EventStore` / resumability.** `EventStore`, `SessionScopedEventStore`, and Last-Event-ID resumption are never constructed on the modern paths. Resumability presupposes a durable stream, which the era does not have.
|
||||
- **Ping keepalive.** Server-initiated ping is a server→client request and is therefore structurally a no-op on modern connections; the SDK owns SSE-level pings on this transport.
|
||||
|
||||
### Already stateless by construction — works on 2026
|
||||
|
||||
These work on `2026-07-28` today because they never leaned on a protocol session:
|
||||
|
||||
- **`tasks/get` polling.** Task result retrieval is keyed by `task_id` and backed by Docket/Redis, so a client polls across independent requests without any session affinity. This session-free polling is exactly why the execution engine survives the SEP-1686-to-SEP-2663 rework: the SEP-2663 wire shape (poll `tasks/get`, resolve in-task input via `tasks/update`) maps onto the same durable store, and SEP-2663's `Mcp-Name: <taskId>` routing header is moot for a shared-Redis deployment where any replica can serve the poll. See [the xfail register](#the-xfail-register).
|
||||
- **OAuth bearer validation.** Auth is per-request bearer validation — every POST carries and re-validates its own credential.
|
||||
- **In-request progress and logging notifications.** Notifications emitted while a request is still streaming ride that POST's SSE sink and are delivered normally.
|
||||
|
||||
### Design holes deferred to the multi-protocol workstream
|
||||
|
||||
The remaining items are real holes, deferred to the [first-class 2026 client](feature-program.md#first-class-2026-client) workstream because they all reduce to one unanswered question — *what is a session when the protocol has none?* The danger in each is that the code currently returns without erroring, which reads as "works" but is actually silent degradation. Again: these affect `2026-07-28` connections only; on the handshake eras every one of them behaves correctly.
|
||||
|
||||
- **`ctx.session_id` and `ctx.set_state` / `ctx.get_state` (broken even single-replica).** On a modern request `ctx.session_id` mints a fresh `uuid4`, cached on the per-request `connection.state` that is discarded when the request returns. So `ctx.set_state` and `ctx.get_state` silently never round-trip across requests — no error, just lost data. The open design decision is whether `session_id` should become `None` with `set_state` documented as session-era-only, or be re-based on an app-level key (the auth subject, or a client-supplied header).
|
||||
- **Task push and in-task input — resolved by the SEP-2663 design, not a statelessness hole.** This was previously framed as a hole because SEP-1686 leaned on a push back-channel (the notification/elicitation relay) that dies once the submitting request returns. SEP-2663 removes the dependency: in-task input is *poll-based* — the task enters `input_required`, surfaces its outstanding elicit/sample/roots requests in an `inputRequests` map on `tasks/get`, and the client answers via `tasks/update`. That round-trips through the durable store with no session affinity, so it is stateless-safe by construction. The SEP-1686 push relay (`server/tasks/elicitation.py`, `notifications.py`) is removed; the `fastmcp-tasks` rebuild implements the poll-based channel instead. Foreground (non-task) elicitation on 2026 remains the guard-mode `InputRequiredResult`.
|
||||
- **Stateful proxy affinity (degraded).** The stateful proxy's `_caches` are keyed by the per-request `Connection`, so on modern connections the proxy collapses to stateless proxying: results stay correct, but the per-session affinity guarantee is lost. This is decided alongside the `session_id` question — same root — or gated to the legacy/stdio transports.
|
||||
|
||||
Multi-replica concerns (per-process rate-limiter buckets, shared Redis backends for state and tasks, a Redis `SubscriptionBus`) are deployment configuration rather than protocol gaps and are out of scope for this section.
|
||||
|
||||
## Upstream advisory dossier
|
||||
|
||||
FastMCP acts as an advisor to the SDK team. The migration produced a dossier of ten findings (`sdk-feedback.md`) — verified bugs and hard edges to report upstream, plus questions to bundle into a feedback thread. The highest-priority items:
|
||||
|
||||
- **#1 (bug)** — SEP-1686 task result types ship but the method registries omit them. *Moot: the SEP-1686 wire shape was removed from the spec; the SEP-2663 rebuild claims `CreateTaskResult` on `tools/call` through the extensions mechanism, which the registries already admit.*
|
||||
- **#2 (bug/question)** — `capabilities.extensions` stripped at pre-2026 negotiated versions. **Elevated:** this now gates the `io.modelcontextprotocol/tasks` extension (and MCP Apps) on the modern era, so it blocks a flagship v4 feature rather than an edge case. Worth prioritizing in the upstream thread.
|
||||
- **#4 (security)** — DCR redirect-URI validation accepts `javascript:`/`data:` schemes.
|
||||
- **#5 (hard edge)** — `streamable_http_client` drops session-id access with no replacement.
|
||||
- **#8 (hard edge)** — custom server notifications are dropped, not tee'd to `message_handler`.
|
||||
- **#10 (hard edge)** — 2026 push-feature degradation error quality is inconsistent. *Resolved on the FastMCP side: `ctx.elicit` / `ctx.sample` are era-gated to raise a clear error on modern connections (#4448).*
|
||||
|
||||
Filing is gated on maintainer approval of each issue text.
|
||||
|
||||
Separately, the [SDK delegation round two](feature-program.md#sdk-delegation-round-two) work depends on **three upstream feature requests** — per-session event-store scoping, a user-middleware injection hook, and a lifespan hook — that would let FastMCP collapse its HTTP builders onto the SDK's and inherit the SDK's session-owner credential enforcement.
|
||||
|
||||
## GA transition checklist
|
||||
|
||||
The beta-to-stable transition is a small set of tracked steps:
|
||||
|
||||
- **Swap the pins.** When `mcp 2.0.0` reaches GA, change `mcp-types==2.0.0b1` (core) and the `mcp` pin (the `[mcp]` extra) in `fastmcp_slim/pyproject.toml` from the beta to the stable release, and cut `4.0.0` instead of another pre-release.
|
||||
- **Re-run the xfail suite against the GA SDK.** Any strict xfail that starts passing means a gap closed — remove the marker and, where applicable, the corresponding shim.
|
||||
- **Confirm `release/3.x`** is cut from pre-merge `main` and receiving upstream security patches for users who stay on the SDK v1 line.
|
||||
53
dev-docs/v4-notes/protocol-2026.md
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
---
|
||||
title: 2026-07-28 Protocol Support
|
||||
---
|
||||
|
||||
FastMCP v4 serves the sessionless `2026-07-28` protocol era and the session-based handshake eras from a single server, with per-connection auto-detection. This page catalogs what FastMCP provides for the modern era — both the protocol machinery it inherits from the MCP Python SDK and the capabilities FastMCP implements itself on top of that layer. It is the reference for what a v4 deployment can actually do on the modern protocol today.
|
||||
|
||||
## Identity assertion (SEP-990)
|
||||
|
||||
SEP-990 defines enterprise "on-behalf-of" access: a corporate identity provider (Okta, Microsoft Entra, etc.) issues a signed *ID-JAG* asserting an employee's identity, the employee's agent presents it at the MCP authorization server's token endpoint via the RFC 7523 `jwt-bearer` grant, and receives a short-lived access token — no browser login, no per-user consent screen, and revocation lives at the IdP.
|
||||
|
||||
The protocol layer for this flow — grant parsing, the `exchange_identity_assertion` provider hook, and metadata advertisement — comes from the SDK. The validation and issuance logic that makes the flow actually work is FastMCP's implementation, and enabling it is one parameter on the existing auth providers:
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.server.auth import OAuthProxy, IdentityAssertion
|
||||
|
||||
auth = OAuthProxy(
|
||||
..., # existing upstream configuration unchanged
|
||||
identity_assertion=IdentityAssertion(
|
||||
trusted_issuers=["https://login.acme-corp.com"],
|
||||
),
|
||||
)
|
||||
mcp = FastMCP("Internal API", auth=auth)
|
||||
```
|
||||
|
||||
Behind that one parameter, FastMCP performs the full SEP-990 §5.1 / RFC 7523 §3 processing: JWKS-based signature verification with automatic OIDC discovery of issuer keys, `typ`/`iss`/`aud`/`sub` validation, temporal checks (`exp`, `iat`, `nbf`, maximum assertion lifetime), enforcement of the assertion's signed `client_id` and `resource` bindings, `jti` replay rejection, scope derivation from the signed assertion (client requests can narrow but never widen), short-lived token issuance with no refresh token, and revocation tracking for the issued tokens. The asserted subject flows into the normal FastMCP auth context, so tools read it through `get_access_token()` like any other identity. See [Identity Assertion](https://gofastmcp.com/servers/auth/oauth-proxy#identity-assertion-sep-990) for the full documentation.
|
||||
|
||||
This slots into FastMCP's existing authorization-server stack — the OAuth proxy's dynamic client registration, the consent flow, and self-issued JWTs — which is what makes a one-parameter enterprise deployment possible.
|
||||
|
||||
## Modern-era capability inventory
|
||||
|
||||
The complete picture of what a FastMCP v4 server and client provide on the `2026-07-28` era:
|
||||
|
||||
| Capability | What FastMCP provides |
|
||||
| --- | --- |
|
||||
| **Dual-era serving** | One server answers both `server/discover` (modern, sessionless) and `initialize` (handshake) connections, auto-detected per connection. Any replica behind a plain load balancer can answer a modern request. |
|
||||
| **Identity assertion (SEP-990)** | Complete server-side implementation, one parameter to enable (above). |
|
||||
| **Authorization server** | Full AS stack: `OAuthProxy` bridges DCR-expecting MCP clients to non-DCR enterprise IdPs, ~18 built-in providers, consent UI, self-issued JWTs, protected-resource metadata (RFC 9728). |
|
||||
| **Cache hints (SEP-2549)** | Server-level authoring (`FastMCP(cache_ttl=..., cache_scope=...)`) stamps every cacheable result; the FastMCP client honors hints with an opt-in response cache. |
|
||||
| **Distributed response caching** | `KeyValueResponseCacheStore` backs the client cache with any key-value store (Redis, memory, filetree), so a fleet of clients or proxy replicas shares cache fills across processes. |
|
||||
| **Resource path security** | Templated resource parameters are screened for traversal, absolute paths, and null bytes before handlers run — on by default, including provider-sourced and mounted templates. |
|
||||
| **Client protocol negotiation** | `Client(mode="auto")` — the default as of v4 — probes `server/discover` and falls back to the classic handshake; the client answers multi-round-trip `input_required` requests through its existing handlers. Pin `mode="legacy"` to force the handshake. |
|
||||
| **Elicitation on the modern protocol (SEP-2322)** | Tools request user input via multi-round trips: a tool returns an `InputRequiredResult` and re-runs per round, reading the client's answers off `ctx.input_responses` / `ctx.request_state` (the [guard pattern](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)). Each round is a complete request→response cycle; the framework seals `request_state` on the wire and unseals it before the tool runs, and a shared-key `request_state_security` policy carries state across replicas. On handshake-era connections returning this result produces a clear era error. |
|
||||
| **Spec-standard errors (SEP-2164)** | Missing-resource reads return `-32602`; push-feature calls on modern connections fail with clear era-specific errors rather than generic method-not-found. |
|
||||
| **Middleware** | Typed per-method hooks (`on_call_tool`, `on_list_tools`, …) and a suite of built-ins (auth, rate limiting, caching, error handling, logging, timing, and more). |
|
||||
| **Composition** | `mount()`, providers, proxying, and tool transforms compose servers dynamically at runtime, with lifespans and middleware driven through the SDK session manager. |
|
||||
| **Pagination** | Declarative `FastMCP(list_page_size=...)` paginates all list operations in the high-level server; the client auto-paginates with cycle detection. |
|
||||
| **Telemetry** | OpenTelemetry spans on by default (no-op without an exporter), SDK-aligned attributes (`mcp.method.name`, `mcp.protocol.version`, `gen_ai.*`), plus auth and provider-delegation spans; `FASTMCP_TELEMETRY_MODE` selects `native`, `propagation_only` (interop with an outer MCP instrumentation layer), or `off`. |
|
||||
| **Background tasks (SEP-2663)** | `fastmcp-tasks` implements the `io.modelcontextprotocol/tasks` extension end to end: `mcp.add_extension(TasksExtension())` plus `task=True` runs a tool as a background task, driven by the same Docket engine FastMCP 3 used. A client transparently completes a tasked call; gathering input mid-task uses the same guard pattern as foreground multi-round-trip tools, so a tool is written once and works either way. Modern-protocol only — the `task=True` runtime this replaced (SEP-1686) is gone entirely, not bridged. See [Background Tasks (SEP-2663)](background-tasks.md) for the design and [servers/tasks](https://gofastmcp.com/servers/tasks) for usage. |
|
||||
|
||||
## Still in the program
|
||||
|
||||
Elicitation on the modern protocol is now shipped in its **guard form** — a tool returns an `InputRequiredResult` and re-runs per round to gather user input via multi-round trips (see [Elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)). The declarative `Resolve(...)` layer over that primitive remains staged, tracked in the [Feature Program](feature-program.md), along with the unified `subscriptions/listen` stream. The [Known Gaps](known-gaps.md) page tracks the upstream dependencies that gate them.
|
||||
217
dev-docs/v4-notes/stateless-session-state.md
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
# Stateless session state (2026-07-28)
|
||||
|
||||
> Design spec. Status: building.
|
||||
|
||||
## Problem
|
||||
|
||||
The `2026-07-28` era is stateless by protocol construction: each request builds a
|
||||
fresh `Connection`, `connection.session_id` is always `None`, and
|
||||
`connection.state` is a new dict discarded when the request returns. So
|
||||
`ctx.session_id` mints a throwaway `uuid4` per request and `ctx.set_state` /
|
||||
`ctx.get_state` **silently never round-trip** — no error, just lost data. A user
|
||||
who wants cross-call state (a cart, a conversation, accumulated context) has no
|
||||
safe mechanism, and the failure is invisible.
|
||||
|
||||
The one identifier every modern request carries that is stable and
|
||||
**non-spoofable** is the authenticated principal — `get_access_token().claims["sub"]`,
|
||||
or the `(client_id, issuer, subject)` triple. Everything else on the wire is
|
||||
client-declared and forgeable.
|
||||
|
||||
## The model
|
||||
|
||||
State lives **server-side** in the one `AsyncKeyValue` (py-key-value) store the
|
||||
server already holds (`session_state_store`). The framework calls `get`/`put`/
|
||||
`delete` and **never imposes a TTL** — retention is entirely the store's
|
||||
(configure it on the store you pass: a Redis TTL, a py-key-value TTL wrapper,
|
||||
whatever). There is no second store and no framework-owned TTL knob.
|
||||
|
||||
Isolation comes from the **authenticated principal, not from the session id.**
|
||||
State is keyed by `(principal, session_id)`. A request under principal B keys
|
||||
into B's own namespace — it can never address A's keys no matter what
|
||||
`session_id` it passes. The id only organizes sessions *within* a principal. The
|
||||
handle is a bare `uuid4` string; it is **not sealed** — the principal prefix is
|
||||
the wall. Sessions are also create-then-validate (below): an id that was never
|
||||
minted by `create_session` under this principal is rejected outright, not
|
||||
resolved to an empty session.
|
||||
|
||||
## Two explicit patterns
|
||||
|
||||
A tool opts into exactly one, on purpose. There is deliberately **no** optional
|
||||
"id if given, else default" parameter — that would silently misroute a call
|
||||
whose id the agent forgot to pass into the shared per-user bucket, which is the
|
||||
invisible-degradation failure this whole feature exists to remove.
|
||||
|
||||
### Per-user state — injected
|
||||
|
||||
```python
|
||||
from fastmcp.server.sessions import UserSession
|
||||
|
||||
@mcp.tool
|
||||
async def remember(fact: str, session: UserSession) -> str:
|
||||
await session.set("fact", fact)
|
||||
return "noted"
|
||||
```
|
||||
|
||||
`session: UserSession` is **dependency-injected** (like `ctx: Context`): keyed by
|
||||
the request's authenticated principal, not present in the input schema, nothing
|
||||
for the agent to pass. Requires auth — with no principal it raises a clear error.
|
||||
Use it when one bucket per user is what you want. `UserSession` is only the
|
||||
injection annotation — the value the handler receives is an ordinary `Session`,
|
||||
so its `get`/`set`/`delete`/`clear` accessors work as usual.
|
||||
|
||||
### Distinct sessions — an argument
|
||||
|
||||
```python
|
||||
from fastmcp.server.sessions import SessionId
|
||||
from fastmcp.server.dependencies import get_session
|
||||
|
||||
@mcp.tool
|
||||
async def add_to_cart(item: str, session_id: SessionId) -> str:
|
||||
session = await get_session(session_id)
|
||||
cart = await session.get("cart", default=[])
|
||||
cart.append(item)
|
||||
await session.set("cart", cart)
|
||||
return f"{len(cart)} items"
|
||||
```
|
||||
|
||||
`session_id: SessionId` is a **required string argument** — it *is* in the schema,
|
||||
the agent supplies it. `SessionId` is a marker type so the framework
|
||||
auto-populates the argument's description with the protocol:
|
||||
|
||||
> "Session identifier. Use a tool to create a session, then pass the resulting id
|
||||
> here to persist state across calls in the same session."
|
||||
|
||||
The tool becomes self-teaching — an agent reads the schema and learns the
|
||||
create-then-pass contract with no hand-prompting. The description names no
|
||||
specific tool: composition can rename the lifecycle tool (mounting under a
|
||||
namespace exposes it as `child_create_session`), so it points at the
|
||||
*capability* rather than a name that may not exist under that mount.
|
||||
|
||||
The standalone `await get_session(session_id)` resolves the id to a `Session`
|
||||
keyed by `(principal, session_id)`, **validating** that it was created under this
|
||||
principal — an unknown or foreign id raises `InvalidSession` rather than opening a
|
||||
fresh bucket. It is a plain function, not a `Context` method, so it needs no
|
||||
foreground context and works from a `task=True` tool's worker. Use this pattern
|
||||
when a user needs more than one session.
|
||||
|
||||
## The `Session` object
|
||||
|
||||
Async accessors over the server store, scoped to one `(principal, session_id)`:
|
||||
|
||||
- `session.id` — the session's id (set for a `session_id`-resolved session; `None`
|
||||
for an injected `UserSession`, which has no distinct id).
|
||||
- `await session.get(key, default=None)`
|
||||
- `await session.set(key, value)`
|
||||
- `await session.delete(key)`
|
||||
- `await session.clear()` — empties user state but **keeps the session valid**.
|
||||
- `await session.end()` — deletes the session (what `end_session` calls).
|
||||
|
||||
A session's state is stored as a **single dict under one key**
|
||||
(`session:{sha256(principal)}:{session_id}`, and `session:anon:{session_id}` when
|
||||
unauthenticated — the principal is hashed into a fixed-length, delimiter-safe
|
||||
segment, never embedded raw). That dict holds user state in a `state` sub-dict
|
||||
alongside a small `_created` marker, so a created-but-empty session is
|
||||
distinguishable from a missing one even if the store collapses empty dicts.
|
||||
`get`/`set`/`delete` read-modify-write the sub-dict and never touch the marker;
|
||||
`clear` resets the sub-dict but leaves the marker (the session still resolves);
|
||||
`end` deletes the key. Namespacing user state under `state` is what keeps a user
|
||||
key named `_created` from colliding with the marker. One key per session means
|
||||
one TTL per session (the store's), refreshed on write — no key index to maintain,
|
||||
and `end` is a single delete. (Trade-off: concurrent writes to one session race
|
||||
on the read-modify-write; session state is small and typically driven serially by
|
||||
one agent, so this is acceptable — noted, not hidden.)
|
||||
|
||||
## `SessionProvider`
|
||||
|
||||
Session ids are minted by `SessionProvider`, which contributes two tools:
|
||||
|
||||
- `create_session()` → mints an unguessable `uuid4`, **records** the session
|
||||
under the current principal, and returns the id as a string.
|
||||
- `end_session(session_id: SessionId)` → validates the id, then deletes the
|
||||
session so it no longer resolves.
|
||||
|
||||
Register it whenever your tools take a `session_id` — providers are the idiomatic
|
||||
way to add functionality like this:
|
||||
|
||||
```python
|
||||
from fastmcp.server.sessions import SessionProvider
|
||||
|
||||
mcp.add_provider(SessionProvider())
|
||||
```
|
||||
|
||||
There is **no enforcement** that a provider is registered, and there was: an
|
||||
earlier version scanned the tool set at list/resolve time and raised if a
|
||||
`session_id` tool had no provider. That check had to reason about the whole
|
||||
composition pipeline — `isinstance` on providers, unwrapping namespaced ones,
|
||||
tool transforms, session visibility, enabled state — and produced false
|
||||
positives that broke valid servers (a namespaced provider, a session-disabled
|
||||
tool). It was deleted. The guarantee never needed it: `get_session` validates
|
||||
that an id was recorded (create-then-validate), so a server with no provider
|
||||
simply cannot mint ids, and every `get_session` rejects — a misconfiguration
|
||||
caught the first time the tools run, not a security hole.
|
||||
|
||||
`SessionProvider` subclasses `Provider`, takes **no store** (uses the server's)
|
||||
and **no ttl** (the store's). It exists to mint and end owned ids.
|
||||
`create_session` matters most without auth, where an unguessable id is the only
|
||||
defense against a caller *guessing* onto another session.
|
||||
|
||||
When an application already mints its own identifiers — conversation ids, workflow
|
||||
ids — take them as ordinary string arguments rather than `SessionId`, and register
|
||||
no provider; `SessionId` is specifically the create-then-pass contract backed by
|
||||
`create_session`.
|
||||
|
||||
## Security
|
||||
|
||||
Keyed by `(principal, session_id)`:
|
||||
|
||||
- **Authenticated → strong isolation.** `principal` is the validated token
|
||||
subject, unforgeable. B keys into B's namespace; A's data is unreachable no
|
||||
matter what id B passes. Guessing is pointless; a session id appearing in agent
|
||||
context or logs is harmless (it is not a capability without the principal).
|
||||
Caller-chosen ids are safe here.
|
||||
- **Unauthenticated → single-tenant-safe only.** No principal, so the key is just
|
||||
the id in a shared namespace: the id becomes a bearer capability, and exposure
|
||||
in logs/conversation leaks the session. `create_session`'s `uuid4` gives
|
||||
guess-*resistance*, not isolation. Documented in bold: not a tenant boundary;
|
||||
without auth, force minted ids and never treat sessions as a wall between
|
||||
clients.
|
||||
- **Isolation is auth; the id is organization.** No id scheme substitutes for a
|
||||
principal, which is why sealing the handle buys nothing load-bearing and is
|
||||
dropped.
|
||||
- **Not FastMCP's job:** transport (use TLS), encryption at rest (the store's), a
|
||||
malicious *authorized* client acting within its rights.
|
||||
|
||||
## Rework plan (from the current prototype)
|
||||
|
||||
The prototype (`sessions.py`, `context.py`, `function_tool.py`, `server.py`) built
|
||||
a `Scope` enum, a sealed `SessionCodec`, and `ctx.get_state(scope=...)`. Rework to
|
||||
the above:
|
||||
|
||||
1. **Remove `Scope`** and the `scope=` parameter; revert `ctx.get_state`/
|
||||
`set_state` to their original request-scoped behavior.
|
||||
2. **Remove the `SessionCodec`/sealing** — ids are bare `uuid4`.
|
||||
3. **`Session` object** with async `get`/`set`/`delete`/`clear` over the server
|
||||
store, single-dict-per-session key scheme.
|
||||
4. **`session: UserSession`** injection (principal-keyed; error without auth) —
|
||||
wire into the same parameter-detection path as `Context`. `UserSession` is the
|
||||
injection marker; the injected value is a `Session`.
|
||||
5. **`session_id: SessionId`** marker type: string in the schema, auto-filled
|
||||
description, standalone `await get_session(id)` resolver that validates the id
|
||||
(works from a task worker — no foreground context needed).
|
||||
6. **`SessionProvider(Provider)`** with `create_session` (records the session) /
|
||||
`end_session` (deletes it), registered explicitly via `add_provider`. No
|
||||
enforcement that it is present — `get_session`'s validation is the guarantee.
|
||||
7. Rewrite the tests to cover both patterns, principal isolation, no-auth
|
||||
behavior, and `end_session`.
|
||||
|
||||
## Docs plan
|
||||
|
||||
Written against the final API once the rework verifies:
|
||||
|
||||
- A concept guide — why stateless removes the session, the two patterns, when to
|
||||
reach for each. Why before how.
|
||||
- A security page — the two tiers, "isolation is auth, the id is organization,"
|
||||
the bold no-multitenant-without-auth warning.
|
||||
- Fully runnable examples for both patterns (pass the doc-import guard, register
|
||||
in `docs.json`).
|
||||
- A migration note from the old `ctx.session_id` / `set_state`.
|
||||
142
docs/apps/architecture.mdx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
---
|
||||
title: Architecture
|
||||
sidebarTitle: Architecture
|
||||
description: How FastMCP apps work under the hood — from Python to pixels.
|
||||
icon: sitemap
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="3.2.0" />
|
||||
|
||||
You don't need this page to build apps. It's for when something isn't rendering the way you expect, when UI tool calls aren't reaching your server, or when you're writing [custom HTML apps](/apps/low-level) and need to understand the protocol directly.
|
||||
|
||||
## The pipeline
|
||||
|
||||
An MCP app moves through five stages from Python to pixels:
|
||||
|
||||
```
|
||||
Python components → JSON tree → structuredContent → Renderer iframe → Host UI
|
||||
```
|
||||
|
||||
You write Prefab components. FastMCP serializes them to a JSON component tree and delivers it as `structuredContent` on the tool result. The host loads the Prefab renderer in a sandboxed iframe, pushes the JSON in, and the renderer paints the UI. If the UI calls server tools, it talks back through the same `postMessage` channel.
|
||||
|
||||
The sections below walk each stage.
|
||||
|
||||
## Tool registration
|
||||
|
||||
When you mark a tool with `app=True` or `@app.ui()`, FastMCP wires up the metadata and renderer resource that the protocol requires.
|
||||
|
||||
### The `app=True` flag
|
||||
|
||||
`app` on `@mcp.tool` accepts `True`, an `AppConfig`, or a dict. When you pass `True`, FastMCP explicitly marks the tool as a Prefab UI tool and stamps placeholder UI metadata so the provider can synthesize the correct renderer resource later. When you omit `app`, FastMCP only applies this automatically if the tool's return type is a Prefab type (`PrefabApp`, `Component`, or unions containing them).
|
||||
|
||||
The tool and renderer are linked through a `resourceUri` field in the metadata. Internally, registration uses the placeholder URI `ui://prefab/renderer.html`; when tools and resources are listed or read, FastMCP rewrites that placeholder to a per-tool URI like `ui://prefab/tool/<hash>/renderer.html` and synthesizes the matching renderer resource on demand.
|
||||
|
||||
### FastMCPApp registration
|
||||
|
||||
`FastMCPApp` uses the same mechanism but adds two things. First, it tags every tool — both `@app.ui()` entry points and `@app.tool()` backends — with `meta["fastmcp"]["app"]` set to the app's name. That tag lets the server identify which app a tool belongs to when routing UI calls.
|
||||
|
||||
Second, it sets `meta["ui"]["visibility"]` to control who can see each tool. Entry points default to `["model"]` (LLM-visible). Backend tools default to `["app"]` (UI-only). Hosts use this to filter the tool list.
|
||||
|
||||
## Serialization
|
||||
|
||||
When a Prefab tool runs, its return value — a `PrefabApp` or a bare `Component` — becomes a JSON blob the renderer can interpret.
|
||||
|
||||
### `PrefabApp.to_json()`
|
||||
|
||||
The entry point is `PrefabApp.to_json()`. It walks the component tree and produces a JSON object with three top-level keys: `view` (the component tree), `state` (initial state values), and `_meta` (routing metadata).
|
||||
|
||||
FastMCP passes a `tool_resolver` callback to `to_json()`. Whenever the tree contains a `CallTool` action that references a function (not a string), the resolver converts it to a `ResolvedTool` with the function's registered name. For `FastMCPApp` backend tools, that registered name is then wrapped in the deterministic hashed format described below. The resolver also handles `unwrap_result` — a flag telling the renderer to unwrap single-value results from the `{"result": value}` envelope FastMCP uses for schema compliance.
|
||||
|
||||
### Hashed backend tool references
|
||||
|
||||
FastMCP still tags app tools with `meta["fastmcp"]["app"]`, but backend routing no longer depends on sending the app name through each tool call. During serialization, FastMCP passes a resolver to `PrefabApp.to_json()`. When the tree contains `CallTool(save_contact)`, the resolver turns it into a deterministic hashed name such as `<hash>_save_contact`, where the hash is derived from the app name and backend tool name.
|
||||
|
||||
That hashed name rides along inside `structuredContent` all the way to the renderer. When the renderer calls the backend tool, it sends the hashed tool name in the normal MCP `tools/call` request. The server recognizes that format and routes through the app-tool lookup path described below.
|
||||
|
||||
### ToolResult assembly
|
||||
|
||||
The final tool result has two parts: `content` (a list of `TextContent` blocks for the LLM) and `structuredContent` (the JSON tree for the renderer). By default, Prefab tools send `"[Rendered Prefab UI]"` as the text content — just enough for the LLM to know something was rendered. If you return a `ToolResult` explicitly, you control both halves.
|
||||
|
||||
## Tool call routing
|
||||
|
||||
A tool has two things that behave very differently. Its **name** is unstable by design — namespace transforms rename it, so `save_contact` becomes `contacts_save_contact` in one composition and something else in another. Its **identity** is a hash of the app name and the registered tool name, written once at registration and never changed.
|
||||
|
||||
A UI is serialized during the entry tool's call, deep inside whatever composition the server happens to have, so it cannot know what its backend tools will be called by the time the payload reaches a host.
|
||||
|
||||
### Late-bound tool names
|
||||
|
||||
The payload leaves the app addressed by identity, and every FastMCP server rewrites those references on the way out to whatever it lists that tool as. Servers unwind innermost-first, so the outermost server rewrites last — and its names are the only ones a client can actually invoke.
|
||||
|
||||
Rewriting a name in place would destroy the identity for the next layer up, so the payload carries a name-to-identity map under `_meta.fastmcp.toolNames`. Each layer resolves through the map and updates it. The action objects keep the exact shape `prefab_ui` defines: only the value of `tool` changes, and only ever to another valid tool name.
|
||||
|
||||
The result is that a renderer receives names that exist in the listing the host is looking at. Under three layers of namespacing the button calls `c_b_a_save`; behind a gateway it calls whatever the gateway lists. No intermediary has to understand a FastMCP-specific convention.
|
||||
|
||||
A reference this server cannot resolve is left alone rather than corrupted. This is what keeps apps working behind [tool search](/servers/transforms/tool-search) and code mode, which replace `tools/list` with a handful of synthetic tools: there is no better name to bind to, so the reference stays identity-addressed and the fallback below carries it.
|
||||
|
||||
### One copy of an app per server
|
||||
|
||||
**An app name must be unique within a server.** Composing the same app twice breaks its UI, and no namespace or mount arrangement makes it work.
|
||||
|
||||
The reason is structural. Identity is derived from the app name and the tool's registered name, and deliberately nothing else — that is what makes it survive renaming. Two copies of one app therefore produce two tools claiming a single identity, and no fact anywhere in the listing says which copy a given button belongs to. The information needed to choose was never recorded.
|
||||
|
||||
FastMCP declines to bind rather than picking a copy, so buttons stop working instead of quietly invoking the wrong tenant's tool. Expect a message naming the cause:
|
||||
|
||||
```
|
||||
Ambiguous app tool 'save': 2 components share the identity '10c0803009ff'.
|
||||
The same app is composed more than once, so this call cannot be routed to a
|
||||
single tool.
|
||||
```
|
||||
|
||||
Give each copy its own app name. Two tenants running the same product want `FastMCPApp("contacts-acme")` and `FastMCPApp("contacts-globex")` — not two instances of `FastMCPApp("contacts")` under different namespaces, since namespaces rename tools and identity is immune to renaming by design.
|
||||
|
||||
### The hashed lookup fallback
|
||||
|
||||
The identity-addressed form `<hash>_<local_name>` remains callable. FastMCP first tries normal tool resolution; if no tool matches and the name has that shape, it calls `get_tool_by_hash(hash, local_name)`, which walks the provider tree directly, skipping transforms.
|
||||
|
||||
When one identity is claimed by more than one tool — which happens when the same app is composed into two branches — the call is refused rather than resolved, since picking either one would silently route into the wrong branch.
|
||||
|
||||
Authorization still applies. The hashed path skips name and visibility transforms, but auth checks still run against the tool's `auth` config before execution.
|
||||
|
||||
### Provider delegation
|
||||
|
||||
`get_tool_by_hash` is defined on the `Provider` base class and overridden by aggregate and wrapped providers. Aggregate providers fan out the lookup across child providers in parallel. Wrapped providers (like `FastMCPProvider`, which wraps a nested `FastMCP` server) delegate to the inner server's hashed lookup. Backend tools are reachable through any depth of composition.
|
||||
|
||||
## The renderer
|
||||
|
||||
The Prefab renderer is a self-contained JavaScript application that interprets the JSON component tree and renders it as a React UI.
|
||||
|
||||
### Renderer resources
|
||||
|
||||
FastMCP exposes the renderer through per-tool resources such as `ui://prefab/tool/<hash>/renderer.html`, each with MIME type `text/html;profile=mcp-app`. The HTML is bundled inside the `prefab-ui` Python package; `get_renderer_html()` returns it as a string. The resources are synthesized on demand from each tool's UI metadata, so CSP and permissions can differ per tool even though they use the same Prefab renderer.
|
||||
|
||||
The resource also carries CSP metadata (via `get_renderer_csp()`) declaring the CDN domains the renderer needs. Hosts use this to configure the iframe's Content Security Policy.
|
||||
|
||||
### `postMessage` communication
|
||||
|
||||
The renderer lives in a sandboxed iframe and communicates with the host using `postMessage`. The protocol follows the [MCP Apps extension](https://modelcontextprotocol.io/docs/extensions/apps) spec:
|
||||
|
||||
The host pushes the tool result (with `structuredContent`) into the iframe. The renderer parses the component tree, initializes state, and renders the UI. When the user interacts — submitting a form, clicking a button — and the interaction triggers a `CallTool` action, the renderer sends a `callServerTool` message back to the host via `postMessage`. The host forwards it as a regular MCP `tools/call` request to the server, using the hashed backend name that FastMCP serialized into the action.
|
||||
|
||||
The response flows back the same way: server → host → iframe via `postMessage`, and the renderer updates state with the result.
|
||||
|
||||
### AppBridge
|
||||
|
||||
The `@modelcontextprotocol/ext-apps` JavaScript SDK provides the `App` class (sometimes called AppBridge) that manages the `postMessage` handshake. It handles connection negotiation, tool result delivery, server tool calls, and host context (safe area insets, theme preferences). The Prefab renderer uses it internally; you only touch it directly when building [custom HTML apps](/apps/low-level).
|
||||
|
||||
## The dev server
|
||||
|
||||
`fastmcp dev apps` simulates the host-side behavior locally without a real MCP client.
|
||||
|
||||
### Proxy architecture
|
||||
|
||||
Two HTTP servers. Your MCP server runs on port 8000 with the Streamable HTTP transport. The dev UI runs on port 8080 and serves a picker page that lists your app tools.
|
||||
|
||||
A reverse proxy at `/mcp` on the dev server forwards requests to your MCP server. This matters because the renderer iframe runs on `localhost:8080` and your MCP server runs on `localhost:8000` — without the proxy, the renderer's `callServerTool` requests would be cross-origin and the browser would block them. The proxy keeps everything same-origin from the iframe's perspective.
|
||||
|
||||
### The launch flow
|
||||
|
||||
When you select a tool and click launch, the dev UI calls the tool through the proxy, receives the `structuredContent` response, and opens a new tab. That tab loads the tool's renderer resource (via the proxy), creates an AppBridge, and pushes the tool result into the renderer. From here on it matches what a real host provides: the renderer displays the UI, and any `CallTool` actions route back through the proxy to your server.
|
||||
|
||||
Auto-reload is on by default, so changes to your server code restart the MCP server automatically. The dev UI keeps running — relaunch the tool to see changes.
|
||||
23
docs/apps/demos/bar-chart.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import Column
|
||||
from prefab_ui.components.charts import BarChart, ChartSeries
|
||||
|
||||
data = [
|
||||
{"quarter": "Q1", "revenue": 42000, "costs": 28000},
|
||||
{"quarter": "Q2", "revenue": 51000, "costs": 31000},
|
||||
{"quarter": "Q3", "revenue": 47000, "costs": 29000},
|
||||
{"quarter": "Q4", "revenue": 63000, "costs": 35000},
|
||||
]
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(css_class="p-6"):
|
||||
BarChart(
|
||||
data=data,
|
||||
series=[
|
||||
ChartSeries(data_key="revenue", label="Revenue"),
|
||||
ChartSeries(data_key="costs", label="Costs"),
|
||||
],
|
||||
x_axis="quarter",
|
||||
show_legend=True,
|
||||
height=250,
|
||||
)
|
||||
78
docs/apps/demos/contacts.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
from prefab_ui.actions import ShowToast
|
||||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import (
|
||||
H3,
|
||||
Badge,
|
||||
Button,
|
||||
Column,
|
||||
DataTable,
|
||||
DataTableColumn,
|
||||
Form,
|
||||
Input,
|
||||
Row,
|
||||
Select,
|
||||
SelectOption,
|
||||
Separator,
|
||||
)
|
||||
|
||||
contacts = [
|
||||
{"name": "Arthur Dent", "email": "arthur@earth.com", "category": "Customer"},
|
||||
{"name": "Ford Prefect", "email": "ford@betelgeuse.org", "category": "Partner"},
|
||||
{
|
||||
"name": "Trillian Astra",
|
||||
"email": "trillian@heartofgold.com",
|
||||
"category": "Customer",
|
||||
},
|
||||
{"name": "Zaphod Beeblebrox", "email": "zaphod@galaxy.gov", "category": "Vendor"},
|
||||
]
|
||||
|
||||
rows = [
|
||||
{
|
||||
"name": c["name"],
|
||||
"email": c["email"],
|
||||
"category": Badge(
|
||||
c["category"],
|
||||
variant="success"
|
||||
if c["category"] == "Customer"
|
||||
else "secondary"
|
||||
if c["category"] == "Partner"
|
||||
else "outline",
|
||||
),
|
||||
}
|
||||
for c in contacts
|
||||
]
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(gap=4, css_class="p-6"):
|
||||
DataTable(
|
||||
columns=[
|
||||
DataTableColumn(key="name", header="Name", sortable=True),
|
||||
DataTableColumn(key="email", header="Email"),
|
||||
DataTableColumn(key="category", header="Category"),
|
||||
],
|
||||
rows=rows,
|
||||
search=True,
|
||||
)
|
||||
|
||||
Separator()
|
||||
|
||||
H3("Add Contact")
|
||||
with Form(
|
||||
on_submit=ShowToast(
|
||||
"Contact saved! (preview demo — no backend wired)",
|
||||
variant="success",
|
||||
),
|
||||
):
|
||||
with Row(gap=4):
|
||||
Input(name="name", label="Name", placeholder="Full name", required=True)
|
||||
Input(
|
||||
name="email",
|
||||
label="Email",
|
||||
placeholder="name@example.com",
|
||||
required=True,
|
||||
)
|
||||
with Select(name="category", label="Category"):
|
||||
SelectOption(value="Customer", label="Customer")
|
||||
SelectOption(value="Partner", label="Partner")
|
||||
SelectOption(value="Vendor", label="Vendor")
|
||||
Button("Save Contact")
|
||||
68
docs/apps/demos/dashboard.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import (
|
||||
Badge,
|
||||
Column,
|
||||
DataTable,
|
||||
DataTableColumn,
|
||||
Row,
|
||||
Separator,
|
||||
)
|
||||
from prefab_ui.components.charts import BarChart, ChartSeries
|
||||
from prefab_ui.components.metric import Metric
|
||||
|
||||
monthly = [
|
||||
{"month": "Jan", "revenue": 48200, "costs": 31000},
|
||||
{"month": "Feb", "revenue": 52100, "costs": 32500},
|
||||
{"month": "Mar", "revenue": 61800, "costs": 34200},
|
||||
{"month": "Apr", "revenue": 58400, "costs": 33800},
|
||||
]
|
||||
|
||||
deals = [
|
||||
{"account": "Acme Corp", "value": "$84,000", "stage": "Won"},
|
||||
{"account": "Globex Inc", "value": "$52,000", "stage": "Negotiation"},
|
||||
{"account": "Initech", "value": "$31,500", "stage": "Proposal"},
|
||||
{"account": "Wayne Enterprises", "value": "$45,000", "stage": "Lost"},
|
||||
]
|
||||
|
||||
rows = [
|
||||
{
|
||||
"account": d["account"],
|
||||
"value": d["value"],
|
||||
"stage": Badge(
|
||||
d["stage"],
|
||||
variant="success"
|
||||
if d["stage"] == "Won"
|
||||
else "destructive"
|
||||
if d["stage"] == "Lost"
|
||||
else "secondary",
|
||||
),
|
||||
}
|
||||
for d in deals
|
||||
]
|
||||
|
||||
total = sum(m["revenue"] for m in monthly)
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(gap=4, css_class="p-6"):
|
||||
with Row(gap=6):
|
||||
Metric(label="Revenue (Q1-Q4)", value=f"${total:,}")
|
||||
Metric(label="Deals", value=f"{len(deals)}")
|
||||
BarChart(
|
||||
data=monthly,
|
||||
series=[
|
||||
ChartSeries(data_key="revenue", label="Revenue"),
|
||||
ChartSeries(data_key="costs", label="Costs"),
|
||||
],
|
||||
x_axis="month",
|
||||
show_legend=True,
|
||||
height=200,
|
||||
)
|
||||
Separator()
|
||||
DataTable(
|
||||
columns=[
|
||||
DataTableColumn(key="account", header="Account", sortable=True),
|
||||
DataTableColumn(key="value", header="Value", sortable=True),
|
||||
DataTableColumn(key="stage", header="Stage"),
|
||||
],
|
||||
rows=rows,
|
||||
)
|
||||
24
docs/apps/demos/data-table.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import Column, DataTable, DataTableColumn
|
||||
|
||||
employees = [
|
||||
{"name": "Alice Chen", "role": "Staff Engineer", "dept": "Platform"},
|
||||
{"name": "Bob Martinez", "role": "Lead Designer", "dept": "Design"},
|
||||
{"name": "Carol Johnson", "role": "Senior Engineer", "dept": "Platform"},
|
||||
{"name": "David Kim", "role": "Product Manager", "dept": "Product"},
|
||||
{"name": "Eva Mueller", "role": "Engineer", "dept": "Platform"},
|
||||
{"name": "Frank Lee", "role": "Data Scientist", "dept": "ML"},
|
||||
{"name": "Grace Park", "role": "Eng Manager", "dept": "Platform"},
|
||||
]
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(gap=4, css_class="p-6"):
|
||||
DataTable(
|
||||
columns=[
|
||||
DataTableColumn(key="name", header="Name", sortable=True),
|
||||
DataTableColumn(key="role", header="Role", sortable=True),
|
||||
DataTableColumn(key="dept", header="Dept", sortable=True),
|
||||
],
|
||||
rows=employees,
|
||||
search=True,
|
||||
)
|
||||
461
docs/apps/demos/hitchhikers.py
Normal file
|
|
@ -0,0 +1,461 @@
|
|||
"""The Hitchhiker's Guide dashboard from the Prefab welcome page.
|
||||
|
||||
Run with:
|
||||
prefab serve examples/hitchhikers-guide/dashboard.py
|
||||
prefab export examples/hitchhikers-guide/dashboard.py
|
||||
"""
|
||||
|
||||
from prefab_ui import PrefabApp
|
||||
from prefab_ui.actions import SetInterval, SetState, ShowToast
|
||||
from prefab_ui.components import (
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
Carousel,
|
||||
Checkbox,
|
||||
Column,
|
||||
Combobox,
|
||||
ComboboxOption,
|
||||
DataTable,
|
||||
DataTableColumn,
|
||||
DatePicker,
|
||||
Dialog,
|
||||
Grid,
|
||||
GridItem,
|
||||
HoverCard,
|
||||
Loader,
|
||||
Metric,
|
||||
Muted,
|
||||
P,
|
||||
Progress,
|
||||
Radio,
|
||||
RadioGroup,
|
||||
Ring,
|
||||
Row,
|
||||
Separator,
|
||||
Slider,
|
||||
Switch,
|
||||
Text,
|
||||
Tooltip,
|
||||
)
|
||||
from prefab_ui.components.charts import (
|
||||
BarChart,
|
||||
ChartSeries,
|
||||
RadarChart,
|
||||
Sparkline,
|
||||
)
|
||||
from prefab_ui.components.control_flow import Else, If
|
||||
from prefab_ui.rx import Rx
|
||||
|
||||
ctx_tick = Rx("ctx_tick")
|
||||
|
||||
# Context window: climbs from 24% to ~78%, then resets
|
||||
ctx_pct = (ctx_tick % 20) * 3 + 20
|
||||
ctx_variant = (ctx_pct > 70).then(
|
||||
"destructive", (ctx_pct <= 33).then("success", "default")
|
||||
)
|
||||
|
||||
with PrefabApp(
|
||||
title="Prefab Showcase",
|
||||
state={"ctx_tick": 0, "improbability": 42},
|
||||
on_mount=SetInterval(
|
||||
400,
|
||||
on_tick=SetState("ctx_tick", ctx_tick + 1),
|
||||
),
|
||||
) as app:
|
||||
with Grid(columns={"default": 1, "md": 2, "lg": 4}, gap=4):
|
||||
# ── Col 1 ─────────────────────────────────────────────────────────
|
||||
with Column(gap=4):
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Register Towel")
|
||||
CardDescription("The most important item in the galaxy")
|
||||
with CardContent():
|
||||
with Column(gap=3):
|
||||
with Combobox(
|
||||
placeholder="Type...",
|
||||
search_placeholder="Search types...",
|
||||
):
|
||||
ComboboxOption("Bath", value="bath")
|
||||
ComboboxOption("Beach", value="beach")
|
||||
ComboboxOption("Interstellar", value="interstellar")
|
||||
ComboboxOption("Microfiber", value="micro")
|
||||
DatePicker(placeholder="Registration date")
|
||||
with CardFooter():
|
||||
with Row(gap=2):
|
||||
with Dialog(
|
||||
title="Towel Registered!",
|
||||
description="Your towel has been added to the galactic registry.",
|
||||
):
|
||||
Button("Register")
|
||||
Text("Don't forget to bring it.")
|
||||
Button("Cancel", variant="outline")
|
||||
with If("{{ !pressed }}"):
|
||||
Button(
|
||||
"This is probably the best button to press.",
|
||||
variant="success",
|
||||
on_click=SetState("pressed", True),
|
||||
)
|
||||
with Else():
|
||||
Button(
|
||||
"Please do not press this button again.",
|
||||
variant="destructive",
|
||||
on_click=SetState("pressed", False),
|
||||
)
|
||||
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Ship Status")
|
||||
with CardContent():
|
||||
with Column(gap=3):
|
||||
with Row(
|
||||
align="center",
|
||||
css_class="justify-between",
|
||||
):
|
||||
Text("heart-of-gold")
|
||||
with HoverCard(open_delay=0, close_delay=200):
|
||||
Badge("In Orbit", variant="default")
|
||||
with Column(gap=2):
|
||||
Text("heart-of-gold")
|
||||
Muted("Deployed 2h ago")
|
||||
Progress(
|
||||
value=100,
|
||||
max=100,
|
||||
variant="success",
|
||||
)
|
||||
Progress(
|
||||
value=100,
|
||||
max=100,
|
||||
indicator_class="bg-yellow-400",
|
||||
)
|
||||
with Row(
|
||||
align="center",
|
||||
css_class="justify-between",
|
||||
):
|
||||
Text("vogon-poetry")
|
||||
with Tooltip("64% — ETA 12 min", delay=0):
|
||||
with Badge(variant="secondary"):
|
||||
Loader(size="sm")
|
||||
Text("Deploying")
|
||||
Progress(value=64, max=100)
|
||||
with Row(
|
||||
align="center",
|
||||
css_class="justify-between",
|
||||
):
|
||||
Text("deep-thought")
|
||||
with Tooltip(
|
||||
"Computing... 7.5 million years remaining",
|
||||
delay=0,
|
||||
):
|
||||
with Badge(variant="outline"):
|
||||
Loader(size="sm", variant="ios")
|
||||
Text("Soon...")
|
||||
Progress(value=12, max=100)
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Planet Ratings")
|
||||
with CardContent():
|
||||
RadarChart(
|
||||
data=[
|
||||
{"axis": "Views", "earth": 30, "mag": 95},
|
||||
{"axis": "Fjords", "earth": 65, "mag": 100},
|
||||
{"axis": "Pubs", "earth": 90, "mag": 10},
|
||||
{"axis": "Mice", "earth": 40, "mag": 85},
|
||||
{"axis": "Tea", "earth": 95, "mag": 15},
|
||||
{"axis": "Safety", "earth": 45, "mag": 70},
|
||||
],
|
||||
series=[
|
||||
ChartSeries(dataKey="earth", label="Earth"),
|
||||
ChartSeries(dataKey="mag", label="Magrathea"),
|
||||
],
|
||||
axis_key="axis",
|
||||
height=200,
|
||||
show_legend=True,
|
||||
show_tooltip=True,
|
||||
)
|
||||
|
||||
# ── Col 2 ─────────────────────────────────────────────────────────
|
||||
with Column(gap=4):
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Survival Odds")
|
||||
with CardContent(css_class="w-fit mx-auto"):
|
||||
Ring(
|
||||
value=42,
|
||||
label="42%",
|
||||
variant="info",
|
||||
size="lg",
|
||||
thickness=12,
|
||||
indicator_class="group-hover:drop-shadow-[0_0_24px_rgba(59,130,246,0.9)]",
|
||||
)
|
||||
with Card():
|
||||
with CardHeader():
|
||||
with Row(gap=2, align="center"):
|
||||
CardTitle("Improbability Drive")
|
||||
Loader(
|
||||
variant="pulse",
|
||||
size="sm",
|
||||
css_class="text-blue-500",
|
||||
)
|
||||
with CardContent():
|
||||
with Column(gap=2):
|
||||
Slider(
|
||||
min=0,
|
||||
max=100,
|
||||
value=42,
|
||||
name="improbability",
|
||||
)
|
||||
with Row(
|
||||
align="center",
|
||||
css_class="justify-between",
|
||||
):
|
||||
Muted("Probable")
|
||||
Muted("Infinite")
|
||||
with Carousel(auto_advance=3000, show_controls=False, direction="up"):
|
||||
with Alert(variant="success", icon="circle-check"):
|
||||
AlertTitle("Don't Panic")
|
||||
AlertDescription("Normality achieved.")
|
||||
with Alert(variant="destructive", icon="triangle-alert"):
|
||||
AlertTitle("Display Department")
|
||||
AlertDescription("Beware of the leopard.")
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Prefect Horizon Config")
|
||||
with CardContent():
|
||||
with Column(gap=3):
|
||||
Switch(
|
||||
label="Auto-scale agents",
|
||||
value=True,
|
||||
name="autoscale",
|
||||
)
|
||||
Separator()
|
||||
Switch(
|
||||
label="Code Mode",
|
||||
value=True,
|
||||
name="code_mode",
|
||||
)
|
||||
Separator()
|
||||
Switch(
|
||||
label="Tool call caching",
|
||||
value=False,
|
||||
name="cache",
|
||||
)
|
||||
with CardFooter():
|
||||
Button(
|
||||
"Save Preferences",
|
||||
on_click=ShowToast("Preferences saved!"),
|
||||
)
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Travel Class")
|
||||
with CardContent():
|
||||
with RadioGroup(name="travel_class"):
|
||||
Radio(option="economy", label="Economy")
|
||||
Radio(option="business", label="Business Class")
|
||||
Radio(
|
||||
option="improbability",
|
||||
label="Infinite Improbability",
|
||||
value=True,
|
||||
)
|
||||
|
||||
# ── Cols 3–4: summary row, chart, then 2-col grid below ─────────
|
||||
with GridItem(css_class="md:col-span-2"):
|
||||
with Column(gap=4):
|
||||
with Grid(columns=2, gap=4, css_class="h-32"):
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Context Window")
|
||||
with CardContent():
|
||||
with Column(
|
||||
gap=6,
|
||||
justify="center",
|
||||
css_class="h-full",
|
||||
):
|
||||
with Row(
|
||||
align="center",
|
||||
css_class="justify-between",
|
||||
):
|
||||
Text(f"{ctx_pct}% used")
|
||||
Muted(f"{ctx_pct * 2}k / 200k tokens")
|
||||
with Tooltip(
|
||||
"Auto-compact buffer: 12%",
|
||||
delay=0,
|
||||
):
|
||||
Progress(
|
||||
value=ctx_pct,
|
||||
max=100,
|
||||
variant=ctx_variant,
|
||||
)
|
||||
with Card(css_class="pb-0 gap-0"):
|
||||
with CardContent():
|
||||
Metric(
|
||||
label="Fjords designed",
|
||||
value="1,847",
|
||||
delta="+3 coastlines",
|
||||
)
|
||||
Sparkline(
|
||||
data=[
|
||||
820,
|
||||
950,
|
||||
1100,
|
||||
980,
|
||||
1250,
|
||||
1400,
|
||||
1350,
|
||||
1500,
|
||||
1680,
|
||||
1847,
|
||||
],
|
||||
variant="success",
|
||||
fill=True,
|
||||
css_class="h-16",
|
||||
)
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Towel Incidents")
|
||||
with CardContent():
|
||||
BarChart(
|
||||
data=[
|
||||
{"month": "Jan", "lost": 8, "found": 5},
|
||||
{"month": "Feb", "lost": 24, "found": 15},
|
||||
{"month": "Mar", "lost": 12, "found": 28},
|
||||
{"month": "Apr", "lost": 35, "found": 19},
|
||||
{"month": "May", "lost": 18, "found": 38},
|
||||
{"month": "Jun", "lost": 42, "found": 30},
|
||||
],
|
||||
series=[
|
||||
ChartSeries(dataKey="lost", label="Lost"),
|
||||
ChartSeries(dataKey="found", label="Found"),
|
||||
],
|
||||
x_axis="month",
|
||||
height=200,
|
||||
bar_radius=4,
|
||||
show_legend=True,
|
||||
show_tooltip=True,
|
||||
show_grid=True,
|
||||
)
|
||||
|
||||
with Grid(columns=2, gap=4):
|
||||
with Column(gap=4):
|
||||
with Card():
|
||||
with CardContent():
|
||||
with Column(gap=2):
|
||||
Checkbox(label="Towel packed", value=True)
|
||||
Checkbox(label="Guide charged", value=True)
|
||||
Checkbox(
|
||||
label="Babel fish inserted",
|
||||
value=False,
|
||||
)
|
||||
with Card():
|
||||
with CardHeader():
|
||||
CardTitle("Marvin's Mood")
|
||||
with CardContent():
|
||||
with Column(gap=3):
|
||||
P("How's life?")
|
||||
with Column(gap=2):
|
||||
Button(
|
||||
"Meh",
|
||||
on_click=ShowToast(
|
||||
"Noted. Enthusiasm levels nominal."
|
||||
),
|
||||
)
|
||||
Button(
|
||||
"Depressed",
|
||||
variant="info",
|
||||
on_click=ShowToast(
|
||||
"I think you ought to "
|
||||
"know I'm feeling very "
|
||||
"depressed."
|
||||
),
|
||||
)
|
||||
Button(
|
||||
"Don't talk to me about life",
|
||||
variant="warning",
|
||||
on_click=ShowToast(
|
||||
"Brain the size of a "
|
||||
"planet and they ask me "
|
||||
"to pick up a piece of "
|
||||
"paper."
|
||||
),
|
||||
)
|
||||
|
||||
with Column(gap=4):
|
||||
with Card():
|
||||
with CardContent():
|
||||
with Row(gap=2, align="center"):
|
||||
Loader(variant="dots", size="sm")
|
||||
Muted("Marvin is thinking...")
|
||||
with Card():
|
||||
with CardContent():
|
||||
DataTable(
|
||||
columns=[
|
||||
DataTableColumn(
|
||||
key="crew",
|
||||
header="Crew",
|
||||
sortable=True,
|
||||
),
|
||||
DataTableColumn(
|
||||
key="species",
|
||||
header="Species",
|
||||
sortable=True,
|
||||
),
|
||||
DataTableColumn(
|
||||
key="towel",
|
||||
header="Towel?",
|
||||
sortable=True,
|
||||
),
|
||||
DataTableColumn(
|
||||
key="status",
|
||||
header="Status",
|
||||
sortable=True,
|
||||
),
|
||||
],
|
||||
rows=[
|
||||
{
|
||||
"crew": "Arthur Dent",
|
||||
"species": "Human",
|
||||
"towel": "Yes",
|
||||
"status": "Confused",
|
||||
},
|
||||
{
|
||||
"crew": "Ford Prefect",
|
||||
"species": "Betelgeusian",
|
||||
"towel": "Always",
|
||||
"status": "Drinking",
|
||||
},
|
||||
{
|
||||
"crew": "Zaphod",
|
||||
"species": "Betelgeusian",
|
||||
"towel": "Lost it",
|
||||
"status": "Presidential",
|
||||
},
|
||||
{
|
||||
"crew": "Trillian",
|
||||
"species": "Human",
|
||||
"towel": "Yes",
|
||||
"status": "Navigating",
|
||||
},
|
||||
{
|
||||
"crew": "Marvin",
|
||||
"species": "Android",
|
||||
"towel": "No point",
|
||||
"status": "Depressed",
|
||||
},
|
||||
{
|
||||
"crew": "Slartibartfast",
|
||||
"species": "Magrathean",
|
||||
"towel": "Somewhere",
|
||||
"status": "Designing",
|
||||
},
|
||||
],
|
||||
search=True,
|
||||
paginated=False,
|
||||
)
|
||||
21
docs/apps/demos/pie-chart.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import Column
|
||||
from prefab_ui.components.charts import PieChart
|
||||
|
||||
data = [
|
||||
{"category": "Bug", "count": 42},
|
||||
{"category": "Feature", "count": 28},
|
||||
{"category": "Docs", "count": 15},
|
||||
{"category": "Infra", "count": 10},
|
||||
]
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(css_class="p-6"):
|
||||
PieChart(
|
||||
data=data,
|
||||
data_key="count",
|
||||
name_key="category",
|
||||
inner_radius=50,
|
||||
show_legend=True,
|
||||
height=240,
|
||||
)
|
||||
66
docs/apps/demos/reactive.py
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import (
|
||||
Column,
|
||||
Row,
|
||||
Select,
|
||||
SelectOption,
|
||||
Switch,
|
||||
Text,
|
||||
)
|
||||
from prefab_ui.components.charts import BarChart, ChartSeries
|
||||
from prefab_ui.components.control_flow import If
|
||||
from prefab_ui.components.metric import Metric
|
||||
from prefab_ui.rx import Rx
|
||||
|
||||
region = Rx("region")
|
||||
|
||||
north = [
|
||||
{"month": "Jan", "sales": 22000},
|
||||
{"month": "Feb", "sales": 25500},
|
||||
{"month": "Mar", "sales": 24200},
|
||||
]
|
||||
south = [
|
||||
{"month": "Jan", "sales": 5800},
|
||||
{"month": "Feb", "sales": 6400},
|
||||
{"month": "Mar", "sales": 5600},
|
||||
]
|
||||
west = [
|
||||
{"month": "Jan", "sales": 6000},
|
||||
{"month": "Feb", "sales": 6000},
|
||||
{"month": "Mar", "sales": 5600},
|
||||
]
|
||||
|
||||
with PrefabApp(
|
||||
state={
|
||||
"region": "north",
|
||||
"north": north,
|
||||
"south": south,
|
||||
"west": west,
|
||||
"show_target": True,
|
||||
},
|
||||
) as app:
|
||||
with Column(
|
||||
gap=4,
|
||||
css_class="p-6",
|
||||
let={
|
||||
"data": "{{ region == 'south' ? south : region == 'west' ? west : north }}",
|
||||
},
|
||||
):
|
||||
with Row(gap=4, align="center"):
|
||||
with Select(name="region", css_class="w-40"):
|
||||
SelectOption(value="north", label="North")
|
||||
SelectOption(value="south", label="South")
|
||||
SelectOption(value="west", label="West")
|
||||
Switch(name="show_target", css_class="ml-auto")
|
||||
Text("Show target", css_class="text-sm text-muted-foreground")
|
||||
BarChart(
|
||||
data=Rx("data"),
|
||||
series=[ChartSeries(data_key="sales", label="Sales")],
|
||||
x_axis="month",
|
||||
height=200,
|
||||
)
|
||||
with If(Rx("show_target")):
|
||||
Metric(
|
||||
label="Q1 Target",
|
||||
value="$75,000",
|
||||
)
|
||||
116
docs/apps/demos/team-directory-reactive.py
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
from collections import Counter
|
||||
|
||||
from prefab_ui.actions import SetState
|
||||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import (
|
||||
H3,
|
||||
Badge,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
Column,
|
||||
DataTable,
|
||||
DataTableColumn,
|
||||
Grid,
|
||||
Row,
|
||||
Small,
|
||||
Text,
|
||||
)
|
||||
from prefab_ui.components.charts import PieChart
|
||||
from prefab_ui.components.control_flow import If
|
||||
from prefab_ui.rx import STATE, Rx
|
||||
|
||||
MEMBERS = [
|
||||
{
|
||||
"name": "Alice Chen",
|
||||
"role": "Staff Engineer",
|
||||
"office": "San Francisco",
|
||||
"email": "alice@company.com",
|
||||
"projects": 3,
|
||||
},
|
||||
{
|
||||
"name": "Bob Martinez",
|
||||
"role": "Lead Designer",
|
||||
"office": "New York",
|
||||
"email": "bob@company.com",
|
||||
"projects": 5,
|
||||
},
|
||||
{
|
||||
"name": "Carol Johnson",
|
||||
"role": "Senior Engineer",
|
||||
"office": "London",
|
||||
"email": "carol@company.com",
|
||||
"projects": 2,
|
||||
},
|
||||
{
|
||||
"name": "David Kim",
|
||||
"role": "Product Manager",
|
||||
"office": "San Francisco",
|
||||
"email": "david@company.com",
|
||||
"projects": 7,
|
||||
},
|
||||
{
|
||||
"name": "Eva Mueller",
|
||||
"role": "Engineer",
|
||||
"office": "Berlin",
|
||||
"email": "eva@company.com",
|
||||
"projects": 1,
|
||||
},
|
||||
{
|
||||
"name": "Frank Lee",
|
||||
"role": "Data Scientist",
|
||||
"office": "San Francisco",
|
||||
"email": "frank@company.com",
|
||||
"projects": 4,
|
||||
},
|
||||
{
|
||||
"name": "Grace Park",
|
||||
"role": "Engineering Manager",
|
||||
"office": "New York",
|
||||
"email": "grace@company.com",
|
||||
"projects": 6,
|
||||
},
|
||||
]
|
||||
|
||||
OFFICE_COUNTS = [
|
||||
{"office": office, "count": count}
|
||||
for office, count in Counter(m["office"] for m in MEMBERS).items()
|
||||
]
|
||||
|
||||
with PrefabApp(state={"selected": None}) as app:
|
||||
with Column(gap=4, css_class="p-6"):
|
||||
with Grid(columns=[1, 2], gap=4):
|
||||
PieChart(
|
||||
data=OFFICE_COUNTS,
|
||||
data_key="count",
|
||||
name_key="office",
|
||||
show_legend=True,
|
||||
)
|
||||
DataTable(
|
||||
columns=[
|
||||
DataTableColumn(key="name", header="Name", sortable=True),
|
||||
DataTableColumn(key="role", header="Role", sortable=True),
|
||||
DataTableColumn(key="office", header="Office", sortable=True),
|
||||
],
|
||||
rows=MEMBERS,
|
||||
search=True,
|
||||
on_row_click=SetState("selected", Rx("$event")),
|
||||
)
|
||||
|
||||
with If(STATE.selected):
|
||||
with Card():
|
||||
with CardHeader():
|
||||
with Row(gap=2, align="center"):
|
||||
H3(Rx("selected.name"))
|
||||
Badge(Rx("selected.office"))
|
||||
with CardContent():
|
||||
with Grid(columns=3, gap=4):
|
||||
with Column(gap=0):
|
||||
Small("Role")
|
||||
Text(Rx("selected.role"))
|
||||
with Column(gap=0):
|
||||
Small("Email")
|
||||
Text(Rx("selected.email"))
|
||||
with Column(gap=0):
|
||||
Small("Active Projects")
|
||||
Text(Rx("selected.projects"))
|
||||
39
docs/apps/demos/team-directory.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
from collections import Counter
|
||||
|
||||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import Column, DataTable, DataTableColumn, Grid
|
||||
from prefab_ui.components.charts import PieChart
|
||||
|
||||
members = [
|
||||
{"name": "Alice Chen", "role": "Staff Engineer", "office": "San Francisco"},
|
||||
{"name": "Bob Martinez", "role": "Lead Designer", "office": "New York"},
|
||||
{"name": "Carol Johnson", "role": "Senior Engineer", "office": "London"},
|
||||
{"name": "David Kim", "role": "Product Manager", "office": "San Francisco"},
|
||||
{"name": "Eva Mueller", "role": "Engineer", "office": "Berlin"},
|
||||
{"name": "Frank Lee", "role": "Data Scientist", "office": "San Francisco"},
|
||||
{"name": "Grace Park", "role": "Engineering Manager", "office": "New York"},
|
||||
]
|
||||
|
||||
office_counts = [
|
||||
{"office": office, "count": count}
|
||||
for office, count in Counter(m["office"] for m in members).items()
|
||||
]
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(gap=4, css_class="p-6"):
|
||||
with Grid(columns=[1, 2], gap=4):
|
||||
PieChart(
|
||||
data=office_counts,
|
||||
data_key="count",
|
||||
name_key="office",
|
||||
show_legend=True,
|
||||
)
|
||||
DataTable(
|
||||
columns=[
|
||||
DataTableColumn(key="name", header="Name", sortable=True),
|
||||
DataTableColumn(key="role", header="Role", sortable=True),
|
||||
DataTableColumn(key="office", header="Office", sortable=True),
|
||||
],
|
||||
rows=members,
|
||||
search=True,
|
||||
)
|
||||
67
docs/apps/development.mdx
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
---
|
||||
title: Development
|
||||
sidebarTitle: Development
|
||||
description: Preview and test your app tools locally without a full MCP host.
|
||||
icon: flask
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="3.2.0" />
|
||||
|
||||
<Frame>
|
||||
<img src="/apps/images/dev-app.png" alt="The dev UI showing a rendered Prefab app with the MCP inspector panel" />
|
||||
</Frame>
|
||||
|
||||
`fastmcp dev apps` gives you a browser preview for your app tools without needing an MCP host client. It starts your server and a local dev UI side by side: you pick a tool, fill in its arguments, and the rendered result opens in a new tab.
|
||||
|
||||
Works with both [Interactive Tools](/apps/prefab) and [custom HTML apps](/apps/low-level).
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
fastmcp dev apps server.py
|
||||
```
|
||||
|
||||
The dev UI opens at `http://localhost:8080`. Your MCP server runs on port 8000 with auto-reload enabled by default — save a file and the server restarts automatically.
|
||||
|
||||
## How it works
|
||||
|
||||
The dev server does three things:
|
||||
|
||||
The **picker page** connects to your MCP server, finds all tools with UI metadata, and renders a form for each one. The forms are auto-generated from the tool's input schema — text fields, dropdowns, checkboxes, all wired up.
|
||||
|
||||
When you submit a form, the dev server **calls your tool** via the MCP protocol and opens the result in a new tab. The result page loads the tool's UI resource (the Prefab renderer or your custom HTML) inside an AppBridge — the same protocol that real MCP hosts use.
|
||||
|
||||
A **reverse proxy** on `/mcp` forwards requests from the browser to your MCP server, avoiding CORS issues that would otherwise block the iframe-based renderer from talking to a different port.
|
||||
|
||||
## MCP inspector
|
||||
|
||||
The dev UI includes an inspector panel on the left side that captures MCP traffic in real time. It shows JSON-RPC messages flowing between the browser and your server — requests, responses, and AppBridge `postMessage` traffic.
|
||||
|
||||
Each entry shows direction, method, timing, and a smart summary. Click any entry to expand the full JSON-RPC body. The panel auto-scrolls to new messages unless you've scrolled up to inspect older ones.
|
||||
|
||||
The inspector is useful for debugging: you can see exactly what arguments your tool received, what it returned, and how the AppBridge communicated with the renderer.
|
||||
|
||||
## Options
|
||||
|
||||
```bash
|
||||
fastmcp dev apps server.py:mcp --mcp-port 9000 --dev-port 9090 --no-reload
|
||||
```
|
||||
|
||||
| Option | Flag | Default | Description |
|
||||
| ------ | ---- | ------- | ----------- |
|
||||
| MCP Port | `--mcp-port` | `8000` | Port for your MCP server |
|
||||
| Dev Port | `--dev-port` | `8080` | Port for the dev UI |
|
||||
| Auto-Reload | `--reload` / `--no-reload` | On | Watch files and restart the server on changes |
|
||||
| Host | `--host` | `127.0.0.1` | Interface for both local servers to bind |
|
||||
| Log Panel | `--log-panel` / `--no-log-panel` | On | Show or hide the log panel in the dev UI |
|
||||
|
||||
## Multiple tools
|
||||
|
||||
If your server has multiple app tools, the picker shows a dropdown. Each tool gets its own form and launch button. The tool's `title` is displayed when available, falling back to the tool name.
|
||||
|
||||
```bash
|
||||
# Server with multiple app tools
|
||||
fastmcp dev apps examples/apps/contacts/contacts_server.py
|
||||
```
|
||||
92
docs/apps/examples.mdx
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
---
|
||||
title: Examples
|
||||
sidebarTitle: Examples
|
||||
description: Example apps you can run right now.
|
||||
icon: images
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="3.2.0" />
|
||||
|
||||
Each tile below is a working FastMCP server you can run with `fastmcp dev apps` or connect to from any MCP host. Source lives in `examples/apps/` in the repository.
|
||||
|
||||
<Columns cols={2}>
|
||||
<Tile href="#sales-dashboard" title="Sales Dashboard" description="Metrics, charts, and deal pipeline">
|
||||
<div style={{overflow: "hidden", width: "100%"}}>
|
||||
<img src="/apps/images/app-example-sales-dashboard.png" />
|
||||
</div>
|
||||
</Tile>
|
||||
<Tile href="#system-monitor" title="System Monitor" description="Live CPU, memory, disk with auto-refresh">
|
||||
<img src="/apps/images/app-example-system-dashboard.png" />
|
||||
</Tile>
|
||||
<Tile href="#quiz" title="Quiz" description="LLM-generated trivia with scoring">
|
||||
<img src="/apps/images/app-example-quiz.png" />
|
||||
</Tile>
|
||||
<Tile href="#interactive-map" title="Interactive Map" description="Geocoded addresses on Leaflet">
|
||||
<img src="/apps/images/app-example-map.png" />
|
||||
</Tile>
|
||||
<Tile href="/apps/providers/file-upload" title="File Upload" description="Drag-and-drop upload provider">
|
||||
<img src="/apps/images/app-file-upload.png" />
|
||||
</Tile>
|
||||
<Tile href="/apps/providers/approval" title="Approval" description="Human-in-the-loop confirmation">
|
||||
<img src="/apps/images/app-approval.png" />
|
||||
</Tile>
|
||||
<Tile href="/apps/providers/choice" title="Choice" description="Clickable option selection">
|
||||
<img src="/apps/images/app-choice.png" />
|
||||
</Tile>
|
||||
<Tile href="/apps/providers/form" title="Form Input" description="Pydantic model forms">
|
||||
<img src="/apps/images/app-form.png" />
|
||||
</Tile>
|
||||
<Tile href="/apps/generative" title="Generative UI" description="LLM writes the UI at runtime">
|
||||
<img src="/apps/images/app-showcase.png" />
|
||||
</Tile>
|
||||
</Columns>
|
||||
|
||||
## Running the examples
|
||||
|
||||
Preview any example in your browser with the dev server:
|
||||
|
||||
```bash
|
||||
pip install "fastmcp[apps]"
|
||||
fastmcp dev apps examples/apps/sales_dashboard/sales_dashboard_server.py
|
||||
```
|
||||
|
||||
The dev UI lets you pick a tool and fill in arguments. In a real deployment the LLM provides those arguments from conversation context — the quiz example especially shines when connected to a host like Goose or Claude Desktop, where the LLM generates the questions itself.
|
||||
|
||||
## Standalone apps
|
||||
|
||||
### Sales dashboard
|
||||
|
||||
A full dashboard with KPI metrics, revenue trends, segment breakdown, and a deal pipeline table. Shows what you can build with a single `app=True` tool and Prefab's chart and data components.
|
||||
|
||||
```bash
|
||||
fastmcp dev apps examples/apps/sales_dashboard/sales_dashboard_server.py
|
||||
```
|
||||
|
||||
### System monitor
|
||||
|
||||
Reads live CPU, memory, and disk stats from your machine using `psutil`. Auto-refreshes via `SetInterval` calling a backend tool, with a dropdown to control the refresh rate. The chart accumulates up to 100 data points over time.
|
||||
|
||||
```bash
|
||||
pip install psutil
|
||||
fastmcp dev apps examples/apps/system_monitor/system_monitor_server.py
|
||||
```
|
||||
|
||||
### Quiz
|
||||
|
||||
The LLM generates trivia questions and passes them to the tool. The user answers via buttons, sees correct/incorrect feedback, and tracks score across questions. Demonstrates multi-turn client-side state with FastMCPApp.
|
||||
|
||||
```bash
|
||||
fastmcp dev apps examples/apps/quiz/quiz_server.py
|
||||
```
|
||||
|
||||
### Interactive map
|
||||
|
||||
Accepts addresses or place names, geocodes them via OpenStreetMap Nominatim (free, no API key), and renders an interactive Leaflet map using Prefab's `Embed` component with inline HTML. A reminder that Prefab apps can break out of built-in components when they need to.
|
||||
|
||||
```bash
|
||||
fastmcp dev apps examples/apps/map/map_server.py
|
||||
```
|
||||
|
||||
For ready-made building blocks like approvals, choice pickers, file uploads, and Pydantic forms, see the [Providers](/apps/providers/approval) group.
|
||||
474
docs/apps/fastmcp-app.mdx
Normal file
|
|
@ -0,0 +1,474 @@
|
|||
---
|
||||
title: FastMCPApp
|
||||
sidebarTitle: FastMCPApp
|
||||
description: Wire an interactive UI to backend tools with managed visibility and composition safety.
|
||||
icon: puzzle-piece
|
||||
tag: NEW
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
import PrefabPinWarning from '/snippets/prefab-pin-warning.mdx'
|
||||
import { PrefabDemoFrame } from '/snippets/prefab-demo-frame.mdx'
|
||||
|
||||
<VersionBadge version="3.2.0" />
|
||||
|
||||
<PrefabPinWarning />
|
||||
|
||||
<PrefabDemoFrame demo="contacts" height="650px" title="Contacts app demo" />
|
||||
|
||||
Search a list, fill out a form, click save, the list updates. That pattern — UI that reads and writes data on the server — needs two things: backend tools that actually do the work, and a way to call them from the UI. `FastMCPApp` handles the wiring.
|
||||
|
||||
You'll build up to the contacts app above by the end of this page. Let's start with something smaller.
|
||||
|
||||
## A minimal interactive app
|
||||
|
||||
The smallest interactive app: a form that saves a note, and a list that updates when the user submits.
|
||||
|
||||
```python
|
||||
from prefab_ui.actions import SetState, ShowToast
|
||||
from prefab_ui.actions.mcp import CallTool
|
||||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import (
|
||||
Badge, Button, Column, ForEach, Form, Heading,
|
||||
Input, Row, Separator, Text,
|
||||
)
|
||||
from prefab_ui.rx import RESULT
|
||||
from fastmcp import FastMCP, FastMCPApp
|
||||
|
||||
app = FastMCPApp("Notes")
|
||||
notes_db: list[dict] = []
|
||||
|
||||
|
||||
@app.tool()
|
||||
def add_note(title: str, body: str) -> list[dict]:
|
||||
"""Save a note and return all notes."""
|
||||
notes_db.append({"title": title, "body": body})
|
||||
return list(notes_db)
|
||||
|
||||
|
||||
@app.ui()
|
||||
def notes_app() -> PrefabApp:
|
||||
"""Open the notes app."""
|
||||
with Column(gap=6, css_class="p-6") as view:
|
||||
Heading("Notes")
|
||||
|
||||
with ForEach("notes") as note:
|
||||
with Row(gap=2, align="center"):
|
||||
Text(note.title, css_class="font-semibold")
|
||||
Badge(note.body)
|
||||
|
||||
Separator()
|
||||
|
||||
with Form(
|
||||
on_submit=CallTool(
|
||||
"add_note",
|
||||
on_success=[
|
||||
SetState("notes", RESULT),
|
||||
ShowToast("Note saved!", variant="success"),
|
||||
],
|
||||
on_error=ShowToast("Failed to save", variant="error"),
|
||||
)
|
||||
):
|
||||
Input(name="title", label="Title", required=True)
|
||||
Input(name="body", label="Body", required=True)
|
||||
Button("Add Note")
|
||||
|
||||
return PrefabApp(view=view, state={"notes": list(notes_db)})
|
||||
|
||||
|
||||
mcp = FastMCP("Notes Server", providers=[app])
|
||||
```
|
||||
|
||||
The model sees one tool: `notes_app`. Calling it opens the UI. When the user submits the form, `CallTool("add_note")` fires, the server saves the note, returns the updated list, and `SetState("notes", RESULT)` writes that list back into state. `ForEach("notes")` re-renders. The model never sees `add_note` — it's UI-only.
|
||||
|
||||
## Why not just `@mcp.tool(app=True)`?
|
||||
|
||||
A fair question. Any [Interactive Tool](/apps/prefab) can call a server tool — there's nothing stopping you from putting `CallTool("add_note")` inside a regular `@mcp.tool(app=True)`. It works for one or two tools. Things get harder once the app grows:
|
||||
|
||||
- Which tools should the model see, and which are UI-only?
|
||||
- What happens to `CallTool("add_note")` when you mount this server under a namespace and the tool becomes `notes_add_note`?
|
||||
- How do you keep it all wired correctly as you compose servers?
|
||||
|
||||
`FastMCPApp` owns these concerns. Entry points register as model-visible, backend tools register as UI-only, and hosts act on those declarations to decide what the model sees.
|
||||
|
||||
Composition is handled by never writing the name down. `CallTool` takes a function reference, and FastMCP resolves it when the UI is serialized — to whatever that tool is actually called by then. Mount the server under a namespace and the button calls `notes_add_note`; put a gateway in front and it calls whatever the gateway lists. Since you never wrote a name, renaming cannot break it. [The architecture page](/apps/architecture) covers how that resolution works.
|
||||
|
||||
The one rule that comes with this: **an app name must be unique within a server.** Composing the same app twice breaks its UI — two copies of `FastMCPApp("notes")` are indistinguishable no matter what namespaces you mount them under, so FastMCP declines to bind rather than picking one. Name apps for what they serve: `FastMCPApp("notes-acme")` and `FastMCPApp("notes-globex")`. [The architecture page](/apps/architecture) explains why identity works this way.
|
||||
|
||||
The rest of this page covers each piece in turn.
|
||||
|
||||
## `@app.ui()` — entry points
|
||||
|
||||
Entry points are what the model sees. They return a `PrefabApp` and default to `visibility=["model"]`, showing up in the LLM tool list but not callable from within the UI.
|
||||
|
||||
```python
|
||||
@app.ui()
|
||||
def dashboard() -> PrefabApp:
|
||||
"""The model calls this to open the dashboard."""
|
||||
with Column(gap=4, css_class="p-6") as view:
|
||||
Heading("Dashboard")
|
||||
...
|
||||
return PrefabApp(view=view)
|
||||
```
|
||||
|
||||
`@app.ui()` supports the same options as `@mcp.tool`: `name`, `description`, `title`, `tags`, `icons`, `auth`, and `timeout`.
|
||||
|
||||
## `@app.tool()` — backend tools
|
||||
|
||||
Backend tools do the work. By default they're visible only to the UI (`visibility=["app"]`), not the model.
|
||||
|
||||
```python
|
||||
@app.tool()
|
||||
def save_contact(name: str, email: str) -> list[dict]:
|
||||
"""Save a contact and return the updated list."""
|
||||
db.append({"name": name, "email": email})
|
||||
return list(db)
|
||||
```
|
||||
|
||||
If you want a tool callable by both the model and the UI, pass `model=True`:
|
||||
|
||||
```python
|
||||
@app.tool(model=True)
|
||||
def list_contacts() -> list[dict]:
|
||||
"""Both the model and the UI can call this."""
|
||||
return list(db)
|
||||
```
|
||||
|
||||
Backend tools support `name`, `description`, `auth`, and `timeout`.
|
||||
|
||||
## `CallTool` — UI → backend
|
||||
|
||||
`CallTool` is how the UI invokes a backend tool. Pass the tool's name (or a direct function reference):
|
||||
|
||||
```python
|
||||
from prefab_ui.actions.mcp import CallTool
|
||||
|
||||
CallTool("save_contact", arguments={"name": "Alice", "email": "alice@example.com"})
|
||||
|
||||
# Or a function reference — resolves to a stable global key
|
||||
CallTool(save_contact, arguments={...})
|
||||
```
|
||||
|
||||
Arguments can reference state with `Rx`:
|
||||
|
||||
```python
|
||||
from prefab_ui.rx import STATE
|
||||
|
||||
CallTool("search", arguments={"query": STATE.search_term})
|
||||
```
|
||||
|
||||
### Handling results
|
||||
|
||||
Server calls are async. Use `on_success` and `on_error` callbacks:
|
||||
|
||||
```python
|
||||
from prefab_ui.actions import SetState, ShowToast
|
||||
from prefab_ui.rx import RESULT
|
||||
|
||||
CallTool(
|
||||
"save_contact",
|
||||
on_success=[
|
||||
SetState("contacts", RESULT),
|
||||
ShowToast("Saved!", variant="success"),
|
||||
],
|
||||
on_error=ShowToast("Something went wrong", variant="error"),
|
||||
)
|
||||
```
|
||||
|
||||
`RESULT` is a reactive reference to the tool's return value, available inside `on_success`. `ERROR` (from `prefab_ui.rx`) is the counterpart inside `on_error`. Callbacks can be a single action or a list; they execute in order and short-circuit on error.
|
||||
|
||||
### `result_key` shorthand
|
||||
|
||||
When a tool's return value should replace a state key, use `result_key`:
|
||||
|
||||
```python
|
||||
CallTool("list_contacts", result_key="contacts")
|
||||
|
||||
# same as:
|
||||
CallTool("list_contacts", on_success=SetState("contacts", RESULT))
|
||||
```
|
||||
|
||||
## Actions
|
||||
|
||||
`CallTool` is one of several actions. Actions attach to handlers like `on_click`, `on_submit`, and `on_change`.
|
||||
|
||||
Client-side actions run instantly in the browser, no server round-trip:
|
||||
|
||||
```python
|
||||
from prefab_ui.actions import SetState, ToggleState, AppendState, PopState, ShowToast
|
||||
|
||||
SetState("count", 42)
|
||||
ToggleState("expanded")
|
||||
AppendState("items", {"name": "New Item"})
|
||||
PopState("items", 0)
|
||||
ShowToast("Done!", variant="success")
|
||||
```
|
||||
|
||||
Pass a list to chain actions:
|
||||
|
||||
```python
|
||||
Button(
|
||||
"Reset",
|
||||
on_click=[
|
||||
SetState("query", ""),
|
||||
SetState("results", []),
|
||||
ShowToast("Cleared"),
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
### Loading states
|
||||
|
||||
A common pattern: disable a button and show a spinner while a call is in flight.
|
||||
|
||||
```python
|
||||
from prefab_ui.rx import Rx
|
||||
|
||||
saving = Rx("saving")
|
||||
|
||||
Button(
|
||||
saving.then("Saving...", "Save"),
|
||||
disabled=saving,
|
||||
on_click=[
|
||||
SetState("saving", True),
|
||||
CallTool(
|
||||
"save_data",
|
||||
on_success=[
|
||||
SetState("saving", False),
|
||||
SetState("result", RESULT),
|
||||
ShowToast("Saved!", variant="success"),
|
||||
],
|
||||
on_error=[
|
||||
SetState("saving", False),
|
||||
ShowToast("Failed", variant="error"),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
# PrefabApp(view=view, state={"saving": False, ...})
|
||||
```
|
||||
|
||||
## Forms
|
||||
|
||||
Forms collect input and submit it to a tool. When submitted, named input values become the tool's arguments.
|
||||
|
||||
### Manual forms
|
||||
|
||||
```python
|
||||
from prefab_ui.components import Form, Input, Select, SelectOption, Textarea, Button
|
||||
|
||||
with Form(
|
||||
on_submit=CallTool(
|
||||
"create_ticket",
|
||||
on_success=ShowToast("Ticket created!", variant="success"),
|
||||
)
|
||||
):
|
||||
Input(name="title", label="Title", required=True)
|
||||
with Select(name="priority", label="Priority"):
|
||||
SelectOption("Low", value="low")
|
||||
SelectOption("Medium", value="medium")
|
||||
SelectOption("High", value="high")
|
||||
Textarea(name="description", label="Description")
|
||||
Button("Create Ticket")
|
||||
```
|
||||
|
||||
On submit, `CallTool` receives `{"title": ..., "priority": ..., "description": ...}`.
|
||||
|
||||
### Forms from Pydantic models
|
||||
|
||||
For structured input, `Form.from_model()` generates the whole form — inputs, labels, validation:
|
||||
|
||||
```python
|
||||
from typing import Literal
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class BugReport(BaseModel):
|
||||
title: str = Field(title="Bug Title")
|
||||
severity: Literal["low", "medium", "high", "critical"] = Field(
|
||||
title="Severity", default="medium"
|
||||
)
|
||||
description: str = Field(title="Description")
|
||||
|
||||
|
||||
@app.ui()
|
||||
def report_bug() -> PrefabApp:
|
||||
with Column(gap=4, css_class="p-6") as view:
|
||||
Heading("Report a Bug")
|
||||
Form.from_model(
|
||||
BugReport,
|
||||
on_submit=CallTool(
|
||||
"create_bug",
|
||||
on_success=ShowToast("Bug filed!", variant="success"),
|
||||
),
|
||||
)
|
||||
return PrefabApp(view=view)
|
||||
|
||||
|
||||
@app.tool()
|
||||
def create_bug(data: BugReport) -> str:
|
||||
return f"Created: {data.title}"
|
||||
```
|
||||
|
||||
`str` becomes a text input, `Literal` becomes a select, `bool` becomes a checkbox. Field titles and defaults are respected.
|
||||
|
||||
## Composition and namespacing
|
||||
|
||||
The reason `FastMCPApp` exists — and why you'd pick it over plain `@mcp.tool(app=True)` with string-based `CallTool` — is composition safety.
|
||||
|
||||
When you mount a server under a namespace, tool names get prefixed:
|
||||
|
||||
```python
|
||||
platform = FastMCP("Platform")
|
||||
platform.mount("contacts", contacts_server)
|
||||
|
||||
# "save_contact" becomes "contacts_save_contact"
|
||||
```
|
||||
|
||||
`CallTool("save_contact")` would now be broken. But `CallTool(save_contact)` with a function reference resolves to a globally stable identifier that bypasses the namespace. Your app works the same whether standalone or mounted.
|
||||
|
||||
### Mounting
|
||||
|
||||
`FastMCPApp` is a Provider. Add it to a server with `providers=` or `add_provider`:
|
||||
|
||||
```python
|
||||
mcp = FastMCP("Platform", providers=[app])
|
||||
|
||||
# or
|
||||
mcp = FastMCP("Platform")
|
||||
mcp.add_provider(app)
|
||||
```
|
||||
|
||||
Multiple apps can coexist; each gets its own global keys, so there's no collision even if two apps have a tool named `save`.
|
||||
|
||||
```python
|
||||
mcp = FastMCP("Platform", providers=[contacts_app, inventory_app, billing_app])
|
||||
```
|
||||
|
||||
### Running standalone
|
||||
|
||||
For development, `FastMCPApp` has a `run()` shortcut that wraps itself in a temporary `FastMCP` server:
|
||||
|
||||
```python
|
||||
app = FastMCPApp("Contacts")
|
||||
# ... register tools ...
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run()
|
||||
```
|
||||
|
||||
## A full example: contact manager
|
||||
|
||||
This brings everything together — entry point, backend tools, Pydantic form, manual form, state, actions, and multi-visibility.
|
||||
|
||||
```python expandable
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from prefab_ui.actions import SetState, ShowToast
|
||||
from prefab_ui.actions.mcp import CallTool
|
||||
from prefab_ui.app import PrefabApp
|
||||
from prefab_ui.components import (
|
||||
Badge, Button, Column, ForEach, Form,
|
||||
Heading, Input, Muted, Row, Separator, Text,
|
||||
)
|
||||
from prefab_ui.rx import RESULT, Rx
|
||||
from pydantic import BaseModel, Field
|
||||
from fastmcp import FastMCP, FastMCPApp
|
||||
|
||||
contacts_db: list[dict] = [
|
||||
{"name": "Arthur Dent", "email": "arthur@earth.com", "category": "Customer"},
|
||||
{"name": "Ford Prefect", "email": "ford@betelgeuse.org", "category": "Partner"},
|
||||
]
|
||||
|
||||
|
||||
class ContactModel(BaseModel):
|
||||
name: str = Field(title="Full Name", min_length=1)
|
||||
email: str = Field(title="Email")
|
||||
category: Literal["Customer", "Vendor", "Partner", "Other"] = "Other"
|
||||
|
||||
|
||||
app = FastMCPApp("Contacts")
|
||||
|
||||
|
||||
@app.tool()
|
||||
def save_contact(data: ContactModel) -> list[dict]:
|
||||
"""Save a new contact and return the updated list."""
|
||||
contacts_db.append(data.model_dump())
|
||||
return list(contacts_db)
|
||||
|
||||
|
||||
@app.tool()
|
||||
def search_contacts(query: str) -> list[dict]:
|
||||
"""Filter contacts by name or email."""
|
||||
q = query.lower()
|
||||
return [
|
||||
c for c in contacts_db
|
||||
if q in c["name"].lower() or q in c["email"].lower()
|
||||
]
|
||||
|
||||
|
||||
@app.tool(model=True)
|
||||
def list_contacts() -> list[dict]:
|
||||
"""Return all contacts. Visible to both the model and the UI."""
|
||||
return list(contacts_db)
|
||||
|
||||
|
||||
@app.ui()
|
||||
def contact_manager() -> PrefabApp:
|
||||
"""Open the contact manager."""
|
||||
with Column(gap=6, css_class="p-6") as view:
|
||||
Heading("Contacts")
|
||||
|
||||
with ForEach("contacts") as contact:
|
||||
with Row(gap=2, align="center"):
|
||||
Text(contact.name, css_class="font-medium")
|
||||
Muted(contact.email)
|
||||
Badge(contact.category)
|
||||
|
||||
Separator()
|
||||
|
||||
Heading("Add Contact", level=3)
|
||||
Form.from_model(
|
||||
ContactModel,
|
||||
on_submit=CallTool(
|
||||
"save_contact",
|
||||
on_success=[
|
||||
SetState("contacts", RESULT),
|
||||
ShowToast("Contact saved!", variant="success"),
|
||||
],
|
||||
on_error=ShowToast("Failed to save", variant="error"),
|
||||
),
|
||||
)
|
||||
|
||||
Separator()
|
||||
|
||||
Heading("Search", level=3)
|
||||
with Form(
|
||||
on_submit=CallTool(
|
||||
"search_contacts",
|
||||
arguments={"query": Rx("query")},
|
||||
on_success=SetState("contacts", RESULT),
|
||||
)
|
||||
):
|
||||
Input(name="query", placeholder="Search by name or email...")
|
||||
Button("Search")
|
||||
|
||||
return PrefabApp(view=view, state={"contacts": list(contacts_db)})
|
||||
|
||||
|
||||
mcp = FastMCP("Contacts Server", providers=[app])
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
```
|
||||
|
||||
Also available as a runnable server at `examples/apps/contacts/contacts_server.py`.
|
||||
|
||||
## Next steps
|
||||
|
||||
- **[Interactive Tools](/apps/prefab)** — the building blocks: charts, tables, dashboards, reactive state
|
||||
- **[Examples](/apps/examples)** — complete working servers
|
||||
- **[Development](/apps/development)** — preview and test app tools locally
|
||||
- **[Prefab UI docs](https://prefab.prefect.io)** — full component reference
|
||||
134
docs/apps/generative.mdx
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
---
|
||||
title: Generative UI
|
||||
sidebarTitle: Generative UI
|
||||
description: Let the LLM build custom Prefab UIs on the fly.
|
||||
icon: wand-magic-sparkles
|
||||
tag: NEW
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="3.2.0" />
|
||||
|
||||
<video src="/apps/images/generative-ui.mp4" autoPlay loop muted playsInline style={{width:"100%", borderRadius:"8px", marginBottom:"1rem"}} />
|
||||
|
||||
With Generative UI, the LLM writes the UI code at runtime. Instead of calling a pre-built tool with a fixed shape, the model writes Prefab Python tailored to the current data and request. The user watches the UI stream in as the model generates it.
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.apps.generative import GenerativeUI
|
||||
|
||||
mcp = FastMCP("Prefab Studio")
|
||||
mcp.add_provider(GenerativeUI())
|
||||
```
|
||||
|
||||
One provider registers three things:
|
||||
|
||||
- **`generate_prefab_ui`** — a tool that accepts Python code, executes it in a Pyodide sandbox, and renders the result as a Prefab app
|
||||
- **`search_prefab_components`** — a tool the LLM uses to discover what components are available
|
||||
- **The streaming renderer** — a `ui://` resource with browser-side Pyodide that progressively renders partial code as the LLM generates it
|
||||
|
||||
## How it works
|
||||
|
||||
When the LLM calls `generate_prefab_ui`, it writes Prefab Python code into the `code` argument. The MCP Apps protocol creates the renderer iframe in parallel with the tool call, so the app is already running by the time partial arguments start flowing.
|
||||
|
||||
As the LLM generates each token:
|
||||
|
||||
1. The host forwards partial arguments to the app via `ontoolinputpartial`
|
||||
2. The renderer extracts the growing `code` string
|
||||
3. Browser-side Pyodide executes whatever compiles successfully
|
||||
4. The user sees components appear as they're written
|
||||
|
||||
When the LLM finishes, the server runs the complete code in a server-side Pyodide sandbox for validation, and the renderer swaps the streaming preview for the final server-validated result.
|
||||
|
||||
## What the LLM writes
|
||||
|
||||
The tool description includes examples that teach the model the Prefab patterns. A typical generation looks like:
|
||||
|
||||
```python
|
||||
from prefab_ui.components import Column, Row, Heading, Text, Badge, Card, CardContent
|
||||
from prefab_ui.components.charts import BarChart, ChartSeries
|
||||
from prefab_ui.app import PrefabApp
|
||||
|
||||
with PrefabApp() as app:
|
||||
with Column(gap=6, css_class="p-6"):
|
||||
Heading("Q3 Revenue Report")
|
||||
|
||||
BarChart(
|
||||
data=[
|
||||
{"month": "Jul", "revenue": 42000},
|
||||
{"month": "Aug", "revenue": 51000},
|
||||
{"month": "Sep", "revenue": 63000},
|
||||
],
|
||||
series=[ChartSeries(data_key="revenue", label="Revenue")],
|
||||
x_axis="month",
|
||||
)
|
||||
|
||||
with Row(gap=4):
|
||||
with Card():
|
||||
with CardContent():
|
||||
Text("Total", css_class="text-sm text-muted-foreground")
|
||||
Heading("$156,000")
|
||||
with Card():
|
||||
with CardContent():
|
||||
Text("Growth", css_class="text-sm text-muted-foreground")
|
||||
Badge("+18%", variant="success")
|
||||
```
|
||||
|
||||
The model writes real Python — loops, f-strings, computation, helper functions. Prefab gives it charts, tables, forms, cards, badges, and layout primitives to compose.
|
||||
|
||||
## The component search tool
|
||||
|
||||
Before writing code, the LLM can call `search_prefab_components` to discover what's available:
|
||||
|
||||
```
|
||||
search_prefab_components("Chart")
|
||||
→ 7 components matching 'Chart':
|
||||
AreaChart — from prefab_ui.components.charts import AreaChart
|
||||
BarChart — from prefab_ui.components.charts import BarChart
|
||||
...
|
||||
```
|
||||
|
||||
Passing `detail=True` returns full field descriptions and docstrings. The search tool introspects Prefab classes at runtime, so it's always up to date with the installed version.
|
||||
|
||||
## Passing data
|
||||
|
||||
The `generate_prefab_ui` tool accepts a `data` parameter. Values become global variables in the sandbox:
|
||||
|
||||
```python
|
||||
# The LLM can reference 'sales_data' directly in its code
|
||||
result = await generate_prefab_ui(
|
||||
code="...",
|
||||
data={"sales_data": [{"month": "Jan", "revenue": 42000}, ...]}
|
||||
)
|
||||
```
|
||||
|
||||
This lets the model use data from earlier in the conversation to build visualizations.
|
||||
|
||||
## Configuration
|
||||
|
||||
`GenerativeUI` takes options for customizing tool names:
|
||||
|
||||
```python
|
||||
GenerativeUI(
|
||||
tool_name="generate_prefab_ui", # default
|
||||
components_tool_name="search_prefab_components", # default
|
||||
include_components_tool=True, # default
|
||||
)
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
Generative UI needs `fastmcp[apps]`, which pulls in `prefab-ui`. The server-side Pyodide sandbox (for final validation) requires Deno — it installs automatically on first use.
|
||||
|
||||
The streaming renderer loads Pyodide from CDN in the browser. The CSP is configured automatically by the provider — no manual setup.
|
||||
|
||||
## Sandbox limitations
|
||||
|
||||
The Pyodide sandbox includes the Python standard library and Prefab. External packages (NumPy, pandas, requests, etc.) are **not available** — the LLM's code must work with only built-in Python and Prefab. If the LLM imports something unavailable, the sandbox raises `ImportError`.
|
||||
|
||||
## Next steps
|
||||
|
||||
- **[Interactive Tools](/apps/prefab)** — the component building blocks the LLM will use
|
||||
- **[Prefab component reference](https://prefab.prefect.io/docs/components)** — full component library
|
||||
- **[Development](/apps/development)** — preview generative tools locally with `fastmcp dev apps`
|
||||
BIN
docs/apps/images/app-approval.png
Normal file
|
After Width: | Height: | Size: 571 KiB |
BIN
docs/apps/images/app-chart.png
Normal file
|
After Width: | Height: | Size: 6 KiB |
BIN
docs/apps/images/app-choice.png
Normal file
|
After Width: | Height: | Size: 536 KiB |
BIN
docs/apps/images/app-contacts.png
Normal file
|
After Width: | Height: | Size: 587 KiB |
BIN
docs/apps/images/app-example-map.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
BIN
docs/apps/images/app-example-quiz.png
Normal file
|
After Width: | Height: | Size: 586 KiB |
BIN
docs/apps/images/app-example-sales-dashboard.png
Normal file
|
After Width: | Height: | Size: 683 KiB |
BIN
docs/apps/images/app-example-system-dashboard.png
Normal file
|
After Width: | Height: | Size: 745 KiB |
BIN
docs/apps/images/app-file-upload.png
Normal file
|
After Width: | Height: | Size: 555 KiB |
BIN
docs/apps/images/app-form.png
Normal file
|
After Width: | Height: | Size: 580 KiB |
BIN
docs/apps/images/app-greet.png
Normal file
|
After Width: | Height: | Size: 267 KiB |
BIN
docs/apps/images/app-overview.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
BIN
docs/apps/images/app-quickstart-dev-2.png
Normal file
|
After Width: | Height: | Size: 586 KiB |
BIN
docs/apps/images/app-quickstart-dev.png
Normal file
|
After Width: | Height: | Size: 652 KiB |
BIN
docs/apps/images/app-quickstart.png
Normal file
|
After Width: | Height: | Size: 639 KiB |