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

import httpx
import pytest
from dirty_equals import IsStr
from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import PlainTextResponse
from httpx import ASGITransport, AsyncClient
from mcp.types import BlobResourceContents
from pydantic import BaseModel, TypeAdapter
from pydantic.networks import AnyUrl

from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.exceptions import ToolError
from fastmcp.server.openapi import (
    FastMCPOpenAPI,
    MCPType,
    OpenAPIResource,
    OpenAPIResourceTemplate,
    OpenAPITool,
    RouteMap,
)


class User(BaseModel):
    id: int
    name: str
    active: bool


class UserCreate(BaseModel):
    name: str
    active: bool


@pytest.fixture
def users_db() -> dict[int, User]:
    return {
        1: User(id=1, name="Alice", active=True),
        2: User(id=2, name="Bob", active=True),
        3: User(id=3, name="Charlie", active=False),
    }


# route maps for GET requests
# use these to create components of all types instead of just tools
GET_ROUTE_MAPS = [
    # GET requests with path parameters go to ResourceTemplate
    RouteMap(
        methods=["GET"],
        pattern=r".*\{.*\}.*",
        mcp_type=MCPType.RESOURCE_TEMPLATE,
    ),
    # GET requests without path parameters go to Resource
    RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
]


@pytest.fixture
def fastapi_app(users_db: dict[int, User]) -> FastAPI:
    app = FastAPI(title="FastAPI App")

    @app.get("/users", tags=["users", "list"])
    async def get_users() -> list[User]:
        """Get all users."""
        return sorted(users_db.values(), key=lambda x: x.id)

    @app.get("/search", tags=["search"])
    async def search_users(
        name: str | None = None, active: bool | None = None, min_id: int | None = None
    ) -> list[User]:
        """Search users with optional filters."""
        results = list(users_db.values())

        if name is not None:
            results = [u for u in results if name.lower() in u.name.lower()]
        if active is not None:
            results = [u for u in results if u.active == active]
        if min_id is not None:
            results = [u for u in results if u.id >= min_id]

        return sorted(results, key=lambda x: x.id)

    @app.get("/users/{user_id}", tags=["users", "detail"])
    async def get_user(user_id: int) -> User | None:
        """Get a user by ID."""
        return users_db.get(user_id)

    @app.get("/users/{user_id}/{is_active}", tags=["users", "detail"])
    async def get_user_active_state(user_id: int, is_active: bool) -> User | None:
        """Get a user by ID and filter by active state."""
        user = users_db.get(user_id)
        if user is not None and user.active == is_active:
            return user
        return None

    @app.post("/users", tags=["users", "create"])
    async def create_user(user: UserCreate) -> User:
        """Create a new user."""
        user_id = max(users_db.keys()) + 1
        new_user = User(id=user_id, **user.model_dump())
        users_db[user_id] = new_user
        return new_user

    @app.patch("/users/{user_id}/name", tags=["users", "update"])
    async def update_user_name(user_id: int, name: str) -> User:
        """Update a user's name."""
        user = users_db.get(user_id)
        if user is None:
            raise HTTPException(status_code=404, detail="User not found")
        user.name = name
        return user

    @app.get("/ping", response_class=PlainTextResponse)
    async def ping() -> str:
        """Ping the server."""
        return "pong"

    @app.get("/ping-bytes")
    async def ping_bytes() -> Response:
        """Ping the server and get a bytes response."""

        return Response(content=b"pong")

    return app


@pytest.fixture
def api_client(fastapi_app: FastAPI) -> AsyncClient:
    """Create a pre-configured httpx client for testing."""
    return AsyncClient(transport=ASGITransport(app=fastapi_app), base_url="http://test")


@pytest.fixture
async def fastmcp_openapi_server_with_all_types(
    fastapi_app: FastAPI, api_client: httpx.AsyncClient
) -> FastMCPOpenAPI:
    openapi_spec = fastapi_app.openapi()

    return FastMCPOpenAPI(
        openapi_spec=openapi_spec,
        client=api_client,
        name="Test App",
        route_maps=GET_ROUTE_MAPS,
    )


