File size: 94,732 Bytes
48f7143
ef5e55f
4f16c08
 
a853a78
5f2c09d
cdb0274
da4845b
0feb19f
48f7143
 
bd66e60
48f7143
 
fa216f2
27eb2df
edc0d82
d817b84
48f7143
 
dc0a2a3
ac3212f
48f7143
 
a5d87c5
48f7143
 
e3f57a4
48f7143
bacf327
3c4246c
48f7143
c2a9892
48f7143
 
 
 
 
428a20f
8ea5e71
48f7143
7bdb963
987be7e
48f7143
e085ebe
5338a1c
a277f25
6090024
48f7143
5ee8f66
0feb19f
 
341332a
3959209
59f2792
 
 
 
 
6fe9090
8ea5e71
927e044
48f7143
7974ade
bacf327
d817b84
7b7b417
7d7a6cb
4d56236
a8188bd
cca52df
ea8c89c
03a2687
ef5e55f
6da0e6b
3acddf3
fa6e614
8c5bdf2
 
 
 
 
 
 
 
ca8cdf5
 
 
48f7143
8c5bdf2
ef5e55f
 
ea8c89c
0fa02ae
ea8c89c
889090e
 
 
ef5e55f
bd66e60
d09d7f6
bd66e60
 
 
 
 
 
 
 
 
 
 
81e8514
d09d7f6
 
 
 
48f7143
6fe9090
48f7143
 
6fe9090
 
 
bd66e60
 
48f7143
 
 
 
 
 
 
 
 
 
196d446
 
3959209
8ea5e71
48f7143
e782013
4f16c08
e782013
 
 
48f7143
cb39c37
b45adb7
85e9cfd
15b1769
bacf327
cb39c37
23dba76
 
957b451
cb39c37
 
 
927e044
 
 
 
 
 
 
 
 
 
 
 
 
 
48f7143
927e044
 
1175ac0
ea8c89c
 
125f50b
d817b84
7b7b417
7d7a6cb
4d56236
ea8c89c
 
927e044
bacf327
ea8c89c
 
85e9cfd
927e044
85e9cfd
 
 
927e044
ea8c89c
4757dcb
bd66e60
 
d4465eb
bd66e60
d4465eb
 
6fe9090
48f7143
809d112
48f7143
81e8514
48f7143
7bdb963
3959209
 
 
 
 
 
 
 
4c1f058
15b1769
 
a853a78
4757dcb
a853a78
4c1f058
cca52df
 
 
ac3212f
 
48f7143
 
5f2c09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
927e044
957b451
 
 
 
 
 
927e044
 
 
 
 
 
 
 
 
 
 
 
48f7143
81e8514
 
 
927e044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
905120e
 
 
 
 
 
927e044
 
 
 
 
60b7afa
 
905120e
 
 
 
 
 
 
60b7afa
 
48f7143
 
 
 
 
 
 
 
1807d5c
 
 
 
9f94e73
4c1f058
0fa02ae
2f3af13
4c1f058
9f94e73
3acddf3
d4adea4
48f7143
4c1f058
48f7143
3acddf3
 
0fa02ae
48f7143
 
 
2f3af13
 
 
 
0fa02ae
2f3af13
 
 
 
 
da4845b
 
3acddf3
9f94e73
4c1f058
0fa02ae
2f3af13
4c1f058
9f94e73
3acddf3
 
 
4c1f058
3acddf3
27eb2df
2f3af13
 
 
 
 
 
 
 
48f7143
 
 
0feb19f
 
1175ac0
0feb19f
1175ac0
 
0feb19f
48f7143
ac3212f
 
 
 
 
 
 
 
 
 
 
8ea5e71
ac3212f
 
81e8514
 
80723cc
81e8514
92cf7e6
 
 
 
 
 
81e8514
c5b3684
d37c5e4
81e8514
a277f25
 
 
 
 
 
81e8514
 
d37c5e4
81e8514
a277f25
bb7d65e
a277f25
 
 
 
 
81e8514
 
 
 
80723cc
c5b3684
a277f25
 
 
 
 
 
7bdb963
 
 
 
 
 
e42c7fe
 
 
 
7bdb963
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb7d65e
 
7bdb963
 
 
bb7d65e
7bdb963
 
 
a853a78
7bdb963
154abca
7bdb963
 
a853a78
7bdb963
 
 
 
 
a853a78
7bdb963
 
 
125f50b
 
 
 
 
 
 
 
 
 
 
d817b84
 
 
 
 
 
 
7b7b417
 
 
 
 
 
14641be
7d7a6cb
 
 
 
 
 
dc0782c
4d56236
 
 
 
 
 
7b7b417
125f50b
 
 
 
 
 
d817b84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d7a6cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125f50b
4d56236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125f50b
7b7b417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81e8514
e97c2b8
 
6fe9090
816878f
957b451
 
 
 
 
 
 
e97c2b8
816878f
81e8514
 
 
 
ac3212f
e97c2b8
 
54bdf2c
09cabfa
ac3212f
54bdf2c
 
ac3212f
54bdf2c
ac3212f
 
 
6fe9090
ac3212f
 
e97c2b8
ac3212f
 
 
 
 
1175ac0
ac3212f
e97c2b8
 
0feb19f
e423e66
 
6fe9090
d37c5e4
e423e66
957b451
 
 
 
 
e423e66
 
d37c5e4
0feb19f
 
 
 
 
ac3212f
e423e66
ac3212f
e423e66
09cabfa
e423e66
 
 
ac3212f
e423e66
 
ac3212f
 
6fe9090
ac3212f
 
 
 
 
 
 
 
 
 
e423e66
 
0feb19f
e423e66
 
6fe9090
d37c5e4
e423e66
957b451
 
 
 
e423e66
 
 
d37c5e4
0feb19f
e423e66
 
0feb19f
 
ac3212f
e423e66
ac3212f
e423e66
09cabfa
e423e66
 
 
ac3212f
e423e66
 
ac3212f
 
6fe9090
ac3212f
 
 
 
 
e423e66
ac3212f
 
 
 
e423e66
 
81e8514
e423e66
 
6fe9090
80723cc
957b451
 
 
 
 
 
 
e423e66
80723cc
81e8514
 
 
 
 
ac3212f
e423e66
80723cc
e423e66
09cabfa
e423e66
 
 
ac3212f
e423e66
 
ac3212f
 
6fe9090
ac3212f
 
80723cc
ac3212f
 
 
 
 
 
 
e423e66
 
81e8514
 
7974ade
a277f25
 
 
 
85e9cfd
 
 
 
 
 
 
 
e97c2b8
81e8514
6fe9090
a277f25
7974ade
 
a277f25
 
 
 
 
7974ade
ac3212f
816878f
ac3212f
 
 
e97c2b8
7974ade
816878f
 
 
 
 
 
ac3212f
 
bacf327
e97c2b8
ac3212f
 
 
 
 
 
 
0feb19f
a277f25
 
 
 
 
e97c2b8
a277f25
6fe9090
a277f25
d37c5e4
a277f25
 
 
 
 
 
 
d37c5e4
ac3212f
d37c5e4
ac3212f
 
 
e97c2b8
ac3212f
d37c5e4
 
 
 
 
 
 
 
 
 
 
ac3212f
 
 
 
 
 
 
 
e97c2b8
ac3212f
 
 
 
 
 
 
81e8514
 
a277f25
 
 
 
 
 
e97c2b8
a277f25
6fe9090
a277f25
80723cc
a277f25
 
 
 
 
 
 
80723cc
 
ac3212f
 
80723cc
ac3212f
 
 
e97c2b8
ac3212f
80723cc
 
 
 
 
 
ac3212f
 
 
e97c2b8
ac3212f
 
 
 
 
 
 
a9a1a98
48f7143
 
 
 
 
 
d809841
a9a1a98
 
 
48f7143
cba81f4
48f7143
6fe9090
 
 
 
 
 
 
 
 
a9a1a98
 
c44bbc1
 
 
 
 
 
 
 
 
 
 
6fe9090
 
 
 
 
 
 
 
 
bacf327
 
 
 
 
 
 
 
 
 
5ee8f66
 
 
 
 
 
226fdf7
5ee8f66
 
aa46c09
5ee8f66
 
0907e77
788b7e2
5ee8f66
 
 
 
 
 
 
 
226fdf7
5ee8f66
 
aa46c09
5ee8f66
 
0907e77
788b7e2
5ee8f66
 
48f7143
316c336
26ff0e9
 
316c336
226fdf7
316c336
 
aa46c09
c2a9892
c5ee465
0907e77
788b7e2
5ee8f66
48f7143
 
 
 
 
 
26ff0e9
 
224caf9
26ff0e9
 
 
 
48f7143
26ff0e9
55471df
48f7143
316c336
c903d7b
bb7d65e
26ff0e9
0907e77
55471df
48f7143
bb7d65e
 
 
26ff0e9
48f7143
 
 
bb7d65e
224caf9
26ff0e9
48f7143
 
26ff0e9
 
48f7143
0feb19f
26ff0e9
 
 
 
 
 
bb7d65e
26ff0e9
a853a78
 
48f7143
ec6bd43
 
 
 
 
 
 
 
 
 
 
 
26ff0e9
ec6bd43
26ff0e9
 
 
 
 
5ee8f66
a853a78
c2a9892
26ff0e9
226fdf7
c2a9892
 
c903d7b
c2a9892
c5ee465
0907e77
4757dcb
788b7e2
c2a9892
a853a78
5ee8f66
48f7143
26ff0e9
 
 
 
 
 
 
 
 
224caf9
26ff0e9
 
 
 
 
 
 
 
 
 
226fdf7
26ff0e9
 
c903d7b
26ff0e9
 
0907e77
788b7e2
26ff0e9
48f7143
a9a1a98
48f7143
 
 
 
0feb19f
a9a1a98
 
 
09cabfa
48f7143
6fe9090
 
 
 
 
 
 
 
 
a9a1a98
 
 
a853a78
 
 
 
a9a1a98
 
 
a853a78
a52441c
a853a78
6fe9090
 
 
 
 
 
 
 
 
a9a1a98
 
f1f59fd
0feb19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a853a78
905120e
 
 
 
 
 
0feb19f
 
 
 
 
 
 
 
 
48f7143
 
 
 
 
226fdf7
48f7143
 
316c336
55471df
e3f57a4
0907e77
5ee8f66
48f7143
 
 
 
 
 
 
 
3d30e82
 
 
 
48f7143
 
 
 
 
 
 
 
316c336
55471df
e3f57a4
0907e77
48f7143
bb7d65e
 
 
48f7143
 
 
 
 
 
 
 
 
 
 
 
 
3d30e82
 
 
 
 
48f7143
 
 
 
bb7d65e
48f7143
e3f57a4
 
 
48f7143
ec6bd43
48f7143
 
 
 
 
5ee8f66
a853a78
 
8c95b71
ec6bd43
 
 
 
 
 
 
 
 
 
 
a853a78
 
 
 
 
 
 
0feb19f
a853a78
 
 
 
 
 
226fdf7
a853a78
 
 
55471df
e3f57a4
0907e77
a853a78
 
5ee8f66
a853a78
 
 
 
 
226fdf7
a853a78
 
 
55471df
e3f57a4
0907e77
a853a78
 
5ee8f66
a853a78
 
 
 
 
 
48f7143
 
a9a1a98
48f7143
 
 
 
a9a1a98
 
 
48f7143
a853a78
48f7143
6fe9090
 
 
 
 
 
 
 
 
a9a1a98
 
5ee8f66
 
 
 
 
 
226fdf7
5ee8f66
 
8604c71
0907e77
5ee8f66
 
 
 
 
 
 
 
226fdf7
5ee8f66
 
