@@ -252,32 +252,55 @@ async def handler(_: Any):
252
252
return decorator
253
253
254
254
def read_resource (self ):
255
- def decorator (func : Callable [[AnyUrl ], Awaitable [str | bytes ]]):
255
+ def decorator (
256
+ func : Callable [[AnyUrl ], Awaitable [str | bytes | tuple [str | bytes , str ]]],
257
+ ):
256
258
logger .debug ("Registering handler for ReadResourceRequest" )
257
259
258
260
async def handler (req : types .ReadResourceRequest ):
259
261
result = await func (req .params .uri )
262
+
263
+ def create_content (data : str | bytes , mime_type : str ):
264
+ match data :
265
+ case str () as data :
266
+ return types .TextResourceContents (
267
+ uri = req .params .uri ,
268
+ text = data ,
269
+ mimeType = mime_type ,
270
+ )
271
+ case bytes () as data :
272
+ import base64
273
+
274
+ return types .BlobResourceContents (
275
+ uri = req .params .uri ,
276
+ blob = base64 .urlsafe_b64encode (data ).decode (),
277
+ mimeType = mime_type ,
278
+ )
279
+
260
280
match result :
261
- case str (s ) :
262
- content = types . TextResourceContents (
263
- uri = req . params . uri ,
264
- text = s ,
265
- mimeType = "text/plain" ,
281
+ case str () | bytes () as data :
282
+ default_mime = (
283
+ "text/plain"
284
+ if isinstance ( data , str )
285
+ else "application/octet-stream"
266
286
)
267
- case bytes (b ):
268
- import base64
269
-
270
- content = types .BlobResourceContents (
271
- uri = req .params .uri ,
272
- blob = base64 .urlsafe_b64encode (b ).decode (),
273
- mimeType = "application/octet-stream" ,
287
+ content = create_content (data , default_mime )
288
+ return types .ServerResult (
289
+ types .ReadResourceResult (
290
+ contents = [content ],
291
+ )
292
+ )
293
+ case (data , mime_type ):
294
+ content = create_content (data , mime_type )
295
+ return types .ServerResult (
296
+ types .ReadResourceResult (
297
+ contents = [content ],
298
+ )
299
+ )
300
+ case _:
301
+ raise ValueError (
302
+ f"Unexpected return type from read_resource: { type (result )} "
274
303
)
275
-
276
- return types .ServerResult (
277
- types .ReadResourceResult (
278
- contents = [content ],
279
- )
280
- )
281
304
282
305
self .request_handlers [types .ReadResourceRequest ] = handler
283
306
return func
0 commit comments