async def test_create_openapi_server(
    fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
    openapi_spec = fastapi_app.openapi()

    server = FastMCPOpenAPI(
        openapi_spec=openapi_spec, client=api_client, name="Test App"
    )

    assert isinstance(server, FastMCP)
    assert server.name == "Test App"


async def test_create_openapi_server_classmethod(
    fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
    server = FastMCP.from_openapi(openapi_spec=fastapi_app.openapi(), client=api_client)
    assert isinstance(server, FastMCPOpenAPI)
    assert server.name == "OpenAPI FastMCP"


async def test_create_fastapi_server_classmethod(fastapi_app: FastAPI):
    server = FastMCP.from_fastapi(fastapi_app)
    assert isinstance(server, FastMCPOpenAPI)
    assert server.name == "FastAPI App"


async def test_create_openapi_server_with_timeout(
    fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
    server = FastMCPOpenAPI(
        openapi_spec=fastapi_app.openapi(),
        client=api_client,
        name="Test App",
        timeout=1.0,
        route_maps=GET_ROUTE_MAPS,
    )
    assert server._timeout == 1.0

    for tool in (await server.get_tools()).values():
        assert isinstance(tool, OpenAPITool)
        assert tool._timeout == 1.0

    for resource in (await server.get_resources()).values():
        assert isinstance(resource, OpenAPIResource)
        assert resource._timeout == 1.0

    for template in (await server.get_resource_templates()).values():
        assert isinstance(template, OpenAPIResourceTemplate)
        assert template._timeout == 1.0


class TestTools:
    async def test_default_behavior_converts_everything_to_tools(
        self, fastapi_app: FastAPI
    ):
        """
        By default, tools exclude GET methods
        """
        server = FastMCPOpenAPI.from_fastapi(fastapi_app)
        assert len(await server.get_tools()) == 8
        assert len(await server.get_resources()) == 0
        assert len(await server.get_resource_templates()) == 0

    async def test_list_tools(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """
        By default, tools exclude GET methods
        """
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            tools = await client.list_tools()
        assert len(tools) == 2

        assert tools[0].model_dump() == dict(
            name="create_user_users_post",
            annotations=None,
            description=IsStr(regex=r"^Create a new user\..*$", regex_flags=re.DOTALL),
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string", "title": "Name"},
                    "active": {"type": "boolean", "title": "Active"},
                },
                "required": ["name", "active"],
            },
        )
        assert tools[1].model_dump() == dict(
            name="update_user_name_users",
            annotations=None,
            description=IsStr(
                regex=r"^Update a user's name\..*$", regex_flags=re.DOTALL
            ),
            inputSchema={
                "type": "object",
                "properties": {
                    "user_id": {"type": "integer", "title": "User Id"},
                    "name": {"type": "string", "title": "Name"},
                },
                "required": ["user_id", "name"],
            },
        )

    async def test_call_create_user_tool(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
    ):
        """
        The tool created by the OpenAPI server should be the same as the original
        """
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            tool_response = await client.call_tool(
                "create_user_users_post", {"name": "David", "active": False}
            )

        response_data = json.loads(tool_response[0].text)  # type: ignore[attr-defined]
        expected_user = User(id=4, name="David", active=False).model_dump()
        assert response_data == expected_user

        # Check that the user was created via API
        response = await api_client.get("/users")
        assert len(response.json()) == 4

        # Check that the user was created via MCP
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            user_response = await client.read_resource("resource://get_user_users/4")
            response_text = user_response[0].text  # type: ignore[attr-defined]
            user = json.loads(response_text)
        assert user == expected_user

    async def test_call_update_user_name_tool(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
    ):
        """
        The tool created by the OpenAPI server should be the same as the original
        """
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            tool_response = await client.call_tool(
                "update_user_name_users",
                {"user_id": 1, "name": "XYZ"},
            )

        response_data = json.loads(tool_response[0].text)  # type: ignore[attr-defined]
        expected_data = dict(id=1, name="XYZ", active=True)
        assert response_data == expected_data

        # Check that the user was updated via API
        response = await api_client.get("/users")
        assert expected_data in response.json()

        # Check that the user was updated via MCP
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            user_response = await client.read_resource("resource://get_user_users/1")
            response_text = user_response[0].text  # type: ignore[attr-defined]
            user = json.loads(response_text)
        assert user == expected_data

    async def test_call_tool_return_list(
        self,
        fastapi_app: FastAPI,
        api_client: httpx.AsyncClient,
        users_db: dict[int, User],
    ):
        """
        The tool created by the OpenAPI server should return a list of content.
        """
        openapi_spec = fastapi_app.openapi()
        mcp_server = FastMCPOpenAPI(
            openapi_spec=openapi_spec,
            client=api_client,
            route_maps=[
                RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.TOOL)
            ],
        )
        async with Client(mcp_server) as client:
            tool_response = await client.call_tool("get_users_users_get", {})
            assert json.loads(tool_response[0].text) == [  # type: ignore[attr-defined]
                user.model_dump()
                for user in sorted(users_db.values(), key=lambda x: x.id)
            ]


class TestResources:
    async def test_list_resources(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """
        By default, resources exclude GET methods without parameters
        """
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resources = await client.list_resources()
        assert len(resources) == 4
        assert resources[0].uri == AnyUrl("resource://get_users_users_get")
        assert resources[0].name == "get_users_users_get"

    async def test_get_resource(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
        users_db: dict[int, User],
    ):
        """
        The resource created by the OpenAPI server should be the same as the original
        """

        json_users = TypeAdapter(list[User]).dump_python(
            sorted(users_db.values(), key=lambda x: x.id)
        )
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resource_response = await client.read_resource(
                "resource://get_users_users_get"
            )
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            resource = json.loads(response_text)
        assert resource == json_users
        response = await api_client.get("/users")
        assert response.json() == json_users

    async def test_get_bytes_resource(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
    ):
        """Test reading a resource that returns bytes."""
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resource_response = await client.read_resource(
                "resource://ping_bytes_ping_bytes_get"
            )
            assert isinstance(resource_response[0], BlobResourceContents)
            assert base64.b64decode(resource_response[0].blob) == b"pong"

    async def test_get_str_resource(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
    ):
        """Test reading a resource that returns a string."""
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resource_response = await client.read_resource("resource://ping_ping_get")
            assert resource_response[0].text == "pong"  # type: ignore[attr-defined]


class TestResourceTemplates:
    async def test_list_resource_templates(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """
        By default, resource templates exclude GET methods without parameters
        """
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resource_templates = await client.list_resource_templates()
        assert len(resource_templates) == 2
        assert resource_templates[0].name == "get_user_users"
        assert (
            resource_templates[0].uriTemplate == r"resource://get_user_users/{user_id}"
        )
        assert resource_templates[1].name == "get_user_active_state_users"
        assert (
            resource_templates[1].uriTemplate
            == r"resource://get_user_active_state_users/{is_active}/{user_id}"
        )

    async def test_get_resource_template(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
        users_db: dict[int, User],
    ):
        """
        The resource template created by the OpenAPI server should be the same as the original
        """
        user_id = 2
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resource_response = await client.read_resource(
                f"resource://get_user_users/{user_id}"
            )
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            resource = json.loads(response_text)

        assert resource == users_db[user_id].model_dump()
        response = await api_client.get(f"/users/{user_id}")
        assert resource == response.json()

    async def test_get_resource_template_multi_param(
        self,
        fastmcp_openapi_server_with_all_types: FastMCPOpenAPI,
        api_client,
        users_db: dict[int, User],
    ):
        """
        The resource template created by the OpenAPI server should be the same as the original
        """
        user_id = 2
        is_active = True
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            resource_response = await client.read_resource(
                f"resource://get_user_active_state_users/{is_active}/{user_id}"
            )
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            resource = json.loads(response_text)

        assert resource == users_db[user_id].model_dump()
        response = await api_client.get(f"/users/{user_id}/{is_active}")
        assert resource == response.json()


class TestPrompts:
    async def test_list_prompts(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """
        By default, there are no prompts.
        """
        async with Client(fastmcp_openapi_server_with_all_types) as client:
            prompts = await client.list_prompts()
        assert len(prompts) == 0


class TestTagTransfer:
    """Tests for transferring tags from OpenAPI routes to MCP objects."""

    async def test_tags_transferred_to_tools(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that tags from OpenAPI routes are correctly transferred to Tools."""
        # Get internal tools directly (not the public API which returns MCP.Content)
        tools = fastmcp_openapi_server_with_all_types._tool_manager.list_tools()

        # Find the create_user and update_user_name tools
        create_user_tool = next(
            (t for t in tools if t.name == "create_user_users_post"), None
        )
        update_user_tool = next(
            (t for t in tools if t.name == "update_user_name_users"),
            None,
        )

        assert create_user_tool is not None
        assert update_user_tool is not None

        # Check that tags from OpenAPI routes were transferred to the Tool objects
        assert "users" in create_user_tool.tags
        assert "create" in create_user_tool.tags
        assert len(create_user_tool.tags) == 2

        assert "users" in update_user_tool.tags
        assert "update" in update_user_tool.tags
        assert len(update_user_tool.tags) == 2

    async def test_tags_transferred_to_resources(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that tags from OpenAPI routes are correctly transferred to Resources."""
        # Get internal resources directly
        resources = list(
            fastmcp_openapi_server_with_all_types._resource_manager.get_resources().values()
        )

        # Find the get_users resource
        get_users_resource = next(
            (r for r in resources if r.name == "get_users_users_get"), None
        )

        assert get_users_resource is not None

        # Check that tags from OpenAPI routes were transferred to the Resource object
        assert "users" in get_users_resource.tags
        assert "list" in get_users_resource.tags
        assert len(get_users_resource.tags) == 2

    async def test_tags_transferred_to_resource_templates(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that tags from OpenAPI routes are correctly transferred to ResourceTemplates."""
        # Get internal resource templates directly
        templates = list(
            fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
        )

        # Find the get_user template
        get_user_template = next(
            (t for t in templates if t.name == "get_user_users"), None
        )

        assert get_user_template is not None

        # Check that tags from OpenAPI routes were transferred to the ResourceTemplate object
        assert "users" in get_user_template.tags
        assert "detail" in get_user_template.tags
        assert len(get_user_template.tags) == 2

    async def test_tags_preserved_in_resources_created_from_templates(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that tags are preserved when creating resources from templates."""
        # Get internal resource templates directly
        templates = list(
            fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
        )

        # Find the get_user template
        get_user_template = next(
            (t for t in templates if t.name == "get_user_users"), None
        )

        assert get_user_template is not None

        # Manually create a resource from template
        params = {"user_id": 1}
        resource = await get_user_template.create_resource(
            "resource://get_user_users/1", params
        )

        # Verify tags are preserved from template to resource
        assert "users" in resource.tags
        assert "detail" in resource.tags
        assert len(resource.tags) == 2


class TestOpenAPI30Compatibility:
    """Tests for compatibility with OpenAPI 3.0 specifications."""

    @pytest.fixture
    def openapi_30_spec(self) -> dict:
        """Fixture that returns a simple OpenAPI 3.0 specification."""
        return {
            "openapi": "3.0.0",
            "info": {"title": "Product API (3.0)", "version": "1.0.0"},
            "paths": {
                "/products": {
                    "get": {
                        "operationId": "listProducts",
                        "summary": "List all products",
                        "responses": {"200": {"description": "A list of products"}},
                    },
                    "post": {
                        "operationId": "createProduct",
                        "summary": "Create a new product",
                        "requestBody": {
                            "required": True,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "name": {"type": "string"},
                                            "price": {"type": "number"},
                                        },
                                        "required": ["name", "price"],
                                    }
                                }
                            },
                        },
                        "responses": {"201": {"description": "Product created"}},
                    },
                },
                "/products/{product_id}": {
                    "get": {
                        "operationId": "getProduct",
                        "summary": "Get product by ID",
                        "parameters": [
                            {
                                "name": "product_id",
                                "in": "path",
                                "required": True,
                                "schema": {"type": "string"},
                            }
                        ],
                        "responses": {"200": {"description": "A product"}},
                    }
                },
            },
        }

    @pytest.fixture
    async def mock_30_client(self) -> httpx.AsyncClient:
        """Mock client that returns predefined responses for the 3.0 API."""

        async def _responder(request):
            if request.url.path == "/products" and request.method == "GET":
                return httpx.Response(
                    200,
                    json=[
                        {"id": "p1", "name": "Product 1", "price": 19.99},
                        {"id": "p2", "name": "Product 2", "price": 29.99},
                    ],
                )
            elif request.url.path == "/products" and request.method == "POST":
                import json

                data = json.loads(request.content)
                return httpx.Response(
                    201, json={"id": "p3", "name": data["name"], "price": data["price"]}
                )
            elif request.url.path.startswith("/products/") and request.method == "GET":
                product_id = request.url.path.split("/")[-1]
                products = {
                    "p1": {"id": "p1", "name": "Product 1", "price": 19.99},
                    "p2": {"id": "p2", "name": "Product 2", "price": 29.99},
                }
                if product_id in products:
                    return httpx.Response(200, json=products[product_id])
                return httpx.Response(404, json={"error": "Product not found"})
            return httpx.Response(404)

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    @pytest.fixture
    async def openapi_30_server_with_all_types(
        self, openapi_30_spec, mock_30_client
    ) -> FastMCPOpenAPI:
        """Create a FastMCPOpenAPI server from the OpenAPI 3.0 spec."""
        return FastMCPOpenAPI(
            openapi_spec=openapi_30_spec,
            client=mock_30_client,
            name="Product API 3.0",
            route_maps=GET_ROUTE_MAPS,
        )

    async def test_server_creation(self, openapi_30_server_with_all_types):
        """Test that a server can be created from an OpenAPI 3.0 spec."""
        assert isinstance(openapi_30_server_with_all_types, FastMCP)
        assert openapi_30_server_with_all_types.name == "Product API 3.0"

    async def test_resource_discovery(self, openapi_30_server_with_all_types):
        """Test that resources are correctly discovered from an OpenAPI 3.0 spec."""
        async with Client(openapi_30_server_with_all_types) as client:
            resources = await client.list_resources()
        assert len(resources) == 1
        assert resources[0].uri == AnyUrl("resource://listProducts")

    async def test_resource_template_discovery(self, openapi_30_server_with_all_types):
        """Test that resource templates are correctly discovered from an OpenAPI 3.0 spec."""
        async with Client(openapi_30_server_with_all_types) as client:
            templates = await client.list_resource_templates()
        assert len(templates) == 1
        assert templates[0].name == "getProduct"
        assert templates[0].uriTemplate == r"resource://getProduct/{product_id}"

    async def test_tool_discovery(self, openapi_30_server_with_all_types):
        """Test that tools are correctly discovered from an OpenAPI 3.0 spec."""
        async with Client(openapi_30_server_with_all_types) as client:
            tools = await client.list_tools()
        assert len(tools) == 1
        assert tools[0].name == "createProduct"
        assert "name" in tools[0].inputSchema["properties"]
        assert "price" in tools[0].inputSchema["properties"]

    async def test_resource_access(self, openapi_30_server_with_all_types):
        """Test reading a resource from an OpenAPI 3.0 server."""
        async with Client(openapi_30_server_with_all_types) as client:
            resource_response = await client.read_resource("resource://listProducts")
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            content = json.loads(response_text)
        assert len(content) == 2
        assert content[0]["name"] == "Product 1"
        assert content[1]["name"] == "Product 2"

    async def test_resource_template_access(self, openapi_30_server_with_all_types):
        """Test reading a resource from template from an OpenAPI 3.0 server."""
        async with Client(openapi_30_server_with_all_types) as client:
            resource_response = await client.read_resource("resource://getProduct/p1")
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            content = json.loads(response_text)
        assert content["id"] == "p1"
        assert content["name"] == "Product 1"
        assert content["price"] == 19.99

    async def test_tool_execution(self, openapi_30_server_with_all_types):
        """Test executing a tool from an OpenAPI 3.0 server."""
        async with Client(openapi_30_server_with_all_types) as client:
            result = await client.call_tool(
                "createProduct", {"name": "New Product", "price": 39.99}
            )
            # Result should be a text content
            assert len(result) == 1
            product = json.loads(result[0].text)  # type: ignore[attr-defined]
            assert product["id"] == "p3"
            assert product["name"] == "New Product"
            assert product["price"] == 39.99


class TestOpenAPI31Compatibility:
    """Tests for compatibility with OpenAPI 3.1 specifications."""

    @pytest.fixture
    def openapi_31_spec(self) -> dict:
        """Fixture that returns a simple OpenAPI 3.1 specification."""
        return {
            "openapi": "3.1.0",
            "info": {"title": "Order API (3.1)", "version": "1.0.0"},
            "paths": {
                "/orders": {
                    "get": {
                        "operationId": "listOrders",
                        "summary": "List all orders",
                        "responses": {"200": {"description": "A list of orders"}},
                    },
                    "post": {
                        "operationId": "createOrder",
                        "summary": "Place a new order",
                        "requestBody": {
                            "required": True,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "customer": {"type": "string"},
                                            "items": {
                                                "type": "array",
                                                "items": {"type": "string"},
                                            },
                                        },
                                        "required": ["customer", "items"],
                                    }
                                }
                            },
                        },
                        "responses": {"201": {"description": "Order created"}},
                    },
                },
                "/orders/{order_id}": {
                    "get": {
                        "operationId": "getOrder",
                        "summary": "Get order by ID",
                        "parameters": [
                            {
                                "name": "order_id",
                                "in": "path",
                                "required": True,
                                "schema": {"type": "string"},
                            }
                        ],
                        "responses": {"200": {"description": "An order"}},
                    }
                },
            },
        }

    @pytest.fixture
    async def mock_31_client(self) -> httpx.AsyncClient:
        """Mock client that returns predefined responses for the 3.1 API."""

        async def _responder(request):
            if request.url.path == "/orders" and request.method == "GET":
                return httpx.Response(
                    200,
                    json=[
                        {"id": "o1", "customer": "Alice", "items": ["item1", "item2"]},
                        {"id": "o2", "customer": "Bob", "items": ["item3"]},
                    ],
                )
            elif request.url.path == "/orders" and request.method == "POST":
                import json

                data = json.loads(request.content)
                return httpx.Response(
                    201,
                    json={
                        "id": "o3",
                        "customer": data["customer"],
                        "items": data["items"],
                    },
                )
            elif request.url.path.startswith("/orders/") and request.method == "GET":
                order_id = request.url.path.split("/")[-1]
                orders = {
                    "o1": {
                        "id": "o1",
                        "customer": "Alice",
                        "items": ["item1", "item2"],
                    },
                    "o2": {"id": "o2", "customer": "Bob", "items": ["item3"]},
                }
                if order_id in orders:
                    return httpx.Response(200, json=orders[order_id])
                return httpx.Response(404, json={"error": "Order not found"})
            return httpx.Response(404)

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    @pytest.fixture
    async def openapi_31_server_with_all_types(
        self, openapi_31_spec, mock_31_client
    ) -> FastMCPOpenAPI:
        """Create a FastMCPOpenAPI server from the OpenAPI 3.1 spec."""
        return FastMCPOpenAPI(
            openapi_spec=openapi_31_spec,
            client=mock_31_client,
            name="Order API 3.1",
            route_maps=GET_ROUTE_MAPS,
        )

    async def test_server_creation(self, openapi_31_server_with_all_types):
        """Test that a server can be created from an OpenAPI 3.1 spec."""
        assert isinstance(openapi_31_server_with_all_types, FastMCP)
        assert openapi_31_server_with_all_types.name == "Order API 3.1"

    async def test_resource_discovery(self, openapi_31_server_with_all_types):
        """Test that resources are correctly discovered from an OpenAPI 3.1 spec."""
        async with Client(openapi_31_server_with_all_types) as client:
            resources = await client.list_resources()
        assert len(resources) == 1
        assert resources[0].uri == AnyUrl("resource://listOrders")

    async def test_resource_template_discovery(self, openapi_31_server_with_all_types):
        """Test that resource templates are correctly discovered from an OpenAPI 3.1 spec."""
        async with Client(openapi_31_server_with_all_types) as client:
            templates = await client.list_resource_templates()
        assert len(templates) == 1
        assert templates[0].name == "getOrder"
        assert templates[0].uriTemplate == r"resource://getOrder/{order_id}"

    async def test_tool_discovery(self, openapi_31_server_with_all_types):
        """Test that tools are correctly discovered from an OpenAPI 3.1 spec."""
        async with Client(openapi_31_server_with_all_types) as client:
            tools = await client.list_tools()
        assert len(tools) == 1
        assert tools[0].name == "createOrder"
        assert "customer" in tools[0].inputSchema["properties"]
        assert "items" in tools[0].inputSchema["properties"]

    async def test_resource_access(self, openapi_31_server_with_all_types):
        """Test reading a resource from an OpenAPI 3.1 server."""
        async with Client(openapi_31_server_with_all_types) as client:
            resource_response = await client.read_resource("resource://listOrders")
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            content = json.loads(response_text)
        assert len(content) == 2
        assert content[0]["customer"] == "Alice"
        assert content[1]["customer"] == "Bob"

    async def test_resource_template_access(self, openapi_31_server_with_all_types):
        """Test reading a resource from template from an OpenAPI 3.1 server."""
        async with Client(openapi_31_server_with_all_types) as client:
            resource_response = await client.read_resource("resource://getOrder/o1")
            response_text = resource_response[0].text  # type: ignore[attr-defined]
            content = json.loads(response_text)
        assert content["id"] == "o1"
        assert content["customer"] == "Alice"
        assert content["items"] == ["item1", "item2"]

    async def test_tool_execution(self, openapi_31_server_with_all_types):
        """Test executing a tool from an OpenAPI 3.1 server."""
        async with Client(openapi_31_server_with_all_types) as client:
            result = await client.call_tool(
                "createOrder", {"customer": "Charlie", "items": ["item4", "item5"]}
            )
            # Result should be a text content
            assert len(result) == 1
            order = json.loads(result[0].text)  # type: ignore[attr-dict]
            assert order["id"] == "o3"
            assert order["customer"] == "Charlie"
            assert order["items"] == ["item4", "item5"]