8604c71
0907e77
5ee8f66
 
48f7143
316c336
4f92aa9
 
316c336
226fdf7
316c336
 
8604c71
0907e77
5ee8f66
48f7143
 
3d30e82
 
 
 
4f92aa9
 
52aa5a1
4f92aa9
 
 
 
48f7143
4f92aa9
55471df
48f7143
316c336
55471df
0907e77
48f7143
bb7d65e
 
 
4f92aa9
48f7143
 
 
 
 
 
 
 
 
52aa5a1
3d30e82
 
 
 
 
 
 
 
 
 
4f92aa9
 
48f7143
 
 
 
 
 
 
 
 
 
 
 
 
4f92aa9
 
 
 
 
 
 
bb7d65e
48f7143
ec6bd43
 
 
 
 
 
 
 
 
 
 
 
 
4f92aa9
ec6bd43
4f92aa9
 
 
 
48f7143
4f92aa9
a853a78
 
4f92aa9
226fdf7
a853a78
 
8604c71
0907e77
a853a78
 
48f7143
5ee8f66
4f92aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226fdf7
4f92aa9
 
8604c71
0907e77
4f92aa9
48f7143
2f3af13
48f7143
2f3af13
 
 
a8188bd
 
 
2f3af13
 
48f7143
a506ee1
48f7143
 
 
a5d87c5
 
 
48f7143
 
da4845b
6e94ee5
2f3af13
0fa02ae
6e94ee5
 
 
d8a9a0b
d09d7f6
8ea5e71
8b24d16
6e94ee5
9302244
 
 
 
 
 
 
 
 
8b24d16
 
9302244
2f3af13
927e044
 
 
 
 
a506ee1
8b24d16
 
 
 
 
 
48f7143
2f3af13
 
 
 
 
 
 
 
 
a8188bd
 
 
 
 
 
2f3af13
731e83f
 
1b89739
731e83f
 
1b89739
731e83f
1b89739
731e83f
 
1b89739
731e83f
48f7143
a506ee1
 
 
 
2f3af13
48f7143
 
da4845b
 
 
 
 
 
d09d7f6
da4845b
 
ea8c89c
 
905120e
 
 
 
 
 
 
 
da4845b
 
 
 
 
 
 
 
 
d8a9a0b
 
 
 
8ea5e71
59f2792
1f22024
 
 
 
 
 
 
 
ea8c89c
905120e
 
 
 
 
 
 
154abca
 
927e044
 
7befcc3
927e044
987be7e
48f7143
 
987be7e
 
 
8ea5e71
59f2792
1f22024
 
 
 
 
 
 
ea8c89c
905120e
 
 
 
 
 
da4845b
 
 
 
 
8ea5e71
927e044
 
0fa02ae
59f2792
9302244
 
 
 
 
 
 
 
 
 
329333a
0fa02ae
da4845b
 
927e044
 
da4845b
7befcc3
4cd1f67
5d7caf0
 
 
4cd1f67
 
5d7caf0
 
 
4cd1f67
927e044
da4845b
 
 
 
 
927e044
 
7befcc3
927e044
da4845b
 
4c1f058
 
 
 
 
 
d8a9a0b
d09d7f6
4c1f058
ea8c89c
905120e
 
 
 
 
 
 
da4845b
0fa02ae
da4845b
 
 
 
 
4c1f058
 
81e8514
 
4f16c08
4d88236
cdb0274
 
81e8514
 
 
 
4d88236
d4465eb
 
 
 
 
 
 
4d88236
cdb0274
d4465eb
cdb0274
d4465eb
cdb0274
 
d4465eb
cdb0274
 
d4465eb
 
 
4d88236
 
 
 
d4465eb
 
 
 
 
 
 
 
 
 
 
 
 
4d88236
 
d4465eb
 
 
cdb0274
 
 
0feb19f
6d04c2c
d4465eb
4d88236
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
87b03f8
905120e
 
 
 
 
 
 
cdb0274
 
87b03f8
905120e
 
 
 
 
 
 
cdb0274
 
87b03f8
905120e
 
 
 
 
 
 
cdb0274
d4465eb
 
 
 
 
 
6d04c2c
d4465eb
816878f
d37c5e4
 
 
 
 
125f50b
816878f
 
 
 
81e8514
37a07a4
4f16c08
4d88236
37a07a4
 
 
 
a1ec1e3
 
 
 
 
 
 
 
 
4d88236
cdb0274
a1ec1e3
cdb0274
 
 
 
 
 
 
 
 
 
d4adea4
4d88236
 
 
d4adea4
cdb0274
4d88236
 
cdb0274
 
 
 
d4adea4
4d88236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
87b03f8
905120e
 
 
 
 
 
 
cdb0274
 
87b03f8
905120e
 
 
 
 
 
 
cdb0274
 
87b03f8
905120e
 
 
 
 
 
 
37a07a4
4d88236
81e8514
4d88236
8d16d26
09cabfa
d4adea4
4d88236
81e8514
4d88236
 
 
 
8d16d26
 
 
09cabfa
cdb0274
81e8514
4d88236
 
 
 
8d16d26
 
 
09cabfa
d4adea4
4d88236
81e8514
4d88236
8d16d26
09cabfa
4d88236
 
09cabfa
4d88236
09cabfa
7826473
dc0a2a3
 
0410d0d
 
 
8c5bdf2
 
 
451db43
e66010e
0410d0d
8c5bdf2
dc0a2a3
 
 
8c5bdf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc0a2a3
 
 
0410d0d
 
 
8c5bdf2
 
 
451db43
18ebe37
e66010e
0410d0d
8c5bdf2
dc0a2a3
 
 
51ea945
18ebe37
 
 
 
dc0a2a3
18ebe37
 
dc0a2a3
 
 
 
8c5bdf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc0a2a3
edc0d82
 
 
fd0c13f
 
 
 
 
 
 
 
 
 
edc0d82
 
 
 
bb7d65e
 
 
 
edc0d82
a60b771
fd0c13f
edc0d82
 
 
c7708b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edc0d82
c7708b2
 
 
 
 
 
 
edc0d82
c7708b2
edc0d82
81e8514
fa6e614
 
 
81e8514
 
 
feafdb6
905120e
 
 
 
 
 
48f7143
edc0d82
428a20f
cca52df
1175ac0
cca52df
1175ac0
 
cca52df
1175ac0
 
bb7d65e
 
 
1175ac0
bb7d65e
1175ac0
bb7d65e
 
1175ac0
cca52df
 
 
 
1175ac0
 
cca52df
23dba76
 
1175ac0
cca52df
23dba76
 
 
 
1175ac0
23dba76
1175ac0
428a20f
fa216f2
4af3969
4d88236
fa216f2
d37c5e4
cdb0274
 
b45adb7
 
 
cdb0274
 
 
 
 
 
 
 
 
 
bb7d65e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
 
 
 
 
 
 
b45adb7
cdb0274
b45adb7
927e044
cdb0274
b45adb7
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
b45adb7
 
 
 
cdb0274
b45adb7
 
 
 
cdb0274
 
 
 
 
b45adb7
cdb0274
 
 
 
bb7d65e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
 
 
 
 
 
 
b45adb7
927e044
cdb0274
b45adb7
 
 
 
 
cdb0274
b45adb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
b45adb7
 
 
 
cdb0274
 
b45adb7
 
 
cdb0274
 
 
 
 
 
 
 
 
 
bb7d65e
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
bb7d65e
cdb0274
 
 
 
 
 
 
b45adb7
 
 
927e044
b45adb7
 
 
 
 
 
 
 
 
 
 
 
 
cdb0274
b45adb7
cdb0274
b45adb7
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
"""FastMCP - A more ergonomic interface for MCP servers."""

from __future__ import annotations

import inspect
import json
import re
import warnings
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import (
    AbstractAsyncContextManager,
    AsyncExitStack,
    asynccontextmanager,
)
from dataclasses import dataclass
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, Literal, Optional, cast, overload

import anyio
import httpx
import mcp.types
import uvicorn
from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.server.lowlevel.server import LifespanResultT, NotificationOptions
from mcp.server.stdio import stdio_server
from mcp.types import (
    Annotations,
    AnyFunction,
    CallToolRequestParams,
    ContentBlock,
    GetPromptResult,
    ToolAnnotations,
)
from mcp.types import Prompt as MCPPrompt
from mcp.types import Resource as MCPResource
from mcp.types import ResourceTemplate as MCPResourceTemplate
from mcp.types import Tool as MCPTool
from pydantic import AnyUrl
from starlette.middleware import Middleware as ASGIMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Route

import fastmcp
import fastmcp.server
from fastmcp.exceptions import DisabledError, NotFoundError
from fastmcp.mcp_config import MCPConfig
from fastmcp.prompts import Prompt, PromptManager
from fastmcp.prompts.prompt import FunctionPrompt
from fastmcp.resources import Resource, ResourceManager
from fastmcp.resources.template import ResourceTemplate
from fastmcp.server.auth import AuthProvider
from fastmcp.server.auth.registry import get_registered_provider
from fastmcp.server.http import (
    StarletteWithLifespan,
    create_sse_app,
    create_streamable_http_app,
)
from fastmcp.server.low_level import LowLevelServer
from fastmcp.server.middleware import Middleware, MiddlewareContext
from fastmcp.settings import Settings
from fastmcp.tools import ToolManager
from fastmcp.tools.tool import FunctionTool, Tool, ToolResult
from fastmcp.tools.tool_transform import ToolTransformConfig
from fastmcp.policy import PolicyEngine
from fastmcp.reflexive import ReflexiveEngine
from fastmcp.ledger import ProvenanceLedger
from fastmcp.contracts import ContractEngine
from fastmcp.utilities.cli import log_server_banner
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import NotSet, NotSetT

if TYPE_CHECKING:
    from fastmcp.client import Client
    from fastmcp.client.transports import ClientTransport, ClientTransportT
    from fastmcp.experimental.server.openapi import FastMCPOpenAPI as FastMCPOpenAPINew
    from fastmcp.experimental.server.openapi.routing import (
        ComponentFn as OpenAPIComponentFnNew,
    )
    from fastmcp.experimental.server.openapi.routing import RouteMap as RouteMapNew
    from fastmcp.experimental.server.openapi.routing import (
        RouteMapFn as OpenAPIRouteMapFnNew,
    )
    from fastmcp.server.openapi import ComponentFn as OpenAPIComponentFn
    from fastmcp.server.openapi import FastMCPOpenAPI, RouteMap
    from fastmcp.server.openapi import RouteMapFn as OpenAPIRouteMapFn
    from fastmcp.server.proxy import FastMCPProxy

logger = get_logger(__name__)

DuplicateBehavior = Literal["warn", "error", "replace", "ignore"]
Transport = Literal["stdio", "http", "sse", "streamable-http"]

# Compiled URI parsing regex to split a URI into protocol and path components
URI_PATTERN = re.compile(r"^([^:]+://)(.*?)$")


@asynccontextmanager
async def default_lifespan(server: FastMCP[LifespanResultT]) -> AsyncIterator[Any]:
    """Default lifespan context manager that does nothing.

    Args:
        server: The server instance this lifespan is managing

    Returns:
        An empty context object
    """
    yield {}


