-
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
Merged
seratch
merged 10 commits into
openai:main
from
adityasingh2400:feat/mcp-list-read-resources
Mar 21, 2026
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c59c740
feat(mcp): expose list_resources, list_resource_templates, and read_r…
adityasingh2400 de257c2
fix: make resource methods non-abstract to avoid breaking existing su…
adityasingh2400 df7336e
fix(typecheck): pass AnyUrl to ClientSession.read_resource; fix test …
adityasingh2400 bfa45e2
fix(typecheck): import AnyUrl from pydantic, not mcp.types
adityasingh2400 bfee07d
fix(style): clean up test imports — move pydantic AnyUrl to top, remo…
adityasingh2400 4fbb7ef
fix(typecheck): use pydantic.AnyUrl in server.py (mcp.types re-export…
adityasingh2400 9e4bd52
feat(mcp): add cursor pagination to list_resources and list_resource_…
adityasingh2400 1fbb553
fix(typecheck): add cursor param to FakeMCPServer stubs to match base…
adityasingh2400 af3b904
fix(lint): ruff format helpers.py
adityasingh2400 6c50eb3
docs: replace URI examples with AnyUrl type reference in docstrings
adityasingh2400 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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,62 @@ async def get_prompt( | |
| """Get a specific prompt from the server.""" | ||
| pass | ||
|
|
||
| async def list_resources(self, cursor: str | None = None) -> ListResourcesResult: | ||
| """List the resources available on the server. | ||
|
|
||
| Args: | ||
| cursor: An opaque pagination cursor returned in a previous | ||
| :class:`~mcp.types.ListResourcesResult` as ``nextCursor``. Pass it | ||
| here to fetch the next page of results. ``None`` fetches the first | ||
| page. | ||
|
|
||
| Returns a :class:`~mcp.types.ListResourcesResult`. When the result contains | ||
| a ``nextCursor`` field, call this method again with that cursor to retrieve | ||
| the next page. 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, cursor: str | None = None | ||
| ) -> ListResourceTemplatesResult: | ||
| """List the resource templates available on the server. | ||
|
|
||
| Args: | ||
| cursor: An opaque pagination cursor returned in a previous | ||
| :class:`~mcp.types.ListResourceTemplatesResult` as ``nextCursor``. | ||
| Pass it here to fetch the next page of results. ``None`` fetches | ||
| the first page. | ||
|
|
||
| Returns a :class:`~mcp.types.ListResourceTemplatesResult`. When the result | ||
| contains a ``nextCursor`` field, call this method again with that cursor to | ||
| retrieve the next page. 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 +772,39 @@ 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, cursor: str | None = None) -> 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(cursor)) | ||
|
|
||
| async def list_resource_templates( | ||
| self, cursor: str | None = None | ||
| ) -> 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(cursor)) | ||
|
|
||
| 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: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| """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_with(None) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_resources_forwards_cursor(server: MCPServerStreamableHttp): | ||
| """list_resources forwards the cursor argument for pagination.""" | ||
| mock_session = MagicMock() | ||
| page2 = ListResourcesResult(resources=[]) | ||
| mock_session.list_resources = AsyncMock(return_value=page2) | ||
| server.session = mock_session | ||
|
|
||
| result = await server.list_resources(cursor="tok_abc") | ||
|
|
||
| assert result is page2 | ||
| mock_session.list_resources.assert_awaited_once_with("tok_abc") | ||
|
|
||
|
|
||
| @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_with(None) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_resource_templates_forwards_cursor(server: MCPServerStreamableHttp): | ||
| """list_resource_templates forwards the cursor argument for pagination.""" | ||
| mock_session = MagicMock() | ||
| page2 = ListResourceTemplatesResult(resourceTemplates=[]) | ||
| mock_session.list_resource_templates = AsyncMock(return_value=page2) | ||
| server.session = mock_session | ||
|
|
||
| result = await server.list_resource_templates(cursor="tok_xyz") | ||
|
|
||
| assert result is page2 | ||
| mock_session.list_resource_templates.assert_awaited_once_with("tok_xyz") | ||
|
|
||
|
|
||
| @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") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.