class TestMountFastMCP:
    """Tests for mounting FastMCP servers."""

    async def test_mount_fastmcp(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test mounting an OpenAPI server."""
        mcp = FastMCP("MainApp")

        await mcp.import_server("fastapi", fastmcp_openapi_server_with_all_types)

        # Check that resources are available with prefixed URIs
        async with Client(mcp) as client:
            resources = await client.list_resources()
        assert len(resources) == 4  # Updated to account for new search endpoint
        # We're checking the key used by mcp to store the resource
        # The prefixed URI is used as the key, but the resource's original uri is preserved
        prefixed_uri = "resource://fastapi/get_users_users_get"
        resource = mcp._resource_manager.get_resources().get(prefixed_uri)
        assert resource is not None


async def test_empty_query_parameters_not_sent(
    fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
    """Test that empty and None query parameters are not sent in the request."""

    # Create a TransportAdapter to track requests
    class RequestCapture(httpx.AsyncBaseTransport):
        def __init__(self, wrapped):
            self.wrapped = wrapped
            self.requests = []

        async def handle_async_request(self, request):
            self.requests.append(request)
            return await self.wrapped.handle_async_request(request)

    # Use our transport adapter to wrap the original one
    capture = RequestCapture(api_client._transport)
    api_client._transport = capture

    # Create the OpenAPI server with new route map to make search endpoint a tool
    openapi_spec = fastapi_app.openapi()
    mcp_server = FastMCPOpenAPI(
        openapi_spec=openapi_spec,
        client=api_client,
        route_maps=[RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.TOOL)],
    )

    # Call the search tool with mixed parameter values
    async with Client(mcp_server) as client:
        await client.call_tool(
            "search_users_search_get",
            {
                "name": "",  # Empty string should be excluded
                "active": None,  # None should be excluded
                "min_id": 2,  # Has value, should be included
            },
        )

    # Verify that the request URL only has min_id parameter
    assert len(capture.requests) > 0
    request = capture.requests[-1]  # Get the last request

    # URL should only contain min_id=2, not name= or active=
    url = str(request.url)
    assert "min_id=2" in url, f"URL should contain min_id=2, got: {url}"
    assert "name=" not in url, f"URL should not contain name=, got: {url}"
    assert "active=" not in url, f"URL should not contain active=, got: {url}"

    # More direct check - parse the URL to examine query params
    from urllib.parse import parse_qs, urlparse

    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)

    assert "min_id" in query_params
    assert "name" not in query_params
    assert "active" not in query_params


async def test_none_path_parameters_rejected(
    fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
    """Test that None values for path parameters are properly rejected."""
    # Create the OpenAPI server
    openapi_spec = fastapi_app.openapi()
    mcp_server = FastMCPOpenAPI(
        openapi_spec=openapi_spec,
        client=api_client,
    )

    # Create a client and try to call a tool with a None path parameter
    async with Client(mcp_server) as client:
        # get_user has a required path parameter user_id
        with pytest.raises(ToolError, match="Missing required path parameters"):
            await client.call_tool(
                "update_user_name_users",
                {
                    "user_id": None,  # This should cause an error
                    "name": "New Name",
                },
            )


class TestDescriptionPropagation:
    """Tests for OpenAPI description propagation to FastMCP components.

    Each test focuses on a single, specific behavior to make it immediately clear
    what's broken when a test fails.
    """

    @pytest.fixture
    def simple_openapi_spec(self) -> dict:
        """Create a minimal OpenAPI spec with obvious test descriptions."""
        return {
            "openapi": "3.1.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/items": {
                    "get": {
                        "operationId": "listItems",
                        "summary": "List items summary",
                        "description": "LIST_DESCRIPTION\n\nFUNCTION_LIST_DESCRIPTION",
                        "responses": {
                            "200": {
                                "description": "LIST_RESPONSE_DESCRIPTION",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "array",
                                            "items": {
                                                "type": "object",
                                                "properties": {
                                                    "id": {
                                                        "type": "string",
                                                        "description": "ITEM_RESPONSE_ID_DESCRIPTION",
                                                    },
                                                    "name": {
                                                        "type": "string",
                                                        "description": "ITEM_RESPONSE_NAME_DESCRIPTION",
                                                    },
                                                    "price": {
                                                        "type": "number",
                                                        "description": "ITEM_RESPONSE_PRICE_DESCRIPTION",
                                                    },
                                                },
                                            },
                                        },
                                    }
                                },
                            }
                        },
                    }
                },
                "/items/{item_id}": {
                    "get": {
                        "operationId": "getItem",
                        "summary": "Get item summary",
                        "description": "GET_DESCRIPTION\n\nFUNCTION_GET_DESCRIPTION",
                        "parameters": [
                            {
                                "name": "item_id",
                                "in": "path",
                                "required": True,
                                "description": "PATH_PARAM_DESCRIPTION",
                                "schema": {"type": "string"},
                            },
                            {
                                "name": "fields",
                                "in": "query",
                                "required": False,
                                "description": "QUERY_PARAM_DESCRIPTION",
                                "schema": {"type": "string"},
                            },
                        ],
                        "responses": {
                            "200": {
                                "description": "GET_RESPONSE_DESCRIPTION",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "properties": {
                                                "id": {
                                                    "type": "string",
                                                    "description": "ITEM_RESPONSE_ID_DESCRIPTION",
                                                },
                                                "name": {
                                                    "type": "string",
                                                    "description": "ITEM_RESPONSE_NAME_DESCRIPTION",
                                                },
                                                "price": {
                                                    "type": "number",
                                                    "description": "ITEM_RESPONSE_PRICE_DESCRIPTION",
                                                },
                                            },
                                        },
                                    }
                                },
                            }
                        },
                    }
                },
                "/items/create": {
                    "post": {
                        "operationId": "createItem",
                        "summary": "Create item summary",
                        "description": "CREATE_DESCRIPTION\n\nFUNCTION_CREATE_DESCRIPTION",
                        "requestBody": {
                            "required": True,
                            "description": "BODY_DESCRIPTION",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "name": {
                                                "type": "string",
                                                "description": "PROP_DESCRIPTION",
                                            }
                                        },
                                        "required": ["name"],
                                    }
                                }
                            },
                        },
                        "responses": {
                            "201": {
                                "description": "CREATE_RESPONSE_DESCRIPTION",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "properties": {
                                                "id": {
                                                    "type": "string",
                                                    "description": "ITEM_RESPONSE_ID_DESCRIPTION",
                                                },
                                                "name": {
                                                    "type": "string",
                                                    "description": "ITEM_RESPONSE_NAME_DESCRIPTION",
                                                },
                                            },
                                        },
                                    }
                                },
                            }
                        },
                    }
                },
            },
        }

    @pytest.fixture
    async def mock_client(self) -> httpx.AsyncClient:
        """Create a mock client that returns simple responses."""

        async def _responder(request):
            if request.url.path == "/items" and request.method == "GET":
                return httpx.Response(200, json=[{"id": "1", "name": "Item 1"}])
            elif request.url.path.startswith("/items/") and request.method == "GET":
                item_id = request.url.path.split("/")[-1]
                return httpx.Response(
                    200, json={"id": item_id, "name": f"Item {item_id}"}
                )
            elif request.url.path == "/items/create" and request.method == "POST":
                import json

                data = json.loads(request.content)
                return httpx.Response(201, json={"id": "new", "name": data.get("name")})

            return httpx.Response(404)

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    @pytest.fixture
    async def simple_server_with_all_types(self, simple_openapi_spec, mock_client):
        """Create a FastMCPOpenAPI server with the simple test spec."""
        return FastMCPOpenAPI(
            openapi_spec=simple_openapi_spec,
            client=mock_client,
            name="Test API",
            route_maps=GET_ROUTE_MAPS,
        )

    # --- RESOURCE TESTS ---

    async def test_resource_includes_route_description(
        self, simple_server_with_all_types
    ):
        """Test that a Resource includes the route description."""
        resources = list(
            simple_server_with_all_types._resource_manager.get_resources().values()
        )
        list_resource = next((r for r in resources if r.name == "listItems"), None)

        assert list_resource is not None, "listItems resource wasn't created"
        assert "LIST_DESCRIPTION" in (list_resource.description or ""), (
            "Route description missing from Resource"
        )

    async def test_resource_includes_response_description(
        self, simple_server_with_all_types
    ):
        """Test that a Resource includes the response description."""
        resources = list(
            simple_server_with_all_types._resource_manager.get_resources().values()
        )
        list_resource = next((r for r in resources if r.name == "listItems"), None)

        assert list_resource is not None, "listItems resource wasn't created"
        assert "LIST_RESPONSE_DESCRIPTION" in (list_resource.description or ""), (
            "Response description missing from Resource"
        )

    async def test_resource_includes_response_model_fields(
        self, simple_server_with_all_types
    ):
        """Test that a Resource description includes response model field descriptions."""
        resources = list(
            simple_server_with_all_types._resource_manager.get_resources().values()
        )
        list_resource = next((r for r in resources if r.name == "listItems"), None)

        assert list_resource is not None, "listItems resource wasn't created"
        description = list_resource.description or ""
        assert "ITEM_RESPONSE_ID_DESCRIPTION" in description, (
            "Response model field descriptions missing from Resource description"
        )
        assert "ITEM_RESPONSE_NAME_DESCRIPTION" in description, (
            "Response model field descriptions missing from Resource description"
        )
        assert "ITEM_RESPONSE_PRICE_DESCRIPTION" in description, (
            "Response model field descriptions missing from Resource description"
        )

    # --- RESOURCE TEMPLATE TESTS ---

    async def test_template_includes_route_description(
        self, simple_server_with_all_types
    ):
        """Test that a ResourceTemplate includes the route description."""
        templates = list(
            simple_server_with_all_types._resource_manager.get_templates().values()
        )
        get_template = next((t for t in templates if t.name == "getItem"), None)

        assert get_template is not None, "getItem template wasn't created"
        assert "GET_DESCRIPTION" in (get_template.description or ""), (
            "Route description missing from ResourceTemplate"
        )

    async def test_template_includes_function_docstring(
        self, simple_server_with_all_types
    ):
        """Test that a ResourceTemplate includes the function docstring."""
        templates = list(
            simple_server_with_all_types._resource_manager.get_templates().values()
        )
        get_template = next((t for t in templates if t.name == "getItem"), None)

        assert get_template is not None, "getItem template wasn't created"
        assert "FUNCTION_GET_DESCRIPTION" in (get_template.description or ""), (
            "Function docstring missing from ResourceTemplate"
        )

    async def test_template_includes_path_parameter_description(
        self, simple_server_with_all_types
    ):
        """Test that a ResourceTemplate includes path parameter descriptions."""
        templates = list(
            simple_server_with_all_types._resource_manager.get_templates().values()
        )
        get_template = next((t for t in templates if t.name == "getItem"), None)

        assert get_template is not None, "getItem template wasn't created"
        assert "PATH_PARAM_DESCRIPTION" in (get_template.description or ""), (
            "Path parameter description missing from ResourceTemplate description"
        )

    async def test_template_includes_query_parameter_description(
        self, simple_server_with_all_types
    ):
        """Test that a ResourceTemplate includes query parameter descriptions."""
        templates = list(
            simple_server_with_all_types._resource_manager.get_templates().values()
        )
        get_template = next((t for t in templates if t.name == "getItem"), None)

        assert get_template is not None, "getItem template wasn't created"
        assert "QUERY_PARAM_DESCRIPTION" in (get_template.description or ""), (
            "Query parameter description missing from ResourceTemplate description"
        )

    async def test_template_parameter_schema_includes_description(
        self, simple_server_with_all_types
    ):
        """Test that a ResourceTemplate's parameter schema includes parameter descriptions."""
        templates = list(
            simple_server_with_all_types._resource_manager.get_templates().values()
        )
        get_template = next((t for t in templates if t.name == "getItem"), None)

        assert get_template is not None, "getItem template wasn't created"
        assert "properties" in get_template.parameters, (
            "Schema properties missing from ResourceTemplate"
        )
        assert "item_id" in get_template.parameters["properties"], (
            "item_id missing from ResourceTemplate schema"
        )
        assert "description" in get_template.parameters["properties"]["item_id"], (
            "Description missing from item_id parameter schema"
        )
        assert (
            "PATH_PARAM_DESCRIPTION"
            in get_template.parameters["properties"]["item_id"]["description"]
        ), "Path parameter description incorrect in schema"

    # --- TOOL TESTS ---

    async def test_tool_includes_route_description(self, simple_server_with_all_types):
        """Test that a Tool includes the route description."""
        tools = simple_server_with_all_types._tool_manager.list_tools()
        create_tool = next((t for t in tools if t.name == "createItem"), None)

        assert create_tool is not None, "createItem tool wasn't created"
        assert "CREATE_DESCRIPTION" in (create_tool.description or ""), (
            "Route description missing from Tool"
        )

    async def test_tool_includes_function_docstring(self, simple_server_with_all_types):
        """Test that a Tool includes the function docstring."""
        tools = simple_server_with_all_types._tool_manager.list_tools()
        create_tool = next((t for t in tools if t.name == "createItem"), None)

        assert create_tool is not None, "createItem tool wasn't created"
        description = create_tool.description or ""
        assert "FUNCTION_CREATE_DESCRIPTION" in description, (
            "Function docstring missing from Tool"
        )

    async def test_tool_parameter_schema_includes_property_description(
        self, simple_server_with_all_types
    ):
        """Test that a Tool's parameter schema includes property descriptions from request model."""
        tools = simple_server_with_all_types._tool_manager.list_tools()
        create_tool = next((t for t in tools if t.name == "createItem"), None)

        assert create_tool is not None, "createItem tool wasn't created"
        assert "properties" in create_tool.parameters, (
            "Schema properties missing from Tool"
        )
        assert "name" in create_tool.parameters["properties"], (
            "name parameter missing from Tool schema"
        )
        assert "description" in create_tool.parameters["properties"]["name"], (
            "Description missing from name parameter schema"
        )
        assert (
            "PROP_DESCRIPTION"
            in create_tool.parameters["properties"]["name"]["description"]
        ), "Property description incorrect in schema"

    # --- CLIENT API TESTS ---

    async def test_client_api_resource_description(self, simple_server_with_all_types):
        """Test that Resource descriptions are accessible via the client API."""
        async with Client(simple_server_with_all_types) as client:
            resources = await client.list_resources()
            list_resource = next((r for r in resources if r.name == "listItems"), None)

            assert list_resource is not None, (
                "listItems resource not accessible via client API"
            )
            resource_description = list_resource.description or ""
            assert "LIST_DESCRIPTION" in resource_description, (
                "Route description missing in Resource from client API"
            )

    async def test_client_api_template_description(self, simple_server_with_all_types):
        """Test that ResourceTemplate descriptions are accessible via the client API."""
        async with Client(simple_server_with_all_types) as client:
            templates = await client.list_resource_templates()
            get_template = next((t for t in templates if t.name == "getItem"), None)

            assert get_template is not None, (
                "getItem template not accessible via client API"
            )
            template_description = get_template.description or ""
            assert "GET_DESCRIPTION" in template_description, (
                "Route description missing in ResourceTemplate from client API"
            )

    async def test_client_api_tool_description(self, simple_server_with_all_types):
        """Test that Tool descriptions are accessible via the client API."""
        async with Client(simple_server_with_all_types) as client:
            tools = await client.list_tools()
            create_tool = next((t for t in tools if t.name == "createItem"), None)

            assert create_tool is not None, (
                "createItem tool not accessible via client API"
            )
            tool_description = create_tool.description or ""
            assert "FUNCTION_CREATE_DESCRIPTION" in tool_description, (
                "Function docstring missing in Tool from client API"
            )

    async def test_client_api_tool_parameter_schema(self, simple_server_with_all_types):
        """Test that Tool parameter schemas are accessible via the client API."""
        async with Client(simple_server_with_all_types) as client:
            tools = await client.list_tools()
            create_tool = next((t for t in tools if t.name == "createItem"), None)

            assert create_tool is not None, (
                "createItem tool not accessible via client API"
            )
            assert "properties" in create_tool.inputSchema, (
                "Schema properties missing from Tool inputSchema in client API"
            )
            assert "name" in create_tool.inputSchema["properties"], (
                "name parameter missing from Tool schema in client API"
            )
            assert "description" in create_tool.inputSchema["properties"]["name"], (
                "Description missing from name parameter in client API"
            )
            assert (
                "PROP_DESCRIPTION"
                in create_tool.inputSchema["properties"]["name"]["description"]
            ), "Property description incorrect in schema from client API"


class TestFastAPIDescriptionPropagation:
    """Tests for FastAPI docstring and annotation propagation to FastMCP components.

    Each test focuses on a single, specific behavior to make it immediately clear
    what's broken when a test fails.
    """

    @pytest.fixture
    def fastapi_app_with_descriptions(self) -> FastAPI:
        """Create a simple FastAPI app with docstrings and annotations."""
        from typing import Annotated

        from pydantic import BaseModel, Field

        app = FastAPI(title="Test FastAPI App")

        class Item(BaseModel):
            name: str = Field(..., description="ITEM_NAME_DESCRIPTION")
            price: float = Field(..., description="ITEM_PRICE_DESCRIPTION")

        class ItemResponse(BaseModel):
            id: str = Field(..., description="ITEM_RESPONSE_ID_DESCRIPTION")
            name: str = Field(..., description="ITEM_RESPONSE_NAME_DESCRIPTION")
            price: float = Field(..., description="ITEM_RESPONSE_PRICE_DESCRIPTION")

        @app.get("/items", tags=["items"])
        async def list_items() -> list[ItemResponse]:
            """FUNCTION_LIST_DESCRIPTION

            Returns a list of items.
            """
            return [
                ItemResponse(id="1", name="Item 1", price=10.0),
                ItemResponse(id="2", name="Item 2", price=20.0),
            ]

        @app.get("/items/{item_id}", tags=["items", "detail"])
        async def get_item(
            item_id: Annotated[str, Field(description="PATH_PARAM_DESCRIPTION")],
            fields: Annotated[
                str | None, Field(description="QUERY_PARAM_DESCRIPTION")
            ] = None,
        ) -> ItemResponse:
            """FUNCTION_GET_DESCRIPTION

            Gets a specific item by ID.

            Args:
                item_id: The ID of the item to retrieve
                fields: Optional fields to include
            """
            return ItemResponse(
                id=item_id, name=f"Item {item_id}", price=float(item_id) * 10.0
            )

        @app.post("/items", tags=["items", "create"])
        async def create_item(item: Item) -> ItemResponse:
            """FUNCTION_CREATE_DESCRIPTION

            Creates a new item.

            Body:
                Item object with name and price
            """
            return ItemResponse(id="new", name=item.name, price=item.price)

        return app

    @pytest.fixture
    async def fastapi_server(self, fastapi_app_with_descriptions):
        """Create a FastMCP server from the FastAPI app with custom route mappings."""
        # First create from FastAPI app to get the OpenAPI spec
        openapi_spec = fastapi_app_with_descriptions.openapi()

        # Debug: check the operationIds in the OpenAPI spec
        print("\nDEBUG - OpenAPI Paths:")
        for path, methods in openapi_spec["paths"].items():
            for method, details in methods.items():
                if method != "parameters":  # Skip non-HTTP method keys
                    operation_id = details.get("operationId", "no_operation_id")
                    print(
                        f"  Path: {path}, Method: {method}, OperationId: {operation_id}"
                    )

        # Create custom route mappings
        route_maps = [
            # Map GET /items to Resource
            RouteMap(methods=["GET"], pattern=r"^/items$", mcp_type=MCPType.RESOURCE),
            # Map GET /items/{item_id} to ResourceTemplate
            RouteMap(
                methods=["GET"],
                pattern=r"^/items/\{.*\}$",
                mcp_type=MCPType.RESOURCE_TEMPLATE,
            ),
            # Map POST /items to Tool
            RouteMap(methods=["POST"], pattern=r"^/items$", mcp_type=MCPType.TOOL),
        ]

        # Create FastMCP server with the OpenAPI spec and custom route mappings
        server = FastMCPOpenAPI(
            openapi_spec=openapi_spec,
            client=AsyncClient(
                transport=ASGITransport(app=fastapi_app_with_descriptions),
                base_url="http://test",
            ),
            name="Test FastAPI App",
            route_maps=route_maps,
        )

        # Debug: print all components created
        print("\nDEBUG - Resources created:")
        for name, resource in server._resource_manager.get_resources().items():
            print(f"  Resource: {name}, Name attribute: {resource.name}")

        print("\nDEBUG - Templates created:")
        for name, template in server._resource_manager.get_templates().items():
            print(f"  Template: {name}, Name attribute: {template.name}")

        print("\nDEBUG - Tools created:")
        for tool in server._tool_manager.list_tools():
            print(f"  Tool: {tool.name}")

        return server

    async def test_resource_includes_function_docstring(self, fastapi_server):
        """Test that a Resource includes the function docstring."""
        resources = list(fastapi_server._resource_manager.get_resources().values())

        # Now checking for the get_items operation ID rather than list_items
        list_resource = next((r for r in resources if "items_get" in r.name), None)

        assert list_resource is not None, "GET /items resource wasn't created"
        description = list_resource.description or ""
        assert "FUNCTION_LIST_DESCRIPTION" in description, (
            "Function docstring missing from Resource"
        )

    async def test_resource_includes_response_model_fields(self, fastapi_server):
        """Test that a Resource description includes basic response information.

        Note: FastAPI doesn't reliably include Pydantic field descriptions in the OpenAPI schema,
        so we can only check for basic response information being present.
        """
        resources = list(fastapi_server._resource_manager.get_resources().values())
        list_resource = next((r for r in resources if "items_get" in r.name), None)

        assert list_resource is not None, "GET /items resource wasn't created"
        description = list_resource.description or ""

        # Check that at least the response information is included
        assert "Successful Response" in description, (
            "Response information missing from Resource description"
        )

        # We've already verified in TestDescriptionPropagation that when descriptions
        # are present in the OpenAPI schema, they are properly included in the component description

    async def test_template_includes_function_docstring(self, fastapi_server):
        """Test that a ResourceTemplate includes the function docstring."""
        templates = list(fastapi_server._resource_manager.get_templates().values())
        get_template = next((t for t in templates if "get_item_items" in t.name), None)

        assert get_template is not None, "GET /items/{item_id} template wasn't created"
        description = get_template.description or ""
        assert "FUNCTION_GET_DESCRIPTION" in description, (
            "Function docstring missing from ResourceTemplate"
        )

    async def test_template_includes_path_parameter_description(self, fastapi_server):
        """Test that a ResourceTemplate includes path parameter descriptions.

        Note: Currently, FastAPI parameter descriptions using Annotated[type, Field(description=...)]
        are not properly propagated to the OpenAPI schema. The parameters appear but without the description.
        """
        templates = list(fastapi_server._resource_manager.get_templates().values())
        get_template = next((t for t in templates if "get_item_items" in t.name), None)

        assert get_template is not None, "GET /items/{item_id} template wasn't created"
        description = get_template.description or ""

        # Just test that parameters are included at all
        assert "Path Parameters" in description, (
            "Path parameters section missing from ResourceTemplate description"
        )
        assert "item_id" in description, (
            "item_id parameter missing from ResourceTemplate description"
        )

    async def test_template_includes_query_parameter_description(self, fastapi_server):
        """Test that a ResourceTemplate includes query parameter descriptions.

        Note: Currently, FastAPI parameter descriptions using Annotated[type, Field(description=...)]
        are not properly propagated to the OpenAPI schema. The parameters appear but without the description.
        """
        templates = list(fastapi_server._resource_manager.get_templates().values())
        get_template = next((t for t in templates if "get_item_items" in t.name), None)

        assert get_template is not None, "GET /items/{item_id} template wasn't created"
        description = get_template.description or ""

        # Just test that parameters are included at all
        assert "Query Parameters" in description, (
            "Query parameters section missing from ResourceTemplate description"
        )
        assert "fields" in description, (
            "fields parameter missing from ResourceTemplate description"
        )

    async def test_template_parameter_schema_includes_description(self, fastapi_server):
        """Test that a ResourceTemplate's parameter schema includes parameter descriptions."""
        templates = list(fastapi_server._resource_manager.get_templates().values())
        get_template = next((t for t in templates if "get_item_items" in t.name), None)

        assert get_template is not None, "GET /items/{item_id} template wasn't created"
        assert "properties" in get_template.parameters, (
            "Schema properties missing from ResourceTemplate"
        )
        assert "item_id" in get_template.parameters["properties"], (
            "item_id missing from ResourceTemplate schema"
        )
        assert "description" in get_template.parameters["properties"]["item_id"], (
            "Description missing from item_id parameter schema"
        )
        assert (
            "PATH_PARAM_DESCRIPTION"
            in get_template.parameters["properties"]["item_id"]["description"]
        ), "Path parameter description incorrect in schema"

    async def test_tool_includes_function_docstring(self, fastapi_server):
        """Test that a Tool includes the function docstring."""
        tools = fastapi_server._tool_manager.list_tools()
        create_tool = next(
            (t for t in tools if "create_item_items_post" == t.name), None
        )

        assert create_tool is not None, "POST /items tool wasn't created"
        description = create_tool.description or ""
        assert "FUNCTION_CREATE_DESCRIPTION" in description, (
            "Function docstring missing from Tool"
        )

    async def test_tool_parameter_schema_includes_property_description(
        self, fastapi_server
    ):
        """Test that a Tool's parameter schema includes property descriptions from request model.

        Note: Currently, model field descriptions defined in Pydantic models using Field(description=...)
        may not be consistently propagated into the FastAPI OpenAPI schema and thus not into the tool's
        parameter schema.
        """
        tools = fastapi_server._tool_manager.list_tools()
        create_tool = next(
            (t for t in tools if "create_item_items_post" == t.name), None
        )

        assert create_tool is not None, "POST /items tool wasn't created"
        assert "properties" in create_tool.parameters, (
            "Schema properties missing from Tool"
        )
        assert "name" in create_tool.parameters["properties"], (
            "name parameter missing from Tool schema"
        )
        # We don't test for the description field content as it may not be consistently propagated

    async def test_client_api_resource_description(self, fastapi_server):
        """Test that Resource descriptions are accessible via the client API."""
        async with Client(fastapi_server) as client:
            resources = await client.list_resources()
            list_resource = next((r for r in resources if "items_get" in r.name), None)

            assert list_resource is not None, (
                "GET /items resource not accessible via client API"
            )
            resource_description = list_resource.description or ""
            assert "FUNCTION_LIST_DESCRIPTION" in resource_description, (
                "Function docstring missing in Resource from client API"
            )

    async def test_client_api_template_description(self, fastapi_server):
        """Test that ResourceTemplate descriptions are accessible via the client API."""
        async with Client(fastapi_server) as client:
            templates = await client.list_resource_templates()
            get_template = next(
                (t for t in templates if "get_item_items" in t.name), None
            )

            assert get_template is not None, (
                "GET /items/{item_id} template not accessible via client API"
            )
            template_description = get_template.description or ""
            assert "FUNCTION_GET_DESCRIPTION" in template_description, (
                "Function docstring missing in ResourceTemplate from client API"
            )

    async def test_client_api_tool_description(self, fastapi_server):
        """Test that Tool descriptions are accessible via the client API."""
        async with Client(fastapi_server) as client:
            tools = await client.list_tools()
            create_tool = next(
                (t for t in tools if "create_item_items_post" == t.name), None
            )

            assert create_tool is not None, (
                "POST /items tool not accessible via client API"
            )
            tool_description = create_tool.description or ""
            assert "FUNCTION_CREATE_DESCRIPTION" in tool_description, (
                "Function docstring missing in Tool from client API"
            )

    async def test_client_api_tool_parameter_schema(self, fastapi_server):
        """Test that Tool parameter schemas are accessible via the client API."""
        async with Client(fastapi_server) as client:
            tools = await client.list_tools()
            create_tool = next(
                (t for t in tools if "create_item_items_post" == t.name), None
            )

            assert create_tool is not None, (
                "POST /items tool not accessible via client API"
            )
            assert "properties" in create_tool.inputSchema, (
                "Schema properties missing from Tool inputSchema in client API"
            )
            assert "name" in create_tool.inputSchema["properties"], (
                "name parameter missing from Tool schema in client API"
            )
            # We don't test for the description field content as it may not be consistently propagated


class TestReprMethods:
    """Tests for the custom __repr__ methods of OpenAPI objects."""

    async def test_openapi_tool_repr(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that OpenAPITool's __repr__ method works without recursion errors."""
        tools = fastmcp_openapi_server_with_all_types._tool_manager.list_tools()
        tool = next(iter(tools))

        # Verify repr doesn't cause recursion and contains expected elements
        tool_repr = repr(tool)
        assert "OpenAPITool" in tool_repr
        assert f"name={tool.name!r}" in tool_repr
        assert "method=" in tool_repr
        assert "path=" in tool_repr

    async def test_openapi_resource_repr(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that OpenAPIResource's __repr__ method works without recursion errors."""
        resources = list(
            fastmcp_openapi_server_with_all_types._resource_manager.get_resources().values()
        )
        resource = next(iter(resources))

        # Verify repr doesn't cause recursion and contains expected elements
        resource_repr = repr(resource)
        assert "OpenAPIResource" in resource_repr
        assert f"name={resource.name!r}" in resource_repr
        assert "uri=" in resource_repr
        assert "path=" in resource_repr

    async def test_openapi_resource_template_repr(
        self, fastmcp_openapi_server_with_all_types: FastMCPOpenAPI
    ):
        """Test that OpenAPIResourceTemplate's __repr__ method works without recursion errors."""
        templates = list(
            fastmcp_openapi_server_with_all_types._resource_manager.get_templates().values()
        )
        template = next(iter(templates))

        # Verify repr doesn't cause recursion and contains expected elements
        template_repr = repr(template)
        assert "OpenAPIResourceTemplate" in template_repr
        assert f"name={template.name!r}" in template_repr
        assert "uri_template=" in template_repr
        assert "path=" in template_repr


class TestEnumHandling:
    """Tests for handling enum parameters in OpenAPI schemas."""

    async def test_enum_parameter_schema(self):
        """Test that enum parameters are properly handled in tool parameter schemas."""

        # Define an enum just like in example.py
        class QueryEnum(str, Enum):
            foo = "foo"
            bar = "bar"
            baz = "baz"

        # Create a minimal FastAPI app with an endpoint using the enum
        app = FastAPI()

        @app.post("/items/{item_id}")
        def read_item(
            item_id: int,
            query: QueryEnum | None = None,
        ):
            return {"item_id": item_id, "query": query}

        # Create a client for the app
        client = AsyncClient(transport=ASGITransport(app=app), base_url="http://test")

        # Create the FastMCPOpenAPI server from the app
        openapi_spec = app.openapi()
        server = FastMCPOpenAPI(
            openapi_spec=openapi_spec,
            client=client,
            name="Enum Test",
        )

        # Get the tools from the server
        tools = server._tool_manager.list_tools()

        # Find the read_item tool
        read_item_tool = next((t for t in tools if t.name == "read_item_items"), None)

        # Verify the tool exists
        assert read_item_tool is not None, "read_item tool wasn't created"

        # Check that the parameters include the enum reference
        assert "properties" in read_item_tool.parameters
        assert "query" in read_item_tool.parameters["properties"]

        # Check for the anyOf with $ref to the enum definition
        query_param = read_item_tool.parameters["properties"]["query"]
        assert "anyOf" in query_param

        # Find the ref in the anyOf list
        ref_found = False
        for option in query_param["anyOf"]:
            if "$ref" in option and option["$ref"].startswith("#/$defs/QueryEnum"):
                ref_found = True
                break

        assert ref_found, "Reference to enum definition not found in query parameter"

        # Check that the $defs section exists and contains the enum definition
        assert "$defs" in read_item_tool.parameters
        assert "QueryEnum" in read_item_tool.parameters["$defs"]

        # Verify the enum definition
        enum_def = read_item_tool.parameters["$defs"]["QueryEnum"]
        assert "enum" in enum_def
        assert enum_def["enum"] == ["foo", "bar", "baz"]
        assert enum_def["type"] == "string"


class TestRouteMapWildcard:
    """Tests for wildcard RouteMap methods functionality."""

    @pytest.fixture
    def basic_openapi_spec(self) -> dict:
        """Create a minimal OpenAPI spec with different HTTP methods."""
        return {
            "openapi": "3.1.0",
            "info": {"title": "Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "operationId": "getUsers",
                        "responses": {"200": {"description": "Success"}},
                    },
                    "post": {
                        "operationId": "createUser",
                        "responses": {"201": {"description": "Created"}},
                    },
                },
                "/posts": {
                    "get": {
                        "operationId": "getPosts",
                        "responses": {"200": {"description": "Success"}},
                    },
                    "post": {
                        "operationId": "createPost",
                        "responses": {"201": {"description": "Created"}},
                    },
                },
            },
        }

    @pytest.fixture
    async def mock_basic_client(self) -> httpx.AsyncClient:
        """Create a simple mock client."""

        async def _responder(request):
            return httpx.Response(200, json={"status": "ok"})

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    async def test_wildcard_matches_all_methods(
        self, basic_openapi_spec, mock_basic_client
    ):
        """Test that a RouteMap with methods='*' matches all HTTP methods."""
        # Create a single route map with wildcard method
        route_maps = [RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)]

        mcp = FastMCPOpenAPI(
            openapi_spec=basic_openapi_spec,
            client=mock_basic_client,
            route_maps=route_maps,
        )

        # All operations should be mapped to tools
        tools = mcp._tool_manager.list_tools()
        tool_names = {tool.name for tool in tools}

        # Check that all 4 operations became tools
        expected_tools = {"getUsers", "createUser", "getPosts", "createPost"}
        assert tool_names == expected_tools