def _lifespan_wrapper(
    app: FastMCP[LifespanResultT],
    lifespan: Callable[
        [FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]
    ],
) -> Callable[
    [LowLevelServer[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]
]:
    @asynccontextmanager
    async def wrap(
        s: LowLevelServer[LifespanResultT],
    ) -> AsyncIterator[LifespanResultT]:
        async with AsyncExitStack() as stack:
            context = await stack.enter_async_context(lifespan(app))
            yield context

    return wrap


class FastMCP(Generic[LifespanResultT]):
    def __init__(
        self,
        name: str | None = None,
        instructions: str | None = None,
        *,
        version: str | None = None,
        auth: AuthProvider | None | NotSetT = NotSet,
        middleware: list[Middleware] | None = None,
        lifespan: (
            Callable[
                [FastMCP[LifespanResultT]],
                AbstractAsyncContextManager[LifespanResultT],
            ]
            | None
        ) = None,
        dependencies: list[str] | None = None,
        resource_prefix_format: Literal["protocol", "path"] | None = None,
        mask_error_details: bool | None = None,
        tools: list[Tool | Callable[..., Any]] | None = None,
        tool_transformations: dict[str, ToolTransformConfig] | None = None,
        tool_serializer: Callable[[Any], str] | None = None,
        include_tags: set[str] | None = None,
        exclude_tags: set[str] | None = None,
        include_fastmcp_meta: bool | None = None,
        on_duplicate_tools: DuplicateBehavior | None = None,
        on_duplicate_resources: DuplicateBehavior | None = None,
        on_duplicate_prompts: DuplicateBehavior | None = None,
        # ---
        # ---
        # --- The following arguments are DEPRECATED ---
        # ---
        # ---
        log_level: str | None = None,
        debug: bool | None = None,
        host: str | None = None,
        port: int | None = None,
        sse_path: str | None = None,
        message_path: str | None = None,
        streamable_http_path: str | None = None,
        json_response: bool | None = None,
        stateless_http: bool | None = None,
    ):
        self.resource_prefix_format: Literal["protocol", "path"] = (
            resource_prefix_format or fastmcp.settings.resource_prefix_format
        )

        self._additional_http_routes: list[BaseRoute] = []
        self._mounted_servers: list[MountedServer] = []
        self._policy_engine: Optional[PolicyEngine] = None
        self._reflexive_engine: Optional[ReflexiveEngine] = None
        self._ledger: Optional[ProvenanceLedger] = None
        self._contract_engine: Optional[ContractEngine] = None
        self._tool_manager = ToolManager(
            duplicate_behavior=on_duplicate_tools,
            mask_error_details=mask_error_details,
            transformations=tool_transformations,
        )
        self._resource_manager = ResourceManager(
            duplicate_behavior=on_duplicate_resources,
            mask_error_details=mask_error_details,
        )
        self._prompt_manager = PromptManager(
            duplicate_behavior=on_duplicate_prompts,
            mask_error_details=mask_error_details,
        )
        self._tool_serializer = tool_serializer

        if lifespan is None:
            self._has_lifespan = False
            lifespan = default_lifespan
        else:
            self._has_lifespan = True
        self._mcp_server = LowLevelServer[LifespanResultT](
            name=name or "FastMCP",
            version=version,
            instructions=instructions,
            lifespan=_lifespan_wrapper(self, lifespan),
        )

        # if auth is `NotSet`, try to create a provider from the environment
        if auth is NotSet:
            if fastmcp.settings.server_auth is not None:
                provider_cls = get_registered_provider(fastmcp.settings.server_auth)
                auth = provider_cls()
            else:
                auth = None
        self.auth = cast(AuthProvider | None, auth)

        if tools:
            for tool in tools:
                if not isinstance(tool, Tool):
                    tool = Tool.from_function(tool, serializer=self._tool_serializer)
                self.add_tool(tool)

        self.include_tags = include_tags
        self.exclude_tags = exclude_tags

        self.middleware = middleware or []

        # Set up MCP protocol handlers
        self._setup_handlers()

        # Handle dependencies with deprecation warning
        # TODO: Remove dependencies parameter (deprecated in v2.11.4)
        if dependencies is not None:
            import warnings

            warnings.warn(
                "The 'dependencies' parameter is deprecated as of FastMCP 2.11.4 and will be removed in a future version. "
                "Please specify dependencies in a fastmcp.json configuration file instead:\n"
                '{\n  "entrypoint": "your_server.py",\n  "environment": {\n    "dependencies": '
                f"{json.dumps(dependencies)}\n  }}\n}}\n"
                "See https://gofastmcp.com/docs/deployment/server-configuration for more information.",
                DeprecationWarning,
                stacklevel=2,
            )
        self.dependencies = (
            dependencies or fastmcp.settings.server_dependencies
        )  # TODO: Remove (deprecated in v2.11.4)

        self.include_fastmcp_meta = (
            include_fastmcp_meta
            if include_fastmcp_meta is not None
            else fastmcp.settings.include_fastmcp_meta
        )

        # handle deprecated settings
        self._handle_deprecated_settings(
            log_level=log_level,
            debug=debug,
            host=host,
            port=port,
            sse_path=sse_path,
            message_path=message_path,
            streamable_http_path=streamable_http_path,
            json_response=json_response,
            stateless_http=stateless_http,
        )

    def __repr__(self) -> str:
        return f"{type(self).__name__}({self.name!r})"

    def _handle_deprecated_settings(
        self,
        log_level: str | None,
        debug: bool | None,
        host: str | None,
        port: int | None,
        sse_path: str | None,
        message_path: str | None,
        streamable_http_path: str | None,
        json_response: bool | None,
        stateless_http: bool | None,
    ) -> None:
        """Handle deprecated settings. Deprecated in 2.8.0."""
        deprecated_settings: dict[str, Any] = {}

        for name, arg in [
            ("log_level", log_level),
            ("debug", debug),
            ("host", host),
            ("port", port),
            ("sse_path", sse_path),
            ("message_path", message_path),
            ("streamable_http_path", streamable_http_path),
            ("json_response", json_response),
            ("stateless_http", stateless_http),
        ]:
            if arg is not None:
                # Deprecated in 2.8.0
                if fastmcp.settings.deprecation_warnings:
                    warnings.warn(
                        f"Providing `{name}` when creating a server is deprecated. Provide it when calling `run` or as a global setting instead.",
                        DeprecationWarning,
                        stacklevel=2,
                    )
                deprecated_settings[name] = arg

        combined_settings = fastmcp.settings.model_dump() | deprecated_settings
        self._deprecated_settings = Settings(**combined_settings)

    @property
    def settings(self) -> Settings:
        # Deprecated in 2.8.0
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "Accessing `.settings` on a FastMCP instance is deprecated. Use the global `fastmcp.settings` instead.",
                DeprecationWarning,
                stacklevel=2,
            )
        return self._deprecated_settings

    @property
    def name(self) -> str:
        return self._mcp_server.name

    @property
    def instructions(self) -> str | None:
        return self._mcp_server.instructions

    @property
    def version(self) -> str | None:
        return self._mcp_server.version

    async def run_async(
        self,
        transport: Transport | None = None,
        show_banner: bool = True,
        **transport_kwargs: Any,
    ) -> None:
        """Run the FastMCP server asynchronously.

        Args:
            transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
        """
        if transport is None:
            transport = "stdio"
        if transport not in {"stdio", "http", "sse", "streamable-http"}:
            raise ValueError(f"Unknown transport: {transport}")

        if transport == "stdio":
            await self.run_stdio_async(
                show_banner=show_banner,
                **transport_kwargs,
            )
        elif transport in {"http", "sse", "streamable-http"}:
            await self.run_http_async(
                transport=transport,
                show_banner=show_banner,
                **transport_kwargs,
            )
        else:
            raise ValueError(f"Unknown transport: {transport}")

    def run(
        self,
        transport: Transport | None = None,
        show_banner: bool = True,
        **transport_kwargs: Any,
    ) -> None:
        """Run the FastMCP server. Note this is a synchronous function.

        Args:
            transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
        """

        anyio.run(
            partial(
                self.run_async,
                transport,
                show_banner=show_banner,
                **transport_kwargs,
            )
        )

    def _setup_handlers(self) -> None:
        """Set up core MCP protocol handlers."""
        self._mcp_server.list_tools()(self._mcp_list_tools)
        self._mcp_server.list_resources()(self._mcp_list_resources)
        self._mcp_server.list_resource_templates()(self._mcp_list_resource_templates)
        self._mcp_server.list_prompts()(self._mcp_list_prompts)
        self._mcp_server.call_tool()(self._mcp_call_tool)
        self._mcp_server.read_resource()(self._mcp_read_resource)
        self._mcp_server.get_prompt()(self._mcp_get_prompt)

    async def _apply_middleware(
        self,
        context: MiddlewareContext[Any],
        call_next: Callable[[MiddlewareContext[Any]], Awaitable[Any]],
    ) -> Any:
        """Builds and executes the middleware chain."""
        chain = call_next
        for mw in reversed(self.middleware):
            chain = partial(mw, call_next=chain)
        return await chain(context)

    def add_middleware(self, middleware: Middleware) -> None:
        self.middleware.append(middleware)

    async def get_tools(self) -> dict[str, Tool]:
        """Get all registered tools, indexed by registered key."""
        return await self._tool_manager.get_tools()

    async def get_tool(self, key: str) -> Tool:
        tools = await self.get_tools()
        if key not in tools:
            raise NotFoundError(f"Unknown tool: {key}")
        return tools[key]

    async def get_resources(self) -> dict[str, Resource]:
        """Get all registered resources, indexed by registered key."""
        return await self._resource_manager.get_resources()

    async def get_resource(self, key: str) -> Resource:
        resources = await self.get_resources()
        if key not in resources:
            raise NotFoundError(f"Unknown resource: {key}")
        return resources[key]

    async def get_resource_templates(self) -> dict[str, ResourceTemplate]:
        """Get all registered resource templates, indexed by registered key."""
        return await self._resource_manager.get_resource_templates()

    async def get_resource_template(self, key: str) -> ResourceTemplate:
        """Get a registered resource template by key."""
        templates = await self.get_resource_templates()
        if key not in templates:
            raise NotFoundError(f"Unknown resource template: {key}")
        return templates[key]

    async def get_prompts(self) -> dict[str, Prompt]:
        """
        List all available prompts.
        """
        return await self._prompt_manager.get_prompts()

    async def get_prompt(self, key: str) -> Prompt:
        prompts = await self.get_prompts()
        if key not in prompts:
            raise NotFoundError(f"Unknown prompt: {key}")
        return prompts[key]

    def custom_route(
        self,
        path: str,
        methods: list[str],
        name: str | None = None,
        include_in_schema: bool = True,
    ) -> Callable[
        [Callable[[Request], Awaitable[Response]]],
        Callable[[Request], Awaitable[Response]],
    ]:
        """
        Decorator to register a custom HTTP route on the FastMCP server.

        Allows adding arbitrary HTTP endpoints outside the standard MCP protocol,
        which can be useful for OAuth callbacks, health checks, or admin APIs.
        The handler function must be an async function that accepts a Starlette
        Request and returns a Response.

        Args:
            path: URL path for the route (e.g., "/oauth/callback")
            methods: List of HTTP methods to support (e.g., ["GET", "POST"])
            name: Optional name for the route (to reference this route with
                Starlette's reverse URL lookup feature)
            include_in_schema: Whether to include in OpenAPI schema, defaults to True

        Example:
            Register a custom HTTP route for a health check endpoint:
            ```python
            @server.custom_route("/health", methods=["GET"])
            async def health_check(request: Request) -> Response:
                return JSONResponse({"status": "ok"})
            ```
        """

        def decorator(
            fn: Callable[[Request], Awaitable[Response]],
        ) -> Callable[[Request], Awaitable[Response]]:
            self._additional_http_routes.append(
                Route(
                    path,
                    endpoint=fn,
                    methods=methods,
                    name=name,
                    include_in_schema=include_in_schema,
                )
            )
            return fn

        return decorator

    def _get_additional_http_routes(self) -> list[BaseRoute]:
        """Get all additional HTTP routes including from mounted servers.

        Returns a list of all custom HTTP routes from this server and
        recursively from all mounted servers.

        Returns:
            List of Starlette BaseRoute objects
        """
        routes = list(self._additional_http_routes)

        # Add policy evaluation endpoint if policy engine is configured
        if self._policy_engine is not None:
            from fastmcp.server.policy_routes import create_policy_evaluate_route
            
            policy_route = create_policy_evaluate_route(self._policy_engine)
            routes.append(policy_route)

        # Add reflexive core endpoints if reflexive engine is configured
        if self._reflexive_engine is not None:
            from fastmcp.server.reflexive_routes import create_reflexive_routes
            
            reflexive_routes = create_reflexive_routes(self._reflexive_engine)
            routes.extend(reflexive_routes)
  
        # Add ledger management endpoints if ledger is configured
        if self._ledger is not None:
            from fastmcp.server.ledger_routes import create_ledger_routes
            
            ledger_routes = create_ledger_routes(self._ledger)
            routes.extend(ledger_routes)
            
        # Add contract management endpoints if contract engine is configured
        if self._contract_engine is not None:
            from fastmcp.server.contract_routes import create_contract_routes
            
            contract_routes = create_contract_routes(self._contract_engine)
            routes.extend(contract_routes)

        # Recursively get routes from mounted servers
        for mounted_server in self._mounted_servers:
            mounted_routes = mounted_server.server._get_additional_http_routes()
            routes.extend(mounted_routes)

        return routes
    
    def enable_policy_engine(self, policy_engine: Optional[PolicyEngine] = None) -> PolicyEngine:
        """Enable the policy engine for this server.
        
        Args:
            policy_engine: Optional policy engine instance. If None, creates a new one.
            
        Returns:
            The policy engine instance
        """
        if policy_engine is None:
            policy_engine = PolicyEngine()
        
        self._policy_engine = policy_engine
        logger.info("Policy engine enabled for server")
        return policy_engine
    
    def get_policy_engine(self) -> Optional[PolicyEngine]:
        """Get the policy engine instance.
        
        Returns:
            The policy engine instance, or None if not enabled
        """
        return self._policy_engine
    
    def enable_ledger(self, ledger: Optional[ProvenanceLedger] = None, database_url: str = "sqlite:///ledger.db") -> ProvenanceLedger:
        """Enable the provenance ledger for this server.
        
        Args:
            ledger: Optional ledger instance. If None, creates a new one.
            database_url: Database URL for ledger persistence
            
        Returns:
            The ledger instance
        """
        if ledger is None:
            ledger = ProvenanceLedger(database_url)
        
        self._ledger = ledger
        logger.info("Provenance ledger enabled for server")
        return ledger
    
    def get_ledger(self) -> Optional[ProvenanceLedger]:
        """Get the provenance ledger instance.
        
        Returns:
            The ledger instance, or None if not enabled
        """
        return self._ledger

    def enable_contract_engine(self, contract_engine: Optional[ContractEngine] = None, database_url: str = "sqlite:///contracts.db") -> ContractEngine:
        """Enable the contract engine for this server.
        
        Args:
            contract_engine: Optional contract engine instance. If None, creates a new one.
            database_url: Database URL for contract persistence
            
        Returns:
            The contract engine instance
        """
        if contract_engine is None:
            contract_engine = ContractEngine(database_url)
        
        self._contract_engine = contract_engine
        logger.info("Contract engine enabled for server")
        return contract_engine
    
    def get_contract_engine(self) -> Optional[ContractEngine]:
        """Get the contract engine instance.
        
        Returns:
            The contract engine instance, or None if not enabled
        """
        return self._contract_engine


    def enable_reflexive_core(self, reflexive_engine: Optional[ReflexiveEngine] = None) -> ReflexiveEngine:
        """Enable the reflexive core for this server.
        
        Args:
            reflexive_engine: Optional reflexive engine instance. If None, creates a new one.
            
        Returns:
            The reflexive engine instance
        """
        if reflexive_engine is None:
            reflexive_engine = ReflexiveEngine(
                policy_engine=self._policy_engine,
                ledger=None
            )
        
        self._reflexive_engine = reflexive_engine
        logger.info("Reflexive core enabled for server")
        return reflexive_engine

    def get_reflexive_engine(self) -> Optional[ReflexiveEngine]:
        """Get the reflexive engine instance.
        
        Returns:
            The reflexive engine instance, or None if not enabled
        """
        return self._reflexive_engine

    async def _mcp_list_tools(self) -> list[MCPTool]:
        logger.debug("Handler called: list_tools")

        async with fastmcp.server.context.Context(fastmcp=self):
            tools = await self._list_tools()
            return [
                tool.to_mcp_tool(
                    name=tool.key,
                    include_fastmcp_meta=self.include_fastmcp_meta,
                )
                for tool in tools
            ]

    async def _list_tools(self) -> list[Tool]:
        """
        List all available tools, in the format expected by the low-level MCP
        server.
        """

        async def _handler(
            context: MiddlewareContext[mcp.types.ListToolsRequest],
        ) -> list[Tool]:
            tools = await self._tool_manager.list_tools()  # type: ignore[reportPrivateUsage]

            mcp_tools: list[Tool] = []
            for tool in tools:
                if self._should_enable_component(tool):
                    mcp_tools.append(tool)

            return mcp_tools

        async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
            # Create the middleware context.
            mw_context = MiddlewareContext(
                message=mcp.types.ListToolsRequest(method="tools/list"),
                source="client",
                type="request",
                method="tools/list",
                fastmcp_context=fastmcp_ctx,
            )

            # Apply the middleware chain.
            return await self._apply_middleware(mw_context, _handler)

    async def _mcp_list_resources(self) -> list[MCPResource]:
        logger.debug("Handler called: list_resources")

        async with fastmcp.server.context.Context(fastmcp=self):
            resources = await self._list_resources()
            return [
                resource.to_mcp_resource(
                    uri=resource.key,
                    include_fastmcp_meta=self.include_fastmcp_meta,
                )
                for resource in resources
            ]

    async def _list_resources(self) -> list[Resource]:
        """
        List all available resources, in the format expected by the low-level MCP
        server.

        """

        async def _handler(
            context: MiddlewareContext[dict[str, Any]],
        ) -> list[Resource]:
            resources = await self._resource_manager.list_resources()  # type: ignore[reportPrivateUsage]

            mcp_resources: list[Resource] = []
            for resource in resources:
                if self._should_enable_component(resource):
                    mcp_resources.append(resource)

            return mcp_resources

        async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
            # Create the middleware context.
            mw_context = MiddlewareContext(
                message={},  # List resources doesn't have parameters
                source="client",
                type="request",
                method="resources/list",
                fastmcp_context=fastmcp_ctx,
            )

            # Apply the middleware chain.
            return await self._apply_middleware(mw_context, _handler)

    async def _mcp_list_resource_templates(self) -> list[MCPResourceTemplate]:
        logger.debug("Handler called: list_resource_templates")

        async with fastmcp.server.context.Context(fastmcp=self):
            templates = await self._list_resource_templates()
            return [
                template.to_mcp_template(
                    uriTemplate=template.key,
                    include_fastmcp_meta=self.include_fastmcp_meta,
                )
                for template in templates
            ]

    async def _list_resource_templates(self) -> list[ResourceTemplate]:
        """
        List all available resource templates, in the format expected by the low-level MCP
        server.

        """

        async def _handler(
            context: MiddlewareContext[dict[str, Any]],
        ) -> list[ResourceTemplate]:
            templates = await self._resource_manager.list_resource_templates()

            mcp_templates: list[ResourceTemplate] = []
            for template in templates:
                if self._should_enable_component(template):
                    mcp_templates.append(template)

            return mcp_templates

        async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
            # Create the middleware context.
            mw_context = MiddlewareContext(
                message={},  # List resource templates doesn't have parameters
                source="client",
                type="request",
                method="resources/templates/list",
                fastmcp_context=fastmcp_ctx,
            )

            # Apply the middleware chain.
            return await self._apply_middleware(mw_context, _handler)

    async def _mcp_list_prompts(self) -> list[MCPPrompt]:
        logger.debug("Handler called: list_prompts")

        async with fastmcp.server.context.Context(fastmcp=self):
            prompts = await self._list_prompts()
            return [
                prompt.to_mcp_prompt(
                    name=prompt.key,
                    include_fastmcp_meta=self.include_fastmcp_meta,
                )
                for prompt in prompts
            ]

    async def _list_prompts(self) -> list[Prompt]:
        """
        List all available prompts, in the format expected by the low-level MCP
        server.

        """

        async def _handler(
            context: MiddlewareContext[mcp.types.ListPromptsRequest],
        ) -> list[Prompt]:
            prompts = await self._prompt_manager.list_prompts()  # type: ignore[reportPrivateUsage]

            mcp_prompts: list[Prompt] = []
            for prompt in prompts:
                if self._should_enable_component(prompt):
                    mcp_prompts.append(prompt)

            return mcp_prompts

        async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:
            # Create the middleware context.
            mw_context = MiddlewareContext(
                message=mcp.types.ListPromptsRequest(method="prompts/list"),
                source="client",
                type="request",
                method="prompts/list",
                fastmcp_context=fastmcp_ctx,
            )

            # Apply the middleware chain.
            return await self._apply_middleware(mw_context, _handler)

    async def _mcp_call_tool(
        self, key: str, arguments: dict[str, Any]
    ) -> list[ContentBlock] | tuple[list[ContentBlock], dict[str, Any]]:
        """
        Handle MCP 'callTool' requests.

        Delegates to _call_tool, which should be overridden by FastMCP subclasses.

        Args:
            key: The name of the tool to call
            arguments: Arguments to pass to the tool

        Returns:
            List of MCP Content objects containing the tool results
        """
        logger.debug("Handler called: call_tool %s with %s", key, arguments)

        async with fastmcp.server.context.Context(fastmcp=self):
            try:
                result = await self._call_tool(key, arguments)
                return result.to_mcp_result()
            except DisabledError:
                raise NotFoundError(f"Unknown tool: {key}")
            except NotFoundError:
                raise NotFoundError(f"Unknown tool: {key}")

    async def _call_tool(self, key: str, arguments: dict[str, Any]) -> ToolResult:
        """
        Applies this server's middleware and delegates the filtered call to the manager.
        """

        async def _handler(
            context: MiddlewareContext[mcp.types.CallToolRequestParams],
        ) -> ToolResult:
            tool = await self._tool_manager.get_tool(context.message.name)
            if not self._should_enable_component(tool):
                raise NotFoundError(f"Unknown tool: {context.message.name!r}")

            return await self._tool_manager.call_tool(
                key=context.message.name, arguments=context.message.arguments or {}
            )

        mw_context = MiddlewareContext[CallToolRequestParams](
            message=mcp.types.CallToolRequestParams(name=key, arguments=arguments),
            source="client",
            type="request",
            method="tools/call",
            fastmcp_context=fastmcp.server.dependencies.get_context(),
        )
        return await self._apply_middleware(mw_context, _handler)

    async def _mcp_read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
        """
        Handle MCP 'readResource' requests.

        Delegates to _read_resource, which should be overridden by FastMCP subclasses.
        """
        logger.debug("Handler called: read_resource %s", uri)

        async with fastmcp.server.context.Context(fastmcp=self):
            try:
                return await self._read_resource(uri)
            except DisabledError:
                # convert to NotFoundError to avoid leaking resource presence
                raise NotFoundError(f"Unknown resource: {str(uri)!r}")
            except NotFoundError:
                # standardize NotFound message
                raise NotFoundError(f"Unknown resource: {str(uri)!r}")

    async def _read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]:
        """
        Applies this server's middleware and delegates the filtered call to the manager.
        """

        async def _handler(
            context: MiddlewareContext[mcp.types.ReadResourceRequestParams],
        ) -> list[ReadResourceContents]:
            resource = await self._resource_manager.get_resource(context.message.uri)
            if not self._should_enable_component(resource):
                raise NotFoundError(f"Unknown resource: {str(context.message.uri)!r}")

            content = await self._resource_manager.read_resource(context.message.uri)
            return [
                ReadResourceContents(
                    content=content,
                    mime_type=resource.mime_type,
                )
            ]

        # Convert string URI to AnyUrl if needed
        if isinstance(uri, str):
            uri_param = AnyUrl(uri)
        else:
            uri_param = uri

        mw_context = MiddlewareContext(
            message=mcp.types.ReadResourceRequestParams(uri=uri_param),
            source="client",
            type="request",
            method="resources/read",
            fastmcp_context=fastmcp.server.dependencies.get_context(),
        )
        return await self._apply_middleware(mw_context, _handler)

    async def _mcp_get_prompt(
        self, name: str, arguments: dict[str, Any] | None = None
    ) -> GetPromptResult:
        """
        Handle MCP 'getPrompt' requests.

        Delegates to _get_prompt, which should be overridden by FastMCP subclasses.
        """
        logger.debug("Handler called: get_prompt %s with %s", name, arguments)

        async with fastmcp.server.context.Context(fastmcp=self):
            try:
                return await self._get_prompt(name, arguments)
            except DisabledError:
                # convert to NotFoundError to avoid leaking prompt presence
                raise NotFoundError(f"Unknown prompt: {name}")
            except NotFoundError:
                # standardize NotFound message
                raise NotFoundError(f"Unknown prompt: {name}")

    async def _get_prompt(
        self, name: str, arguments: dict[str, Any] | None = None
    ) -> GetPromptResult:
        """
        Applies this server's middleware and delegates the filtered call to the manager.
        """

        async def _handler(
            context: MiddlewareContext[mcp.types.GetPromptRequestParams],
        ) -> GetPromptResult:
            prompt = await self._prompt_manager.get_prompt(context.message.name)
            if not self._should_enable_component(prompt):
                raise NotFoundError(f"Unknown prompt: {context.message.name!r}")

            return await self._prompt_manager.render_prompt(
                name=context.message.name, arguments=context.message.arguments
            )

        mw_context = MiddlewareContext(
            message=mcp.types.GetPromptRequestParams(name=name, arguments=arguments),
            source="client",
            type="request",
            method="prompts/get",
            fastmcp_context=fastmcp.server.dependencies.get_context(),
        )
        return await self._apply_middleware(mw_context, _handler)

    def add_tool(self, tool: Tool) -> Tool:
        """Add a tool to the server.

        The tool function can optionally request a Context object by adding a parameter
        with the Context type annotation. See the @tool decorator for examples.

        Args:
            tool: The Tool instance to register

        Returns:
            The tool instance that was added to the server.
        """
        self._tool_manager.add_tool(tool)

        # Send notification if we're in a request context
        try:
            from fastmcp.server.dependencies import get_context

            context = get_context()
            context._queue_tool_list_changed()  # type: ignore[private-use]
        except RuntimeError:
            pass  # No context available

        return tool

    def remove_tool(self, name: str) -> None:
        """Remove a tool from the server.

        Args:
            name: The name of the tool to remove

        Raises:
            NotFoundError: If the tool is not found
        """
        self._tool_manager.remove_tool(name)

        # Send notification if we're in a request context
        try:
            from fastmcp.server.dependencies import get_context

            context = get_context()
            context._queue_tool_list_changed()  # type: ignore[private-use]
        except RuntimeError:
            pass  # No context available

    def add_tool_transformation(
        self, tool_name: str, transformation: ToolTransformConfig
    ) -> None:
        """Add a tool transformation."""
        self._tool_manager.add_tool_transformation(tool_name, transformation)

    def remove_tool_transformation(self, tool_name: str) -> None:
        """Remove a tool transformation."""
        self._tool_manager.remove_tool_transformation(tool_name)

    @overload
    def tool(
        self,
        name_or_fn: AnyFunction,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        tags: set[str] | None = None,
        output_schema: dict[str, Any] | None | NotSetT = NotSet,
        annotations: ToolAnnotations | dict[str, Any] | None = None,
        exclude_args: list[str] | None = None,
        meta: dict[str, Any] | None = None,
        enabled: bool | None = None,
    ) -> FunctionTool: ...

    @overload
    def tool(
        self,
        name_or_fn: str | None = None,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        tags: set[str] | None = None,
        output_schema: dict[str, Any] | None | NotSetT = NotSet,
        annotations: ToolAnnotations | dict[str, Any] | None = None,
        exclude_args: list[str] | None = None,
        meta: dict[str, Any] | None = None,
        enabled: bool | None = None,
    ) -> Callable[[AnyFunction], FunctionTool]: ...

    def tool(
        self,
        name_or_fn: str | AnyFunction | None = None,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        tags: set[str] | None = None,
        output_schema: dict[str, Any] | None | NotSetT = NotSet,
        annotations: ToolAnnotations | dict[str, Any] | None = None,
        exclude_args: list[str] | None = None,
        meta: dict[str, Any] | None = None,
        enabled: bool | None = None,
    ) -> Callable[[AnyFunction], FunctionTool] | FunctionTool:
        """Decorator to register a tool.

        Tools can optionally request a Context object by adding a parameter with the
        Context type annotation. The context provides access to MCP capabilities like
        logging, progress reporting, and resource access.

        This decorator supports multiple calling patterns:
        - @server.tool (without parentheses)
        - @server.tool (with empty parentheses)
        - @server.tool("custom_name") (with name as first argument)
        - @server.tool(name="custom_name") (with name as keyword argument)
        - server.tool(function, name="custom_name") (direct function call)

        Args:
            name_or_fn: Either a function (when used as @tool), a string name, or None
            name: Optional name for the tool (keyword-only, alternative to name_or_fn)
            description: Optional description of what the tool does
            tags: Optional set of tags for categorizing the tool
            output_schema: Optional JSON schema for the tool's output
            annotations: Optional annotations about the tool's behavior
            exclude_args: Optional list of argument names to exclude from the tool schema
            meta: Optional meta information about the tool
            enabled: Optional boolean to enable or disable the tool

        Examples:
            Register a tool with a custom name:
            ```python
            @server.tool
            def my_tool(x: int) -> str:
                return str(x)

            # Register a tool with a custom name
            @server.tool
            def my_tool(x: int) -> str:
                return str(x)

            @server.tool("custom_name")
            def my_tool(x: int) -> str:
                return str(x)

            @server.tool(name="custom_name")
            def my_tool(x: int) -> str:
                return str(x)

            # Direct function call
            server.tool(my_function, name="custom_name")
            ```
        """
        if isinstance(annotations, dict):
            annotations = ToolAnnotations(**annotations)

        if isinstance(name_or_fn, classmethod):
            raise ValueError(
                inspect.cleandoc(
                    """
                    To decorate a classmethod, first define the method and then call
                    tool() directly on the method instead of using it as a
                    decorator. See https://gofastmcp.com/patterns/decorating-methods
                    for examples and more information.
                    """
                )
            )

        # Determine the actual name and function based on the calling pattern
        if inspect.isroutine(name_or_fn):
            # Case 1: @tool (without parens) - function passed directly
            # Case 2: direct call like tool(fn, name="something")
            fn = name_or_fn
            tool_name = name  # Use keyword name if provided, otherwise None

            # Register the tool immediately and return the tool object
            tool = Tool.from_function(
                fn,
                name=tool_name,
                title=title,
                description=description,
                tags=tags,
                output_schema=output_schema,
                annotations=annotations,
                exclude_args=exclude_args,
                meta=meta,
                serializer=self._tool_serializer,
                enabled=enabled,
            )
            self.add_tool(tool)
            return tool

        elif isinstance(name_or_fn, str):
            # Case 3: @tool("custom_name") - name passed as first argument
            if name is not None:
                raise TypeError(
                    "Cannot specify both a name as first argument and as keyword argument. "
                    f"Use either @tool('{name_or_fn}') or @tool(name='{name}'), not both."
                )
            tool_name = name_or_fn
        elif name_or_fn is None:
            # Case 4: @tool or @tool(name="something") - use keyword name
            tool_name = name
        else:
            raise TypeError(
                f"First argument to @tool must be a function, string, or None, got {type(name_or_fn)}"
            )

        # Return partial for cases where we need to wait for the function
        return partial(
            self.tool,
            name=tool_name,
            title=title,
            description=description,
            tags=tags,
            output_schema=output_schema,
            annotations=annotations,
            exclude_args=exclude_args,
            meta=meta,
            enabled=enabled,
        )

    def add_resource(self, resource: Resource) -> Resource:
        """Add a resource to the server.

        Args:
            resource: A Resource instance to add

        Returns:
            The resource instance that was added to the server.
        """
        self._resource_manager.add_resource(resource)

        # Send notification if we're in a request context
        try:
            from fastmcp.server.dependencies import get_context

            context = get_context()
            context._queue_resource_list_changed()  # type: ignore[private-use]
        except RuntimeError:
            pass  # No context available

        return resource

    def add_template(self, template: ResourceTemplate) -> ResourceTemplate:
        """Add a resource template to the server.

        Args:
            template: A ResourceTemplate instance to add

        Returns:
            The template instance that was added to the server.
        """
        self._resource_manager.add_template(template)

        # Send notification if we're in a request context
        try:
            from fastmcp.server.dependencies import get_context

            context = get_context()
            context._queue_resource_list_changed()  # type: ignore[private-use]
        except RuntimeError:
            pass  # No context available

        return template

    def add_resource_fn(
        self,
        fn: AnyFunction,
        uri: str,
        name: str | None = None,
        description: str | None = None,
        mime_type: str | None = None,
        tags: set[str] | None = None,
    ) -> None:
        """Add a resource or template to the server from a function.

        If the URI contains parameters (e.g. "resource://{param}") or the function
        has parameters, it will be registered as a template resource.

        Args:
            fn: The function to register as a resource
            uri: The URI for the resource
            name: Optional name for the resource
            description: Optional description of the resource
            mime_type: Optional MIME type for the resource
            tags: Optional set of tags for categorizing the resource
        """
        # deprecated since 2.7.0
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "The add_resource_fn method is deprecated. Use the resource decorator instead.",
                DeprecationWarning,
                stacklevel=2,
            )
        self._resource_manager.add_resource_or_template_from_fn(
            fn=fn,
            uri=uri,
            name=name,
            description=description,
            mime_type=mime_type,
            tags=tags,
        )

    def resource(
        self,
        uri: str,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        mime_type: str | None = None,
        tags: set[str] | None = None,
        enabled: bool | None = None,
        annotations: Annotations | dict[str, Any] | None = None,
        meta: dict[str, Any] | None = None,
    ) -> Callable[[AnyFunction], Resource | ResourceTemplate]:
        """Decorator to register a function as a resource.

        The function will be called when the resource is read to generate its content.
        The function can return:
        - str for text content
        - bytes for binary content
        - other types will be converted to JSON

        Resources can optionally request a Context object by adding a parameter with the
        Context type annotation. The context provides access to MCP capabilities like
        logging, progress reporting, and session information.

        If the URI contains parameters (e.g. "resource://{param}") or the function
        has parameters, it will be registered as a template resource.

        Args:
            uri: URI for the resource (e.g. "resource://my-resource" or "resource://{param}")
            name: Optional name for the resource
            description: Optional description of the resource
            mime_type: Optional MIME type for the resource
            tags: Optional set of tags for categorizing the resource
            enabled: Optional boolean to enable or disable the resource
            annotations: Optional annotations about the resource's behavior
            meta: Optional meta information about the resource

        Examples:
            Register a resource with a custom name:
            ```python
            @server.resource("resource://my-resource")
            def get_data() -> str:
                return "Hello, world!"

            @server.resource("resource://my-resource")
            async get_data() -> str:
                data = await fetch_data()
                return f"Hello, world! {data}"

            @server.resource("resource://{city}/weather")
            def get_weather(city: str) -> str:
                return f"Weather for {city}"

            @server.resource("resource://{city}/weather")
            def get_weather_with_context(city: str, ctx: Context) -> str:
                ctx.info(f"Fetching weather for {city}")
                return f"Weather for {city}"

            @server.resource("resource://{city}/weather")
            async def get_weather(city: str) -> str:
                data = await fetch_weather(city)
                return f"Weather for {city}: {data}"
            ```
        """
        if isinstance(annotations, dict):
            annotations = Annotations(**annotations)

        # Check if user passed function directly instead of calling decorator
        if inspect.isroutine(uri):
            raise TypeError(
                "The @resource decorator was used incorrectly. "
                "Did you forget to call it? Use @resource('uri') instead of @resource"
            )

        def decorator(fn: AnyFunction) -> Resource | ResourceTemplate:
            from fastmcp.server.context import Context

            if isinstance(fn, classmethod):  # type: ignore[reportUnnecessaryIsInstance]
                raise ValueError(
                    inspect.cleandoc(
                        """
                        To decorate a classmethod, first define the method and then call
                        resource() directly on the method instead of using it as a
                        decorator. See https://gofastmcp.com/patterns/decorating-methods
                        for examples and more information.
                        """
                    )
                )

            # Check if this should be a template
            has_uri_params = "{" in uri and "}" in uri
            # check if the function has any parameters (other than injected context)
            has_func_params = any(
                p
                for p in inspect.signature(fn).parameters.values()
                if p.annotation is not Context
            )

            if has_uri_params or has_func_params:
                template = ResourceTemplate.from_function(
                    fn=fn,
                    uri_template=uri,
                    name=name,
                    title=title,
                    description=description,
                    mime_type=mime_type,
                    tags=tags,
                    enabled=enabled,
                    annotations=annotations,
                    meta=meta,
                )
                self.add_template(template)
                return template
            elif not has_uri_params and not has_func_params:
                resource = Resource.from_function(
                    fn=fn,
                    uri=uri,
                    name=name,
                    title=title,
                    description=description,
                    mime_type=mime_type,
                    tags=tags,
                    enabled=enabled,
                    annotations=annotations,
                    meta=meta,
                )
                self.add_resource(resource)
                return resource
            else:
                raise ValueError(
                    "Invalid resource or template definition due to a "
                    "mismatch between URI parameters and function parameters."
                )

        return decorator

    def add_prompt(self, prompt: Prompt) -> Prompt:
        """Add a prompt to the server.

        Args:
            prompt: A Prompt instance to add

        Returns:
            The prompt instance that was added to the server.
        """
        self._prompt_manager.add_prompt(prompt)

        # Send notification if we're in a request context
        try:
            from fastmcp.server.dependencies import get_context

            context = get_context()
            context._queue_prompt_list_changed()  # type: ignore[private-use]
        except RuntimeError:
            pass  # No context available

        return prompt

    @overload
    def prompt(
        self,
        name_or_fn: AnyFunction,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        tags: set[str] | None = None,
        enabled: bool | None = None,
        meta: dict[str, Any] | None = None,
    ) -> FunctionPrompt: ...

    @overload
    def prompt(
        self,
        name_or_fn: str | None = None,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        tags: set[str] | None = None,
        enabled: bool | None = None,
        meta: dict[str, Any] | None = None,
    ) -> Callable[[AnyFunction], FunctionPrompt]: ...

    def prompt(
        self,
        name_or_fn: str | AnyFunction | None = None,
        *,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        tags: set[str] | None = None,
        enabled: bool | None = None,
        meta: dict[str, Any] | None = None,
    ) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt:
        """Decorator to register a prompt.

        Prompts can optionally request a Context object by adding a parameter with the
        Context type annotation. The context provides access to MCP capabilities like
        logging, progress reporting, and session information.

        This decorator supports multiple calling patterns:
        - @server.prompt (without parentheses)
        - @server.prompt() (with empty parentheses)
        - @server.prompt("custom_name") (with name as first argument)
        - @server.prompt(name="custom_name") (with name as keyword argument)
        - server.prompt(function, name="custom_name") (direct function call)

        Args:
            name_or_fn: Either a function (when used as @prompt), a string name, or None
            name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
            description: Optional description of what the prompt does
            tags: Optional set of tags for categorizing the prompt
            enabled: Optional boolean to enable or disable the prompt
            meta: Optional meta information about the prompt

        Examples:

            ```python
            @server.prompt
            def analyze_table(table_name: str) -> list[Message]:
                schema = read_table_schema(table_name)
                return [
                    {
                        "role": "user",
                        "content": f"Analyze this schema:\n{schema}"
                    }
                ]

            @server.prompt()
            def analyze_with_context(table_name: str, ctx: Context) -> list[Message]:
                ctx.info(f"Analyzing table {table_name}")
                schema = read_table_schema(table_name)
                return [
                    {
                        "role": "user",
                        "content": f"Analyze this schema:\n{schema}"
                    }
                ]

            @server.prompt("custom_name")
            def analyze_file(path: str) -> list[Message]:
                content = await read_file(path)
                return [
                    {
                        "role": "user",
                        "content": {
                            "type": "resource",
                            "resource": {
                                "uri": f"file://{path}",
                                "text": content
                            }
                        }
                    }
                ]

            @server.prompt(name="custom_name")
            def another_prompt(data: str) -> list[Message]:
                return [{"role": "user", "content": data}]

            # Direct function call
            server.prompt(my_function, name="custom_name")
            ```
        """

        if isinstance(name_or_fn, classmethod):
            raise ValueError(
                inspect.cleandoc(
                    """
                    To decorate a classmethod, first define the method and then call
                    prompt() directly on the method instead of using it as a
                    decorator. See https://gofastmcp.com/patterns/decorating-methods
                    for examples and more information.
                    """
                )
            )

        # Determine the actual name and function based on the calling pattern
        if inspect.isroutine(name_or_fn):
            # Case 1: @prompt (without parens) - function passed directly as decorator
            # Case 2: direct call like prompt(fn, name="something")
            fn = name_or_fn
            prompt_name = name  # Use keyword name if provided, otherwise None

            # Register the prompt immediately
            prompt = Prompt.from_function(
                fn=fn,
                name=prompt_name,
                title=title,
                description=description,
                tags=tags,
                enabled=enabled,
                meta=meta,
            )
            self.add_prompt(prompt)

            return prompt

        elif isinstance(name_or_fn, str):
            # Case 3: @prompt("custom_name") - name passed as first argument
            if name is not None:
                raise TypeError(
                    "Cannot specify both a name as first argument and as keyword argument. "
                    f"Use either @prompt('{name_or_fn}') or @prompt(name='{name}'), not both."
                )
            prompt_name = name_or_fn
        elif name_or_fn is None:
            # Case 4: @prompt() or @prompt(name="something") - use keyword name
            prompt_name = name
        else:
            raise TypeError(
                f"First argument to @prompt must be a function, string, or None, got {type(name_or_fn)}"
            )

        # Return partial for cases where we need to wait for the function
        return partial(
            self.prompt,
            name=prompt_name,
            title=title,
            description=description,
            tags=tags,
            enabled=enabled,
            meta=meta,
        )

    async def run_stdio_async(self, show_banner: bool = True) -> None:
        """Run the server using stdio transport."""

        # Display server banner
        if show_banner:
            log_server_banner(
                server=self,
                transport="stdio",
            )

        async with stdio_server() as (read_stream, write_stream):
            logger.info(f"Starting MCP server {self.name!r} with transport 'stdio'")
            await self._mcp_server.run(
                read_stream,
                write_stream,
                self._mcp_server.create_initialization_options(
                    NotificationOptions(tools_changed=True)
                ),
            )

    async def run_http_async(
        self,
        show_banner: bool = True,
        transport: Literal["http", "streamable-http", "sse"] = "http",
        host: str | None = None,
        port: int | None = None,
        log_level: str | None = None,
        path: str | None = None,
        uvicorn_config: dict[str, Any] | None = None,
        middleware: list[ASGIMiddleware] | None = None,
        stateless_http: bool | None = None,
    ) -> None:
        """Run the server using HTTP transport.

        Args:
            transport: Transport protocol to use - either "streamable-http" (default) or "sse"
            host: Host address to bind to (defaults to settings.host)
            port: Port to bind to (defaults to settings.port)
            log_level: Log level for the server (defaults to settings.log_level)
            path: Path for the endpoint (defaults to settings.streamable_http_path or settings.sse_path)
            uvicorn_config: Additional configuration for the Uvicorn server
            middleware: A list of middleware to apply to the app
            stateless_http: Whether to use stateless HTTP (defaults to settings.stateless_http)
        """

        host = host or self._deprecated_settings.host
        port = port or self._deprecated_settings.port
        default_log_level_to_use = (
            log_level or self._deprecated_settings.log_level
        ).lower()

        app = self.http_app(
            path=path,
            transport=transport,
            middleware=middleware,
            stateless_http=stateless_http,
        )

        # Get the path for the server URL
        server_path = (
            app.state.path.lstrip("/")
            if hasattr(app, "state") and hasattr(app.state, "path")
            else path or ""
        )

        # Display server banner
        if show_banner:
            log_server_banner(
                server=self,
                transport=transport,
                host=host,
                port=port,
                path=server_path,
            )
        _uvicorn_config_from_user = uvicorn_config or {}

        config_kwargs: dict[str, Any] = {
            "timeout_graceful_shutdown": 0,
            "lifespan": "on",
        }
        config_kwargs.update(_uvicorn_config_from_user)

        if "log_config" not in config_kwargs and "log_level" not in config_kwargs:
            config_kwargs["log_level"] = default_log_level_to_use

        config = uvicorn.Config(app, host=host, port=port, **config_kwargs)
        server = uvicorn.Server(config)
        path = app.state.path.lstrip("/")  # type: ignore
        logger.info(
            f"Starting MCP server {self.name!r} with transport {transport!r} on http://{host}:{port}/{path}"
        )

        await server.serve()

    async def run_sse_async(
        self,
        host: str | None = None,
        port: int | None = None,
        log_level: str | None = None,
        path: str | None = None,
        uvicorn_config: dict[str, Any] | None = None,
    ) -> None:
        """Run the server using SSE transport."""

        # Deprecated since 2.3.2
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "The run_sse_async method is deprecated (as of 2.3.2). Use run_http_async for a "
                "modern (non-SSE) alternative, or create an SSE app with "
                "`fastmcp.server.http.create_sse_app` and run it directly.",
                DeprecationWarning,
                stacklevel=2,
            )
        await self.run_http_async(
            transport="sse",
            host=host,
            port=port,
            log_level=log_level,
            path=path,
            uvicorn_config=uvicorn_config,
        )

    def sse_app(
        self,
        path: str | None = None,
        message_path: str | None = None,
        middleware: list[ASGIMiddleware] | None = None,
    ) -> StarletteWithLifespan:
        """
        Create a Starlette app for the SSE server.

        Args:
            path: The path to the SSE endpoint
            message_path: The path to the message endpoint
            middleware: A list of middleware to apply to the app
        """
        # Deprecated since 2.3.2
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "The sse_app method is deprecated (as of 2.3.2). Use http_app as a modern (non-SSE) "
                "alternative, or call `fastmcp.server.http.create_sse_app` directly.",
                DeprecationWarning,
                stacklevel=2,
            )
        return create_sse_app(
            server=self,
            message_path=message_path or self._deprecated_settings.message_path,
            sse_path=path or self._deprecated_settings.sse_path,
            auth=self.auth,
            debug=self._deprecated_settings.debug,
            middleware=middleware,
        )

    def streamable_http_app(
        self,
        path: str | None = None,
        middleware: list[ASGIMiddleware] | None = None,
    ) -> StarletteWithLifespan:
        """
        Create a Starlette app for the StreamableHTTP server.

        Args:
            path: The path to the StreamableHTTP endpoint
            middleware: A list of middleware to apply to the app
        """
        # Deprecated since 2.3.2
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "The streamable_http_app method is deprecated (as of 2.3.2). Use http_app() instead.",
                DeprecationWarning,
                stacklevel=2,
            )
        return self.http_app(path=path, middleware=middleware)

    def http_app(
        self,
        path: str | None = None,
        middleware: list[ASGIMiddleware] | None = None,
        json_response: bool | None = None,
        stateless_http: bool | None = None,
        transport: Literal["http", "streamable-http", "sse"] = "http",
    ) -> StarletteWithLifespan:
        """Create a Starlette app using the specified HTTP transport.

        Args:
            path: The path for the HTTP endpoint
            middleware: A list of middleware to apply to the app
            transport: Transport protocol to use - either "streamable-http" (default) or "sse"

        Returns:
            A Starlette application configured with the specified transport
        """

        if transport in ("streamable-http", "http"):
            return create_streamable_http_app(
                server=self,
                streamable_http_path=path
                or self._deprecated_settings.streamable_http_path,
                event_store=None,
                auth=self.auth,
                json_response=(
                    json_response
                    if json_response is not None
                    else self._deprecated_settings.json_response
                ),
                stateless_http=(
                    stateless_http
                    if stateless_http is not None
                    else self._deprecated_settings.stateless_http
                ),
                debug=self._deprecated_settings.debug,
                middleware=middleware,
            )
        elif transport == "sse":
            return create_sse_app(
                server=self,
                message_path=self._deprecated_settings.message_path,
                sse_path=path or self._deprecated_settings.sse_path,
                auth=self.auth,
                debug=self._deprecated_settings.debug,
                middleware=middleware,
            )

    async def run_streamable_http_async(
        self,
        host: str | None = None,
        port: int | None = None,
        log_level: str | None = None,
        path: str | None = None,
        uvicorn_config: dict[str, Any] | None = None,
    ) -> None:
        # Deprecated since 2.3.2
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "The run_streamable_http_async method is deprecated (as of 2.3.2). "
                "Use run_http_async instead.",
                DeprecationWarning,
                stacklevel=2,
            )
        await self.run_http_async(
            transport="http",
            host=host,
            port=port,
            log_level=log_level,
            path=path,
            uvicorn_config=uvicorn_config,
        )

    def mount(
        self,
        server: FastMCP[LifespanResultT],
        prefix: str | None = None,
        as_proxy: bool | None = None,
        *,
        tool_separator: str | None = None,
        resource_separator: str | None = None,
        prompt_separator: str | None = None,
    ) -> None:
        """Mount another FastMCP server on this server with an optional prefix.

        Unlike importing (with import_server), mounting establishes a dynamic connection
        between servers. When a client interacts with a mounted server's objects through
        the parent server, requests are forwarded to the mounted server in real-time.
        This means changes to the mounted server are immediately reflected when accessed
        through the parent.

        When a server is mounted with a prefix:
        - Tools from the mounted server are accessible with prefixed names.
          Example: If server has a tool named "get_weather", it will be available as "prefix_get_weather".
        - Resources are accessible with prefixed URIs.
          Example: If server has a resource with URI "weather://forecast", it will be available as
          "weather://prefix/forecast".
        - Templates are accessible with prefixed URI templates.
          Example: If server has a template with URI "weather://location/{id}", it will be available
          as "weather://prefix/location/{id}".
        - Prompts are accessible with prefixed names.
          Example: If server has a prompt named "weather_prompt", it will be available as
          "prefix_weather_prompt".

        When a server is mounted without a prefix (prefix=None), its tools, resources, templates,
        and prompts are accessible with their original names. Multiple servers can be mounted
        without prefixes, and they will be tried in order until a match is found.

        There are two modes for mounting servers:
        1. Direct mounting (default when server has no custom lifespan): The parent server
           directly accesses the mounted server's objects in-memory for better performance.
           In this mode, no client lifecycle events occur on the mounted server, including
           lifespan execution.

        2. Proxy mounting (default when server has a custom lifespan): The parent server
           treats the mounted server as a separate entity and communicates with it via a
           Client transport. This preserves all client-facing behaviors, including lifespan
           execution, but with slightly higher overhead.

        Args:
            server: The FastMCP server to mount.
            prefix: Optional prefix to use for the mounted server's objects. If None,
                the server's objects are accessible with their original names.
            as_proxy: Whether to treat the mounted server as a proxy. If None (default),
                automatically determined based on whether the server has a custom lifespan
                (True if it has a custom lifespan, False otherwise).
            tool_separator: Deprecated. Separator character for tool names.
            resource_separator: Deprecated. Separator character for resource URIs.
            prompt_separator: Deprecated. Separator character for prompt names.
        """
        from fastmcp.server.proxy import FastMCPProxy

        # Deprecated since 2.9.0
        # Prior to 2.9.0, the first positional argument was the prefix and the
        # second was the server. Here we swap them if needed now that the prefix
        # is optional.
        if isinstance(server, str):
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "Mount prefixes are now optional and the first positional argument "
                    "should be the server you want to mount.",
                    DeprecationWarning,
                    stacklevel=2,
                )
            server, prefix = cast(FastMCP[Any], prefix), server

        if tool_separator is not None:
            # Deprecated since 2.4.0
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "The tool_separator parameter is deprecated and will be removed in a future version. "
                    "Tools are now prefixed using 'prefix_toolname' format.",
                    DeprecationWarning,
                    stacklevel=2,
                )

        if resource_separator is not None:
            # Deprecated since 2.4.0
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "The resource_separator parameter is deprecated and ignored. "
                    "Resource prefixes are now added using the protocol://prefix/path format.",
                    DeprecationWarning,
                    stacklevel=2,
                )

        if prompt_separator is not None:
            # Deprecated since 2.4.0
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "The prompt_separator parameter is deprecated and will be removed in a future version. "
                    "Prompts are now prefixed using 'prefix_promptname' format.",
                    DeprecationWarning,
                    stacklevel=2,
                )

        # if as_proxy is not specified and the server has a custom lifespan,
        # we should treat it as a proxy
        if as_proxy is None:
            as_proxy = server._has_lifespan

        if as_proxy and not isinstance(server, FastMCPProxy):
            server = FastMCP.as_proxy(server)

        # Delegate mounting to all three managers
        mounted_server = MountedServer(
            prefix=prefix,
            server=server,
            resource_prefix_format=self.resource_prefix_format,
        )
        self._mounted_servers.append(mounted_server)
        self._tool_manager.mount(mounted_server)
        self._resource_manager.mount(mounted_server)
        self._prompt_manager.mount(mounted_server)

    async def import_server(
        self,
        server: FastMCP[LifespanResultT],
        prefix: str | None = None,
        tool_separator: str | None = None,
        resource_separator: str | None = None,
        prompt_separator: str | None = None,
    ) -> None:
        """
        Import the MCP objects from another FastMCP server into this one,
        optionally with a given prefix.

        Note that when a server is *imported*, its objects are immediately
        registered to the importing server. This is a one-time operation and
        future changes to the imported server will not be reflected in the
        importing server. Server-level configurations and lifespans are not imported.

        When a server is imported with a prefix:
        - The tools are imported with prefixed names
          Example: If server has a tool named "get_weather", it will be
          available as "prefix_get_weather"
        - The resources are imported with prefixed URIs using the new format
          Example: If server has a resource with URI "weather://forecast", it will
          be available as "weather://prefix/forecast"
        - The templates are imported with prefixed URI templates using the new format
          Example: If server has a template with URI "weather://location/{id}", it will
          be available as "weather://prefix/location/{id}"
        - The prompts are imported with prefixed names
          Example: If server has a prompt named "weather_prompt", it will be available as
          "prefix_weather_prompt"

        When a server is imported without a prefix (prefix=None), its tools, resources,
        templates, and prompts are imported with their original names.

        Args:
            server: The FastMCP server to import
            prefix: Optional prefix to use for the imported server's objects. If None,
                objects are imported with their original names.
            tool_separator: Deprecated. Separator for tool names.
            resource_separator: Deprecated and ignored. Prefix is now
              applied using the protocol://prefix/path format
            prompt_separator: Deprecated. Separator for prompt names.
        """

        # Deprecated since 2.9.0
        # Prior to 2.9.0, the first positional argument was the prefix and the
        # second was the server. Here we swap them if needed now that the prefix
        # is optional.
        if isinstance(server, str):
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "Import prefixes are now optional and the first positional argument "
                    "should be the server you want to import.",
                    DeprecationWarning,
                    stacklevel=2,
                )
            server, prefix = cast(FastMCP[Any], prefix), server

        if tool_separator is not None:
            # Deprecated since 2.4.0
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "The tool_separator parameter is deprecated and will be removed in a future version. "
                    "Tools are now prefixed using 'prefix_toolname' format.",
                    DeprecationWarning,
                    stacklevel=2,
                )

        if resource_separator is not None:
            # Deprecated since 2.4.0
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "The resource_separator parameter is deprecated and ignored. "
                    "Resource prefixes are now added using the protocol://prefix/path format.",
                    DeprecationWarning,
                    stacklevel=2,
                )

        if prompt_separator is not None:
            # Deprecated since 2.4.0
            if fastmcp.settings.deprecation_warnings:
                warnings.warn(
                    "The prompt_separator parameter is deprecated and will be removed in a future version. "
                    "Prompts are now prefixed using 'prefix_promptname' format.",
                    DeprecationWarning,
                    stacklevel=2,
                )

        # Import tools from the server
        for key, tool in (await server.get_tools()).items():
            if prefix:
                tool = tool.model_copy(key=f"{prefix}_{key}")
            self._tool_manager.add_tool(tool)

        # Import resources and templates from the server
        for key, resource in (await server.get_resources()).items():
            if prefix:
                resource_key = add_resource_prefix(
                    key, prefix, self.resource_prefix_format
                )
                resource = resource.model_copy(
                    update={"name": f"{prefix}_{resource.name}"}, key=resource_key
                )
            self._resource_manager.add_resource(resource)

        for key, template in (await server.get_resource_templates()).items():
            if prefix:
                template_key = add_resource_prefix(
                    key, prefix, self.resource_prefix_format
                )
                template = template.model_copy(
                    update={"name": f"{prefix}_{template.name}"}, key=template_key
                )
            self._resource_manager.add_template(template)

        # Import prompts from the server
        for key, prompt in (await server.get_prompts()).items():
            if prefix:
                prompt = prompt.model_copy(key=f"{prefix}_{key}")
            self._prompt_manager.add_prompt(prompt)

        if prefix:
            logger.debug(f"Imported server {server.name} with prefix '{prefix}'")
        else:
            logger.debug(f"Imported server {server.name}")

    @classmethod
    def from_openapi(
        cls,
        openapi_spec: dict[str, Any],
        client: httpx.AsyncClient,
        route_maps: list[RouteMap] | list[RouteMapNew] | None = None,
        route_map_fn: OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | None = None,
        mcp_component_fn: OpenAPIComponentFn | OpenAPIComponentFnNew | None = None,
        mcp_names: dict[str, str] | None = None,
        tags: set[str] | None = None,
        **settings: Any,
    ) -> FastMCPOpenAPI | FastMCPOpenAPINew:
        """
        Create a FastMCP server from an OpenAPI specification.
        """

        # Check if experimental parser is enabled
        if fastmcp.settings.experimental.enable_new_openapi_parser:
            from fastmcp.experimental.server.openapi import FastMCPOpenAPI

            return FastMCPOpenAPI(
                openapi_spec=openapi_spec,
                client=client,
                route_maps=cast(Any, route_maps),
                route_map_fn=cast(Any, route_map_fn),
                mcp_component_fn=cast(Any, mcp_component_fn),
                mcp_names=mcp_names,
                tags=tags,
                **settings,
            )
        else:
            logger.info(
                "Using legacy OpenAPI parser. To use the new parser, set "
                "FASTMCP_EXPERIMENTAL_ENABLE_NEW_OPENAPI_PARSER=true. The new parser "
                "was introduced for testing in 2.11 and will become the default soon."
            )
            from .openapi import FastMCPOpenAPI

            return FastMCPOpenAPI(
                openapi_spec=openapi_spec,
                client=client,
                route_maps=cast(Any, route_maps),
                route_map_fn=cast(Any, route_map_fn),
                mcp_component_fn=cast(Any, mcp_component_fn),
                mcp_names=mcp_names,
                tags=tags,
                **settings,
            )

    @classmethod
    def from_fastapi(
        cls,
        app: Any,
        name: str | None = None,
        route_maps: list[RouteMap] | list[RouteMapNew] | None = None,
        route_map_fn: OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | None = None,
        mcp_component_fn: OpenAPIComponentFn | OpenAPIComponentFnNew | None = None,
        mcp_names: dict[str, str] | None = None,
        httpx_client_kwargs: dict[str, Any] | None = None,
        tags: set[str] | None = None,
        **settings: Any,
    ) -> FastMCPOpenAPI | FastMCPOpenAPINew:
        """
        Create a FastMCP server from a FastAPI application.
        """

        if httpx_client_kwargs is None:
            httpx_client_kwargs = {}
        httpx_client_kwargs.setdefault("base_url", "http://fastapi")

        client = httpx.AsyncClient(
            transport=httpx.ASGITransport(app=app),
            **httpx_client_kwargs,
        )

        name = name or app.title

        # Check if experimental parser is enabled
        if fastmcp.settings.experimental.enable_new_openapi_parser:
            from fastmcp.experimental.server.openapi import FastMCPOpenAPI

            return FastMCPOpenAPI(
                openapi_spec=app.openapi(),
                client=client,
                name=name,
                route_maps=cast(Any, route_maps),
                route_map_fn=cast(Any, route_map_fn),
                mcp_component_fn=cast(Any, mcp_component_fn),
                mcp_names=mcp_names,
                tags=tags,
                **settings,
            )
        else:
            logger.info(
                "Using legacy OpenAPI parser. To use the new parser, set "
                "FASTMCP_EXPERIMENTAL_ENABLE_NEW_OPENAPI_PARSER=true. The new parser "
                "was introduced for testing in 2.11 and will become the default soon."
            )
            from .openapi import FastMCPOpenAPI

            return FastMCPOpenAPI(
                openapi_spec=app.openapi(),
                client=client,
                name=name,
                route_maps=cast(Any, route_maps),
                route_map_fn=cast(Any, route_map_fn),
                mcp_component_fn=cast(Any, mcp_component_fn),
                mcp_names=mcp_names,
                tags=tags,
                **settings,
            )

    @classmethod
    def as_proxy(
        cls,
        backend: (
            Client[ClientTransportT]
            | ClientTransport
            | FastMCP[Any]
            | AnyUrl
            | Path
            | MCPConfig
            | dict[str, Any]
            | str
        ),
        **settings: Any,
    ) -> FastMCPProxy:
        """Create a FastMCP proxy server for the given backend.

        The `backend` argument can be either an existing `fastmcp.client.Client`
        instance or any value accepted as the `transport` argument of
        `fastmcp.client.Client`. This mirrors the convenience of the
        `fastmcp.client.Client` constructor.
        """
        from fastmcp.client.client import Client
        from fastmcp.server.proxy import FastMCPProxy, ProxyClient

        if isinstance(backend, Client):
            client = backend
            # Session strategy based on client connection state:
            # - Connected clients: reuse existing session for all requests
            # - Disconnected clients: create fresh sessions per request for isolation
            if client.is_connected():
                from fastmcp.utilities.logging import get_logger

                logger = get_logger(__name__)
                logger.info(
                    "Proxy detected connected client - reusing existing session for all requests. "
                    "This may cause context mixing in concurrent scenarios."
                )

                # Reuse sessions - return the same client instance
                def reuse_client_factory():
                    return client

                client_factory = reuse_client_factory
            else:
                # Fresh sessions per request
                def fresh_client_factory():
                    return client.new()

                client_factory = fresh_client_factory
        else:
            base_client = ProxyClient(backend)

            # Fresh client created from transport - use fresh sessions per request
            def proxy_client_factory():
                return base_client.new()

            client_factory = proxy_client_factory

        return FastMCPProxy(client_factory=client_factory, **settings)

    @classmethod
    def from_client(
        cls, client: Client[ClientTransportT], **settings: Any
    ) -> FastMCPProxy:
        """
        Create a FastMCP proxy server from a FastMCP client.
        """
        # Deprecated since 2.3.5
        if fastmcp.settings.deprecation_warnings:
            warnings.warn(
                "FastMCP.from_client() is deprecated; use FastMCP.as_proxy() instead.",
                DeprecationWarning,
                stacklevel=2,
            )

        return cls.as_proxy(client, **settings)

    def _should_enable_component(
        self,
        component: FastMCPComponent,
    ) -> bool:
        """
        Given a component, determine if it should be enabled. Returns True if it should be enabled; False if it should not.

        Rules:
            - If the component's enabled property is False, always return False.
            - If both include_tags and exclude_tags are None, return True.
            - If exclude_tags is provided, check each exclude tag:
                - If the exclude tag is a string, it must be present in the input tags to exclude.
            - If include_tags is provided, check each include tag:
                - If the include tag is a string, it must be present in the input tags to include.
            - If include_tags is provided and none of the include tags match, return False.
            - If include_tags is not provided, return True.
        """
        if not component.enabled:
            return False

        if self.include_tags is None and self.exclude_tags is None:
            return True

        if self.exclude_tags is not None:
            if any(etag in component.tags for etag in self.exclude_tags):
                return False

        if self.include_tags is not None:
            if any(itag in component.tags for itag in self.include_tags):
                return True
            else:
                return False

        return True


