-
Notifications
You must be signed in to change notification settings - Fork 4.1k
feat(mcp): expose list_resources, list_resource_templates, and read_resource on MCPServer #2721
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
c59c740
de257c2
df7336e
bfa45e2
bfee07d
4fbb7ef
9e4bd52
1fbb553
af3b904
6c50eb3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,7 +22,15 @@ | |
| from mcp.client.streamable_http import GetSessionIdCallback, streamablehttp_client | ||
| from mcp.shared.exceptions import McpError | ||
| from mcp.shared.message import SessionMessage | ||
| from mcp.types import CallToolResult, GetPromptResult, InitializeResult, ListPromptsResult | ||
| from mcp.types import ( | ||
| CallToolResult, | ||
| GetPromptResult, | ||
| InitializeResult, | ||
| ListPromptsResult, | ||
| ListResourcesResult, | ||
| ListResourceTemplatesResult, | ||
| ReadResourceResult, | ||
| ) | ||
| from typing_extensions import NotRequired, TypedDict | ||
|
|
||
| from ..exceptions import UserError | ||
|
|
@@ -192,6 +200,45 @@ async def get_prompt( | |
| """Get a specific prompt from the server.""" | ||
| pass | ||
|
|
||
| async def list_resources(self) -> ListResourcesResult: | ||
| """List the resources available on the server. | ||
|
|
||
| Returns a :class:`~mcp.types.ListResourcesResult` containing all resources | ||
| exposed by the server. Subclasses that do not support resources may leave | ||
| this unimplemented; it will raise :exc:`NotImplementedError` at call time. | ||
| """ | ||
| raise NotImplementedError( | ||
| f"MCP server '{self.name}' does not support list_resources. " | ||
| "Override this method in your server implementation." | ||
| ) | ||
|
|
||
| async def list_resource_templates(self) -> ListResourceTemplatesResult: | ||
| """List the resource templates available on the server. | ||
|
|
||
| Returns a :class:`~mcp.types.ListResourceTemplatesResult`. Subclasses that | ||
| do not support resource templates may leave this unimplemented; it will raise | ||
| :exc:`NotImplementedError` at call time. | ||
| """ | ||
| raise NotImplementedError( | ||
| f"MCP server '{self.name}' does not support list_resource_templates. " | ||
| "Override this method in your server implementation." | ||
| ) | ||
|
|
||
| async def read_resource(self, uri: str) -> ReadResourceResult: | ||
| """Read the contents of a specific resource by URI. | ||
|
|
||
| Args: | ||
| uri: The URI of the resource to read (e.g. ``file:///path/to/file.txt``). | ||
|
|
||
| Returns a :class:`~mcp.types.ReadResourceResult`. Subclasses that do not | ||
| support resources may leave this unimplemented; it will raise | ||
| :exc:`NotImplementedError` at call time. | ||
| """ | ||
| raise NotImplementedError( | ||
| f"MCP server '{self.name}' does not support read_resource. " | ||
| "Override this method in your server implementation." | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _normalize_needs_approval( | ||
| *, | ||
|
|
@@ -708,6 +755,37 @@ async def get_prompt( | |
| assert session is not None | ||
| return await self._maybe_serialize_request(lambda: session.get_prompt(name, arguments)) | ||
|
|
||
| async def list_resources(self) -> ListResourcesResult: | ||
| """List the resources available on the server.""" | ||
| if not self.session: | ||
| raise UserError("Server not initialized. Make sure you call `connect()` first.") | ||
| session = self.session | ||
| assert session is not None | ||
| return await self._maybe_serialize_request(lambda: session.list_resources()) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Useful? React with 👍 / 👎. |
||
|
|
||
| async def list_resource_templates(self) -> ListResourceTemplatesResult: | ||
| """List the resource templates available on the server.""" | ||
| if not self.session: | ||
| raise UserError("Server not initialized. Make sure you call `connect()` first.") | ||
| session = self.session | ||
| assert session is not None | ||
| return await self._maybe_serialize_request(lambda: session.list_resource_templates()) | ||
|
|
||
| async def read_resource(self, uri: str) -> ReadResourceResult: | ||
| """Read the contents of a specific resource by URI. | ||
|
|
||
| Args: | ||
| uri: The URI of the resource to read (e.g. ``file:///path/to/file.txt`` or | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can you simply mention AnyUrl docstring as reference? We'd like to avoid mentioning specific examples and having our own comment, which can be outdated in the future. |
||
| ``postgres://db/table/row``). | ||
| """ | ||
| if not self.session: | ||
| raise UserError("Server not initialized. Make sure you call `connect()` first.") | ||
| session = self.session | ||
| assert session is not None | ||
| from pydantic import AnyUrl | ||
|
|
||
| return await self._maybe_serialize_request(lambda: session.read_resource(AnyUrl(uri))) | ||
|
|
||
| async def cleanup(self): | ||
| """Cleanup the server.""" | ||
| async with self._cleanup_lock: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,7 +11,10 @@ | |
| Content, | ||
| GetPromptResult, | ||
| ListPromptsResult, | ||
| ListResourcesResult, | ||
| ListResourceTemplatesResult, | ||
| PromptMessage, | ||
| ReadResourceResult, | ||
| TextContent, | ||
| ) | ||
|
|
||
|
|
@@ -138,6 +141,18 @@ async def get_prompt( | |
| message = PromptMessage(role="user", content=TextContent(type="text", text=content)) | ||
| return GetPromptResult(description=f"Fake prompt: {name}", messages=[message]) | ||
|
|
||
| async def list_resources(self) -> ListResourcesResult: | ||
| """Return empty list of resources for fake server.""" | ||
| return ListResourcesResult(resources=[]) | ||
|
|
||
| async def list_resource_templates(self) -> ListResourceTemplatesResult: | ||
| """Return empty list of resource templates for fake server.""" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Useful? React with 👍 / 👎. |
||
| return ListResourceTemplatesResult(resourceTemplates=[]) | ||
|
|
||
| async def read_resource(self, uri: str) -> ReadResourceResult: | ||
| """Return empty resource contents for fake server.""" | ||
| return ReadResourceResult(contents=[]) | ||
|
|
||
| @property | ||
| def name(self) -> str: | ||
| return self._server_name | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| """Tests for MCP server list_resources, list_resource_templates, and read_resource.""" | ||
|
|
||
| from unittest.mock import AsyncMock, MagicMock | ||
|
|
||
| import pytest | ||
| from mcp.types import ( | ||
| ListResourcesResult, | ||
| ListResourceTemplatesResult, | ||
| ReadResourceResult, | ||
| Resource, | ||
| ResourceTemplate, | ||
| TextResourceContents, | ||
| ) | ||
| from pydantic import AnyUrl | ||
|
|
||
| from agents.mcp import MCPServerStreamableHttp | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def server(): | ||
| return MCPServerStreamableHttp(params={"url": "http://localhost:8000/mcp"}) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_resources_raises_when_not_connected(server: MCPServerStreamableHttp): | ||
| """list_resources raises UserError when server has not been connected.""" | ||
| from agents.exceptions import UserError | ||
|
|
||
| with pytest.raises(UserError, match="Server not initialized"): | ||
| await server.list_resources() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_resource_templates_raises_when_not_connected(server: MCPServerStreamableHttp): | ||
| """list_resource_templates raises UserError when server has not been connected.""" | ||
| from agents.exceptions import UserError | ||
|
|
||
| with pytest.raises(UserError, match="Server not initialized"): | ||
| await server.list_resource_templates() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_read_resource_raises_when_not_connected(server: MCPServerStreamableHttp): | ||
| """read_resource raises UserError when server has not been connected.""" | ||
| from agents.exceptions import UserError | ||
|
|
||
| with pytest.raises(UserError, match="Server not initialized"): | ||
| await server.read_resource("file:///etc/hosts") | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_resources_returns_result(server: MCPServerStreamableHttp): | ||
| """list_resources delegates to the underlying MCP session.""" | ||
| mock_session = MagicMock() | ||
| expected = ListResourcesResult( | ||
| resources=[ | ||
| Resource(uri=AnyUrl("file:///readme.md"), name="readme.md", mimeType="text/markdown"), | ||
| ] | ||
| ) | ||
| mock_session.list_resources = AsyncMock(return_value=expected) | ||
| server.session = mock_session | ||
|
|
||
| result = await server.list_resources() | ||
|
|
||
| assert result is expected | ||
| mock_session.list_resources.assert_awaited_once() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_resource_templates_returns_result(server: MCPServerStreamableHttp): | ||
| """list_resource_templates delegates to the underlying MCP session.""" | ||
| mock_session = MagicMock() | ||
| expected = ListResourceTemplatesResult( | ||
| resourceTemplates=[ | ||
| ResourceTemplate(uriTemplate="file:///{path}", name="file"), | ||
| ] | ||
| ) | ||
| mock_session.list_resource_templates = AsyncMock(return_value=expected) | ||
| server.session = mock_session | ||
|
|
||
| result = await server.list_resource_templates() | ||
|
|
||
| assert result is expected | ||
| mock_session.list_resource_templates.assert_awaited_once() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_read_resource_returns_result(server: MCPServerStreamableHttp): | ||
| """read_resource delegates to the underlying MCP session with the given URI.""" | ||
| mock_session = MagicMock() | ||
| uri = "file:///readme.md" | ||
| expected = ReadResourceResult( | ||
| contents=[ | ||
| TextResourceContents(uri=AnyUrl(uri), text="# Hello", mimeType="text/markdown"), | ||
| ] | ||
| ) | ||
| mock_session.read_resource = AsyncMock(return_value=expected) | ||
| server.session = mock_session | ||
|
|
||
| result = await server.read_resource(uri) | ||
|
|
||
| assert result is expected | ||
| mock_session.read_resource.assert_awaited_once_with(AnyUrl(uri)) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_base_methods_raise_not_implemented(): | ||
| """Bare MCPServer subclasses that don't override resource methods get NotImplementedError.""" | ||
| from mcp.types import CallToolResult, GetPromptResult, ListPromptsResult | ||
|
|
||
| from agents.mcp import MCPServer | ||
|
|
||
| class MinimalServer(MCPServer): | ||
| """Minimal subclass implementing only the truly abstract methods.""" | ||
|
|
||
| @property | ||
| def name(self) -> str: | ||
| return "minimal" | ||
|
|
||
| async def connect(self) -> None: | ||
| pass | ||
|
|
||
| async def cleanup(self) -> None: | ||
| pass | ||
|
|
||
| async def list_tools(self, run_context=None, agent=None): | ||
| return [] | ||
|
|
||
| async def call_tool(self, tool_name, tool_arguments, run_context=None, agent=None): | ||
| return CallToolResult(content=[]) | ||
|
|
||
| async def list_prompts(self): | ||
| return ListPromptsResult(prompts=[]) | ||
|
|
||
| async def get_prompt(self, name, arguments=None): | ||
| return GetPromptResult(messages=[]) | ||
|
|
||
| s = MinimalServer() | ||
|
|
||
| with pytest.raises(NotImplementedError, match="list_resources"): | ||
| await s.list_resources() | ||
|
|
||
| with pytest.raises(NotImplementedError, match="list_resource_templates"): | ||
| await s.list_resource_templates() | ||
|
|
||
| with pytest.raises(NotImplementedError, match="read_resource"): | ||
| await s.read_resource("file:///test.txt") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you simply mention AnyUrl docstring as reference? We'd like to avoid mentioning specific examples and having our own comment, which can be outdated in the future.