class TestRouteMapTags:
    """Tests for RouteMap tags functionality."""

    @pytest.fixture
    def tagged_openapi_spec(self) -> dict:
        """Create an OpenAPI spec with various tags for testing."""
        return {
            "openapi": "3.1.0",
            "info": {"title": "Tagged API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "operationId": "getUsers",
                        "tags": ["users", "public"],
                        "responses": {"200": {"description": "Success"}},
                    },
                    "post": {
                        "operationId": "createUser",
                        "tags": ["users", "admin"],
                        "responses": {"201": {"description": "Created"}},
                    },
                },
                "/admin/stats": {
                    "get": {
                        "operationId": "getAdminStats",
                        "tags": ["admin", "internal"],
                        "responses": {"200": {"description": "Success"}},
                    }
                },
                "/health": {
                    "get": {
                        "operationId": "getHealth",
                        "tags": ["public"],
                        "responses": {"200": {"description": "Success"}},
                    }
                },
                "/metrics": {
                    "get": {
                        "operationId": "getMetrics",
                        "responses": {"200": {"description": "Success"}},
                    }
                },
            },
        }

    @pytest.fixture
    async def mock_client(self) -> httpx.AsyncClient:
        """Create a simple mock client."""

        async def _responder(request):
            return httpx.Response(200, json={"status": "ok"})

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    async def test_tags_as_tools(self, tagged_openapi_spec, mock_client):
        """Test that routes with specific tags are converted to tools."""
        # Convert routes with "admin" tag to tools
        route_maps = [
            RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL, tags={"admin"}),
            RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=tagged_openapi_spec,
            client=mock_client,
            route_maps=route_maps,
        )

        # Check that admin-tagged routes are tools
        tools = server._tool_manager.get_tools()
        tool_names = {t.name for t in tools.values()}

        resources = server._resource_manager.get_resources()
        resource_names = {r.name for r in resources.values()}

        # Routes with "admin" tag should be tools
        assert "createUser" in tool_names
        assert "getAdminStats" in tool_names

        # Routes without "admin" tag should be resources
        assert "getUsers" in resource_names
        assert "getHealth" in resource_names
        assert "getMetrics" in resource_names

    async def test_exclude_tags(self, tagged_openapi_spec, mock_client):
        """Test that routes with specific tags are excluded."""
        # Exclude routes with "internal" tag
        route_maps = [
            RouteMap(
                methods="*", pattern=r".*", mcp_type=MCPType.EXCLUDE, tags={"internal"}
            ),
            RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
            RouteMap(methods=["POST"], pattern=r".*", mcp_type=MCPType.TOOL),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=tagged_openapi_spec,
            client=mock_client,
            route_maps=route_maps,
        )

        # Check that internal-tagged routes are excluded
        resources = server._resource_manager.get_resources()
        resource_names = {r.name for r in resources.values()}

        tools = server._tool_manager.get_tools()
        tool_names = {t.name for t in tools.values()}

        # Internal-tagged route should be excluded
        assert "getAdminStats" not in resource_names
        assert "getAdminStats" not in tool_names

        # Other routes should still be present
        assert "getUsers" in resource_names
        assert "getHealth" in resource_names
        assert "getMetrics" in resource_names
        assert "createUser" in tool_names

    async def test_multiple_tags_and_condition(self, tagged_openapi_spec, mock_client):
        """Test that routes must have ALL specified tags (AND condition)."""
        # Routes must have BOTH "users" AND "admin" tags
        route_maps = [
            RouteMap(
                methods="*",
                pattern=r".*",
                mcp_type=MCPType.TOOL,
                tags={"users", "admin"},
            ),
            RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=tagged_openapi_spec,
            client=mock_client,
            route_maps=route_maps,
        )

        tools = server._tool_manager.get_tools()
        tool_names = {t.name for t in tools.values()}

        resources = server._resource_manager.get_resources()
        resource_names = {r.name for r in resources.values()}

        # Only createUser has both "users" AND "admin" tags
        assert "createUser" in tool_names

        # Other routes should be resources
        assert "getUsers" in resource_names  # has "users" but not "admin"
        assert "getAdminStats" in resource_names  # has "admin" but not "users"
        assert "getHealth" in resource_names
        assert "getMetrics" in resource_names

    async def test_pattern_and_tags_combination(self, tagged_openapi_spec, mock_client):
        """Test that both pattern and tags must be satisfied."""
        # Routes matching pattern AND having specific tags
        route_maps = [
            RouteMap(
                methods="*",
                pattern=r".*/admin/.*",
                mcp_type=MCPType.TOOL,
                tags={"admin"},
            ),
            RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
            RouteMap(methods=["POST"], pattern=r".*", mcp_type=MCPType.TOOL),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=tagged_openapi_spec,
            client=mock_client,
            route_maps=route_maps,
        )

        tools = server._tool_manager.get_tools()
        tool_names = {t.name for t in tools.values()}

        resources = server._resource_manager.get_resources()
        resource_names = {r.name for r in resources.values()}

        # Only getAdminStats matches both /admin/ pattern AND "admin" tag
        assert "getAdminStats" in tool_names

        # createUser has "admin" tag but doesn't match pattern, so it becomes a tool via POST rule
        assert "createUser" in tool_names

        # Other routes should be resources (GET)
        assert "getUsers" in resource_names
        assert "getHealth" in resource_names
        assert "getMetrics" in resource_names

    async def test_empty_tags_ignored(self, tagged_openapi_spec, mock_client):
        """Test that empty tags set is ignored (matches all routes)."""
        # Empty tags should match all routes
        route_maps = [
            RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL, tags=set()),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=tagged_openapi_spec,
            client=mock_client,
            route_maps=route_maps,
        )

        tools = server._tool_manager.get_tools()
        tool_names = {t.name for t in tools.values()}

        # All routes should be tools since empty tags matches everything
        expected_tools = {
            "getUsers",
            "createUser",
            "getAdminStats",
            "getHealth",
            "getMetrics",
        }
        assert tool_names == expected_tools