@dataclass
class MountedServer:
    prefix: str | None
    server: FastMCP[Any]
    resource_prefix_format: Literal["protocol", "path"] | None = None


def add_resource_prefix(
    uri: str, prefix: str, prefix_format: Literal["protocol", "path"] | None = None
) -> str:
    """Add a prefix to a resource URI.

    Args:
        uri: The original resource URI
        prefix: The prefix to add

    Returns:
        The resource URI with the prefix added

    Examples:
        With new style:
        ```python
        add_resource_prefix("resource://path/to/resource", "prefix")
        "resource://prefix/path/to/resource"
        ```
        With legacy style:
        ```python
        add_resource_prefix("resource://path/to/resource", "prefix")
        "prefix+resource://path/to/resource"
        ```
        With absolute path:
        ```python
        add_resource_prefix("resource:///absolute/path", "prefix")
        "resource://prefix//absolute/path"
        ```

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    """
    if not prefix:
        return uri

    # Get the server settings to check for legacy format preference

    if prefix_format is None:
        prefix_format = fastmcp.settings.resource_prefix_format

    if prefix_format == "protocol":
        # Legacy style: prefix+protocol://path
        return f"{prefix}+{uri}"
    elif prefix_format == "path":
        # New style: protocol://prefix/path
        # Split the URI into protocol and path
        match = URI_PATTERN.match(uri)
        if not match:
            raise ValueError(
                f"Invalid URI format: {uri}. Expected protocol://path format."
            )

        protocol, path = match.groups()

        # Add the prefix to the path
        return f"{protocol}{prefix}/{path}"
    else:
        raise ValueError(f"Invalid prefix format: {prefix_format}")


