Add tests for MCPServer.read_resource exception handling (#1957)

This commit is contained in:
Marcelo Trylesinski 2026-01-27 13:49:06 +01:00 • committed by GitHub
commit 14744c66c5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -347,16 +347,18 @@ class MCPServer(Generic[LifespanResultT]):
"""Read a resource by URI."""
context = self.get_context()
resource = await self._resource_manager.get_resource(uri, context=context)
if not resource: # pragma: no cover
try:
resource = await self._resource_manager.get_resource(uri, context=context)
except ValueError:
raise ResourceError(f"Unknown resource: {uri}")
try:
content = await resource.read()
return [ReadResourceContents(content=content, mime_type=resource.mime_type, meta=resource.meta)]
except Exception as e: # pragma: no cover
logger.exception(f"Error reading resource {uri}")
raise ResourceError(str(e))
except Exception as exc:
logger.exception(f"Error getting resource {uri}")
# If an exception happens when reading the resource, we should not leak the exception to the client.
raise ResourceError(f"Error reading resource {uri}") from exc
def add_tool(
self,