class TestMCPNames:
    """Tests for the mcp_names dictionary functionality."""

    @pytest.fixture
    def mcp_names_openapi_spec(self) -> dict:
        """OpenAPI spec with various operationIds for testing naming strategies."""
        return {
            "openapi": "3.1.0",
            "info": {"title": "MCP Names Test API", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "operationId": "list_users__with_pagination",
                        "summary": "Get All Users",
                        "responses": {"200": {"description": "Success"}},
                    },
                    "post": {
                        "operationId": "create_user_admin__special_permissions",
                        "summary": "Create New User",
                        "requestBody": {
                            "required": True,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {"name": {"type": "string"}},
                                        "required": ["name"],
                                    }
                                }
                            },
                        },
                        "responses": {"201": {"description": "Created"}},
                    },
                },
                "/users/{id}": {
                    "get": {
                        "operationId": "get_user_by_id__admin_only",
                        "summary": "Fetch Single User Profile",
                        "parameters": [
                            {
                                "name": "id",
                                "in": "path",
                                "required": True,
                                "schema": {"type": "integer"},
                            }
                        ],
                        "responses": {"200": {"description": "Success"}},
                    }
                },
                "/very-long-endpoint-name": {
                    "get": {
                        "operationId": "this_is_a_very_long_operation_id_that_exceeds_fifty_six_characters_and_should_be_truncated",
                        "summary": "This Is A Very Long Summary That Should Also Be Truncated When Used As Name",
                        "responses": {"200": {"description": "Success"}},
                    }
                },
                "/special": {
                    "get": {
                        "operationId": "special-chars@and#spaces in$operation%id",
                        "summary": "Special Chars & Spaces In Summary!",
                        "responses": {"200": {"description": "Success"}},
                    }
                },
            },
        }

    @pytest.fixture
    async def mock_client(self) -> httpx.AsyncClient:
        """Mock client for testing."""

        async def _responder(request):
            return httpx.Response(200, json={"status": "ok"})

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    async def test_mcp_names_custom_mapping(self, mcp_names_openapi_spec, mock_client):
        """Test that mcp_names dictionary provides custom names for components."""
        mcp_names = {
            "list_users__with_pagination": "user_list",
            "create_user_admin__special_permissions": "admin_create_user",
            "get_user_by_id__admin_only": "user_detail",
        }

        server = FastMCPOpenAPI(
            openapi_spec=mcp_names_openapi_spec,
            client=mock_client,
            mcp_names=mcp_names,
            route_maps=GET_ROUTE_MAPS,
        )

        # Check tools use custom names
        tools = server._tool_manager.list_tools()
        tool_names = {tool.name for tool in tools}
        assert "admin_create_user" in tool_names

        # Check resource templates use custom names
        templates = list(server._resource_manager.get_templates().values())
        template_names = {template.name for template in templates}
        assert "user_detail" in template_names

        # Check resources use custom names
        resources = list(server._resource_manager.get_resources().values())
        resource_names = {resource.name for resource in resources}
        assert "user_list" in resource_names

    async def test_mcp_names_fallback_to_operation_id_short(
        self, mcp_names_openapi_spec, mock_client
    ):
        """Test fallback to operationId up to double underscore when not in mcp_names."""
        # Only provide mapping for one operationId
        mcp_names = {
            "list_users__with_pagination": "custom_user_list",
        }

        server = FastMCPOpenAPI(
            openapi_spec=mcp_names_openapi_spec,
            client=mock_client,
            mcp_names=mcp_names,
            route_maps=GET_ROUTE_MAPS,
        )

        tools = server._tool_manager.list_tools()
        tool_names = {tool.name for tool in tools}

        templates = list(server._resource_manager.get_templates().values())
        template_names = {template.name for template in templates}

        resources = list(server._resource_manager.get_resources().values())
        resource_names = {resource.name for resource in resources}

        # Custom mapped name should be used
        assert "custom_user_list" in resource_names

        # Unmapped operationIds should use short version (up to __)
        assert "create_user_admin" in tool_names
        assert "get_user_by_id" in template_names

    async def test_names_are_slugified(self, mcp_names_openapi_spec, mock_client):
        """Test that names are properly slugified (spaces, special chars removed)."""
        server = FastMCPOpenAPI(
            openapi_spec=mcp_names_openapi_spec,
            client=mock_client,
            route_maps=GET_ROUTE_MAPS,
        )

        resources = list(server._resource_manager.get_resources().values())
        resource_names = {
            resource.name for resource in resources if resource.name is not None
        }

        # Special chars and spaces should be slugified
        slugified_name = next(
            (name for name in resource_names if "special" in name), None
        )
        assert slugified_name is not None
        # Should not contain special characters or spaces
        assert "@" not in slugified_name
        assert "#" not in slugified_name
        assert "$" not in slugified_name
        assert "%" not in slugified_name
        assert " " not in slugified_name

    async def test_names_are_truncated_to_56_chars(
        self, mcp_names_openapi_spec, mock_client
    ):
        """Test that names are truncated to 56 characters maximum."""
        server = FastMCPOpenAPI(
            openapi_spec=mcp_names_openapi_spec,
            client=mock_client,
            route_maps=GET_ROUTE_MAPS,
        )

        # Check all component types
        all_names = []

        tools = server._tool_manager.list_tools()
        all_names.extend(tool.name for tool in tools)

        resources = list(server._resource_manager.get_resources().values())
        all_names.extend(resource.name for resource in resources)

        templates = list(server._resource_manager.get_templates().values())
        all_names.extend(template.name for template in templates)

        # All names should be 56 characters or less
        for name in all_names:
            assert len(name) <= 56, (
                f"Name '{name}' exceeds 56 characters (length: {len(name)})"
            )

        # Verify that the long operationId was actually truncated
        long_name = next((name for name in all_names if len(name) > 50), None)
        assert long_name is not None, "Expected to find a truncated name for testing"

    async def test_mcp_names_with_from_openapi_classmethod(
        self, mcp_names_openapi_spec, mock_client
    ):
        """Test mcp_names works with FastMCP.from_openapi() classmethod."""
        mcp_names = {
            "list_users__with_pagination": "openapi_user_list",
        }

        server = FastMCP.from_openapi(
            openapi_spec=mcp_names_openapi_spec,
            client=mock_client,
            mcp_names=mcp_names,
        )

        tools = server._tool_manager.list_tools()
        tool_names = {tool.name for tool in tools}
        assert "openapi_user_list" in tool_names

    async def test_mcp_names_with_from_fastapi_classmethod(self):
        """Test mcp_names works with FastMCP.from_fastapi() classmethod."""
        from fastapi import FastAPI
        from pydantic import BaseModel

        app = FastAPI(title="FastAPI MCP Names Test")

        class User(BaseModel):
            name: str

        @app.get("/users", operation_id="list_users__with_filters")
        async def get_users() -> list[User]:
            return [User(name="test")]

        @app.post("/users", operation_id="create_user__admin_required")
        async def create_user(user: User) -> User:
            return user

        mcp_names = {
            "list_users__with_filters": "fastapi_user_list",
            "create_user__admin_required": "fastapi_create_user",
        }

        server = FastMCP.from_fastapi(
            app=app,
            mcp_names=mcp_names,
        )

        tools = server._tool_manager.list_tools()
        tool_names = {tool.name for tool in tools}

        assert "fastapi_create_user" in tool_names
        assert "fastapi_user_list" in tool_names

    async def test_mcp_names_custom_names_are_also_truncated(
        self, mcp_names_openapi_spec, mock_client
    ):
        """Test that custom names in mcp_names are also truncated to 56 characters."""
        # Provide a custom name that's longer than 56 characters
        very_long_custom_name = "this_is_a_very_long_custom_name_that_exceeds_fifty_six_characters_and_should_be_truncated"

        mcp_names = {
            "list_users__with_pagination": very_long_custom_name,
        }

        server = FastMCPOpenAPI(
            openapi_spec=mcp_names_openapi_spec,
            client=mock_client,
            mcp_names=mcp_names,
            route_maps=GET_ROUTE_MAPS,
        )

        resources = list(server._resource_manager.get_resources().values())
        resource_names = {
            resource.name for resource in resources if resource.name is not None
        }

        # Find the resource that should have the custom name
        truncated_name = next(
            (
                name
                for name in resource_names
                if "this_is_a_very_long_custom_name" in name
            ),
            None,
        )
        assert truncated_name is not None
        assert len(truncated_name) <= 56
        assert (
            len(truncated_name) == 56
        )  # Should be exactly 56 since original was longer