def remove_resource_prefix(
    uri: str, prefix: str, prefix_format: Literal["protocol", "path"] | None = None
) -> str:
    """Remove a prefix from a resource URI.

    Args:
        uri: The resource URI with a prefix
        prefix: The prefix to remove
        prefix_format: The format of the prefix to remove
    Returns:
        The resource URI with the prefix removed

    Examples:
        With new style:
        ```python
        remove_resource_prefix("resource://prefix/path/to/resource", "prefix")
        "resource://path/to/resource"
        ```
        With legacy style:
        ```python
        remove_resource_prefix("prefix+resource://path/to/resource", "prefix")
        "resource://path/to/resource"
        ```
        With absolute path:
        ```python
        remove_resource_prefix("resource://prefix//absolute/path", "prefix")
        "resource:///absolute/path"
        ```

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    """
    if not prefix:
        return uri

    if prefix_format is None:
        prefix_format = fastmcp.settings.resource_prefix_format

    if prefix_format == "protocol":
        # Legacy style: prefix+protocol://path
        legacy_prefix = f"{prefix}+"
        if uri.startswith(legacy_prefix):
            return uri[len(legacy_prefix) :]
        return uri
    elif prefix_format == "path":
        # New style: protocol://prefix/path
        # Split the URI into protocol and path
        match = URI_PATTERN.match(uri)
        if not match:
            raise ValueError(
                f"Invalid URI format: {uri}. Expected protocol://path format."
            )

        protocol, path = match.groups()

        # Check if the path starts with the prefix followed by a /
        prefix_pattern = f"^{re.escape(prefix)}/(.*?)$"
        path_match = re.match(prefix_pattern, path)
        if not path_match:
            return uri

        # Return the URI without the prefix
        return f"{protocol}{path_match.group(1)}"
    else:
        raise ValueError(f"Invalid prefix format: {prefix_format}")


