Read a resource by URI. Raises: ResourceNotFoundError: If no resource or template matches the URI. ResourceError: If template creation or resource reading fails.
(
self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None
)
| 429 | ] |
| 430 | |
| 431 | async def read_resource( |
| 432 | self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None |
| 433 | ) -> Iterable[ReadResourceContents]: |
| 434 | """Read a resource by URI. |
| 435 | |
| 436 | Raises: |
| 437 | ResourceNotFoundError: If no resource or template matches the URI. |
| 438 | ResourceError: If template creation or resource reading fails. |
| 439 | """ |
| 440 | if context is None: |
| 441 | context = Context(mcp_server=self) |
| 442 | resource = await self._resource_manager.get_resource(uri, context) |
| 443 | |
| 444 | try: |
| 445 | content = await resource.read() |
| 446 | return [ReadResourceContents(content=content, mime_type=resource.mime_type, meta=resource.meta)] |
| 447 | except Exception as exc: |
| 448 | logger.exception(f"Error getting resource {uri}") |
| 449 | # If an exception happens when reading the resource, we should not leak the exception to the client. |
| 450 | raise ResourceError(f"Error reading resource {uri}") from exc |
| 451 | |
| 452 | def add_tool( |
| 453 | self, |