class TestRouteMapMCPTags:
    """Tests for RouteMap mcp_tags functionality."""

    @pytest.fixture
    def simple_fastapi_app(self) -> FastAPI:
        """Create a simple FastAPI app for testing mcp_tags."""
        app = FastAPI(title="MCP Tags Test API")

        @app.get("/users", tags=["users"])
        async def get_users():
            """Get all users."""
            return [{"id": 1, "name": "Alice"}]

        @app.get("/users/{user_id}", tags=["users"])
        async def get_user(user_id: int):
            """Get user by ID."""
            return {"id": user_id, "name": f"User {user_id}"}

        @app.post("/users", tags=["users"])
        async def create_user(name: str):
            """Create a new user."""
            return {"id": 99, "name": name}

        return app

    @pytest.fixture
    async def mock_client(self) -> httpx.AsyncClient:
        """Mock client for testing."""

        async def _responder(request):
            return httpx.Response(200, json={"status": "ok"})

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    async def test_mcp_tags_added_to_tools(self, simple_fastapi_app, mock_client):
        """Test that mcp_tags are added to Tools created from routes."""
        # Create route map that adds custom tags to POST endpoints
        route_maps = [
            RouteMap(
                methods=["POST"],
                pattern=r".*",
                mcp_type=MCPType.TOOL,
                mcp_tags={"custom", "api-write"},
            ),
            # Default mapping for other routes
            RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=simple_fastapi_app.openapi(),
            client=mock_client,
            route_maps=route_maps,
        )

        # Get the POST tool
        tools = server._tool_manager.list_tools()
        create_user_tool = next((t for t in tools if "create_user" in t.name), None)

        assert create_user_tool is not None, "create_user tool not found"

        # Check that both original tags and mcp_tags are present
        assert "users" in create_user_tool.tags  # Original OpenAPI tag
        assert "custom" in create_user_tool.tags  # Added via mcp_tags
        assert "api-write" in create_user_tool.tags  # Added via mcp_tags

    async def test_mcp_tags_added_to_resources(self, simple_fastapi_app, mock_client):
        """Test that mcp_tags are added to Resources created from routes."""
        # Create route map that adds custom tags to GET endpoints without path params
        route_maps = [
            RouteMap(
                methods=["GET"],
                pattern=r"^/users$",  # Only match /users, not /users/{id}
                mcp_type=MCPType.RESOURCE,
                mcp_tags={"list-data", "public-api"},
            ),
            # Default mapping for other routes
            RouteMap(
                methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE_TEMPLATE
            ),
            RouteMap(methods=["POST"], pattern=r".*", mcp_type=MCPType.TOOL),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=simple_fastapi_app.openapi(),
            client=mock_client,
            route_maps=route_maps,
        )

        # Get the resource
        resources = list(server._resource_manager.get_resources().values())
        get_users_resource = next((r for r in resources if "get_users" in r.name), None)

        assert get_users_resource is not None, "get_users resource not found"

        # Check that both original tags and mcp_tags are present
        assert "users" in get_users_resource.tags  # Original OpenAPI tag
        assert "list-data" in get_users_resource.tags  # Added via mcp_tags
        assert "public-api" in get_users_resource.tags  # Added via mcp_tags

    async def test_mcp_tags_added_to_resource_templates(
        self, simple_fastapi_app, mock_client
    ):
        """Test that mcp_tags are added to ResourceTemplates created from routes."""
        # Create route map that adds custom tags to GET endpoints with path params
        route_maps = [
            RouteMap(
                methods=["GET"],
                pattern=r".*\{.*\}.*",  # Match routes with path parameters
                mcp_type=MCPType.RESOURCE_TEMPLATE,
                mcp_tags={"detail-view", "parameterized"},
            ),
            # Default mapping for other routes
            RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
            RouteMap(methods=["POST"], pattern=r".*", mcp_type=MCPType.TOOL),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=simple_fastapi_app.openapi(),
            client=mock_client,
            route_maps=route_maps,
        )

        # Get the resource template
        templates = list(server._resource_manager.get_templates().values())
        get_user_template = next((t for t in templates if "get_user" in t.name), None)

        assert get_user_template is not None, "get_user template not found"

        # Check that both original tags and mcp_tags are present
        assert "users" in get_user_template.tags  # Original OpenAPI tag
        assert "detail-view" in get_user_template.tags  # Added via mcp_tags
        assert "parameterized" in get_user_template.tags  # Added via mcp_tags

    async def test_multiple_route_maps_with_different_mcp_tags(
        self, simple_fastapi_app, mock_client
    ):
        """Test that different route maps can add different mcp_tags."""
        # Multiple route maps with different mcp_tags
        route_maps = [
            # First priority: POST requests get write-related tags
            RouteMap(
                methods=["POST"],
                pattern=r".*",
                mcp_type=MCPType.TOOL,
                mcp_tags={"write-operation", "mutation"},
            ),
            # Second priority: GET with path params get detail tags
            RouteMap(
                methods=["GET"],
                pattern=r".*\{.*\}.*",
                mcp_type=MCPType.RESOURCE_TEMPLATE,
                mcp_tags={"detail", "single-item"},
            ),
            # Third priority: Other GET requests get list tags
            RouteMap(
                methods=["GET"],
                pattern=r".*",
                mcp_type=MCPType.RESOURCE,
                mcp_tags={"list", "collection"},
            ),
        ]

        server = FastMCPOpenAPI(
            openapi_spec=simple_fastapi_app.openapi(),
            client=mock_client,
            route_maps=route_maps,
        )

        # Check tool tags
        tools = server._tool_manager.list_tools()
        create_tool = next((t for t in tools if "create_user" in t.name), None)
        assert create_tool is not None
        assert "write-operation" in create_tool.tags
        assert "mutation" in create_tool.tags

        # Check resource template tags
        templates = list(server._resource_manager.get_templates().values())
        detail_template = next((t for t in templates if "get_user" in t.name), None)
        assert detail_template is not None
        assert "detail" in detail_template.tags
        assert "single-item" in detail_template.tags

        # Check resource tags
        resources = list(server._resource_manager.get_resources().values())
        list_resource = next((r for r in resources if "get_users" in r.name), None)
        assert list_resource is not None
        assert "list" in list_resource.tags
        assert "collection" in list_resource.tags