def has_resource_prefix(
    uri: str, prefix: str, prefix_format: Literal["protocol", "path"] | None = None
) -> bool:
    """Check if a resource URI has a specific prefix.

    Args:
        uri: The resource URI to check
        prefix: The prefix to look for

    Returns:
        True if the URI has the specified prefix, False otherwise

    Examples:
        With new style:
        ```python
        has_resource_prefix("resource://prefix/path/to/resource", "prefix")
        True
        ```
        With legacy style:
        ```python
        has_resource_prefix("prefix+resource://path/to/resource", "prefix")
        True
        ```
        With other path:
        ```python
        has_resource_prefix("resource://other/path/to/resource", "prefix")
        False
        ```

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    """
    if not prefix:
        return False

    # Get the server settings to check for legacy format preference

    if prefix_format is None:
        prefix_format = fastmcp.settings.resource_prefix_format

    if prefix_format == "protocol":
        # Legacy style: prefix+protocol://path
        legacy_prefix = f"{prefix}+"
        return uri.startswith(legacy_prefix)
    elif prefix_format == "path":
        # New style: protocol://prefix/path
        # Split the URI into protocol and path
        match = URI_PATTERN.match(uri)
        if not match:
            raise ValueError(
                f"Invalid URI format: {uri}. Expected protocol://path format."
            )

        _, path = match.groups()

        # Check if the path starts with the prefix followed by a /
        prefix_pattern = f"^{re.escape(prefix)}/"
        return bool(re.match(prefix_pattern, path))
    else:
        raise ValueError(f"Invalid prefix format: {prefix_format}")