Add tests for MCPServer.read_resource exception handling (#1957)
This commit is contained in:
parent
6f0e8e7851
commit
14744c66c5
4 changed files with 165 additions and 254 deletions
|
|
@ -91,7 +91,7 @@ class Experimental:
|
|||
error = ErrorData(code=METHOD_NOT_FOUND, message="This tool does not support task-augmented invocation")
|
||||
|
||||
if error is not None and raise_error:
|
||||
raise MCPError(code=error.code, message=error.message)
|
||||
raise MCPError.from_error_data(error)
|
||||
|
||||
return error
|
||||
|
||||
|
|
|
|||
|
|
@ -795,12 +795,7 @@ class Server(Generic[LifespanResultT, RequestT]):
|
|||
|
||||
await message.respond(response)
|
||||
else: # pragma: no cover
|
||||
await message.respond(
|
||||
types.ErrorData(
|
||||
code=types.METHOD_NOT_FOUND,
|
||||
message="Method not found",
|
||||
)
|
||||
)
|
||||
await message.respond(types.ErrorData(code=types.METHOD_NOT_FOUND, message="Method not found"))
|
||||
|
||||
logger.debug("Response sent")
|
||||
|
||||
|
|
|
|||
|
|
@ -82,10 +82,8 @@ class ResourceManager:
|
|||
return template
|
||||
|
||||
async def get_resource(
|
||||
self,
|
||||
uri: AnyUrl | str,
|
||||
context: Context[ServerSessionT, LifespanContextT, RequestT] | None = None,
|
||||
) -> Resource | None:
|
||||
self, uri: AnyUrl | str, context: Context[ServerSessionT, LifespanContextT, RequestT] | None = None
|
||||
) -> Resource:
|
||||
"""Get resource by URI, checking concrete resources first, then templates."""
|
||||
uri_str = str(uri)
|
||||
logger.debug("Getting resource", extra={"uri": uri_str})
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Reference in a new issue