class TestGlobalTagsParameter:
    """Tests for the global tags parameter on from_openapi and from_fastapi class methods."""

    @pytest.fixture
    def simple_fastapi_app(self) -> FastAPI:
        """Create a simple FastAPI app for testing global tags."""
        app = FastAPI(title="Global Tags Test API")

        @app.get("/items", tags=["items"])
        async def get_items():
            """Get all items."""
            return [{"id": 1, "name": "Item 1"}]

        @app.get("/items/{item_id}", tags=["items"])
        async def get_item(item_id: int):
            """Get item by ID."""
            return {"id": item_id, "name": f"Item {item_id}"}

        @app.post("/items", tags=["items"])
        async def create_item(name: str):
            """Create a new item."""
            return {"id": 99, "name": name}

        return app

    @pytest.fixture
    async def mock_client(self) -> httpx.AsyncClient:
        """Mock client for testing."""

        async def _responder(request):
            return httpx.Response(200, json={"status": "ok"})

        transport = httpx.MockTransport(_responder)
        return httpx.AsyncClient(transport=transport, base_url="http://test")

    async def test_from_fastapi_adds_global_tags(self, simple_fastapi_app):
        """Test that from_fastapi adds global tags to all components."""
        global_tags = {"global", "api-v1"}

        server = FastMCP.from_fastapi(
            simple_fastapi_app,
            tags=global_tags,
            route_maps=[
                RouteMap(
                    methods=["GET"], pattern=r"^/items$", mcp_type=MCPType.RESOURCE
                ),
                RouteMap(
                    methods=["GET"],
                    pattern=r".*\{.*\}.*",
                    mcp_type=MCPType.RESOURCE_TEMPLATE,
                ),
                RouteMap(methods=["POST"], pattern=r".*", mcp_type=MCPType.TOOL),
            ],
        )

        # Check tool has both original and global tags
        tools = await server.get_tools()
        create_item_tool = tools["create_item_items_post"]
        assert "items" in create_item_tool.tags  # Original OpenAPI tag
        assert "global" in create_item_tool.tags  # Global tag
        assert "api-v1" in create_item_tool.tags  # Global tag

        # Check resource has both original and global tags
        resources = await server.get_resources()
        get_items_resource = resources["resource://get_items_items_get"]
        assert "items" in get_items_resource.tags  # Original OpenAPI tag
        assert "global" in get_items_resource.tags  # Global tag
        assert "api-v1" in get_items_resource.tags  # Global tag

        # Check resource template has both original and global tags
        templates = await server.get_resource_templates()
        get_item_template = templates["resource://get_item_items/{item_id}"]
        assert "items" in get_item_template.tags  # Original OpenAPI tag
        assert "global" in get_item_template.tags  # Global tag
        assert "api-v1" in get_item_template.tags  # Global tag

    async def test_from_openapi_adds_global_tags(self, simple_fastapi_app, mock_client):
        """Test that from_openapi adds global tags to all components."""
        global_tags = {"openapi-global", "service"}

        server = FastMCP.from_openapi(
            openapi_spec=simple_fastapi_app.openapi(),
            client=mock_client,
            tags=global_tags,
            route_maps=[
                RouteMap(
                    methods=["GET"], pattern=r"^/items$", mcp_type=MCPType.RESOURCE
                ),
                RouteMap(
                    methods=["GET"],
                    pattern=r".*\{.*\}.*",
                    mcp_type=MCPType.RESOURCE_TEMPLATE,
                ),
                RouteMap(methods=["POST"], pattern=r".*", mcp_type=MCPType.TOOL),
            ],
        )

        # Check tool has both original and global tags
        tools = await server.get_tools()
        create_item_tool = tools["create_item_items_post"]
        assert "items" in create_item_tool.tags  # Original OpenAPI tag
        assert "openapi-global" in create_item_tool.tags  # Global tag
        assert "service" in create_item_tool.tags  # Global tag

        # Check resource has both original and global tags
        resources = await server.get_resources()
        get_items_resource = resources["resource://get_items_items_get"]
        assert "items" in get_items_resource.tags  # Original OpenAPI tag
        assert "openapi-global" in get_items_resource.tags  # Global tag
        assert "service" in get_items_resource.tags  # Global tag

        # Check resource template has both original and global tags
        templates = await server.get_resource_templates()
        get_item_template = templates["resource://get_item_items/{item_id}"]
        assert "items" in get_item_template.tags  # Original OpenAPI tag
        assert "openapi-global" in get_item_template.tags  # Global tag
        assert "service" in get_item_template.tags  # Global tag

    async def test_global_tags_combine_with_route_map_tags(
        self, simple_fastapi_app, mock_client
    ):
        """Test that global tags combine with both OpenAPI tags and RouteMap mcp_tags."""
        global_tags = {"global"}
        route_map_tags = {"route-specific"}

        server = FastMCP.from_openapi(
            openapi_spec=simple_fastapi_app.openapi(),
            client=mock_client,
            tags=global_tags,
            route_maps=[
                RouteMap(
                    methods=["POST"],
                    pattern=r".*",
                    mcp_type=MCPType.TOOL,
                    mcp_tags=route_map_tags,
                ),
                RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),
            ],
        )

        # Check that all three types of tags are present on the tool
        tools = await server.get_tools()
        create_item_tool = tools["create_item_items_post"]
        assert "items" in create_item_tool.tags  # Original OpenAPI tag
        assert "global" in create_item_tool.tags  # Global tag
        assert "route-specific" in create_item_tool.tags  # RouteMap mcp_tag

        # Check that resource only has OpenAPI and global tags (no route-specific since different RouteMap)
        resources = await server.get_resources()
        get_items_resource = resources["resource://get_items_items_get"]
        assert "items" in get_items_resource.tags  # Original OpenAPI tag
        assert "global" in get_items_resource.tags  # Global tag
        assert "route-specific" not in get_items_resource.tags  # Not from this RouteMap