Skip to content

Commit aedbcd6

Browse files
authored
Expose server_info in MCPServer (#3055)
1 parent a426d55 commit aedbcd6

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

pydantic_ai_slim/pydantic_ai/mcp.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ class MCPServer(AbstractToolset[Any], ABC):
112112
_client: ClientSession
113113
_read_stream: MemoryObjectReceiveStream[SessionMessage | Exception]
114114
_write_stream: MemoryObjectSendStream[SessionMessage]
115+
_server_info: mcp_types.Implementation
115116

116117
def __init__(
117118
self,
@@ -177,6 +178,15 @@ def label(self) -> str:
177178
def tool_name_conflict_hint(self) -> str:
178179
return 'Set the `tool_prefix` attribute to avoid name conflicts.'
179180

181+
@property
182+
def server_info(self) -> mcp_types.Implementation:
183+
"""Access the information send by the MCP server during initialization."""
184+
if getattr(self, '_server_info', None) is None:
185+
raise AttributeError(
186+
f'The `{self.__class__.__name__}.server_info` is only instantiated after initialization.'
187+
)
188+
return self._server_info
189+
180190
async def list_tools(self) -> list[mcp_types.Tool]:
181191
"""Retrieve tools that are currently active on the server.
182192
@@ -312,8 +322,8 @@ async def __aenter__(self) -> Self:
312322
self._client = await exit_stack.enter_async_context(client)
313323

314324
with anyio.fail_after(self.timeout):
315-
await self._client.initialize()
316-
325+
result = await self._client.initialize()
326+
self._server_info = result.serverInfo
317327
if log_level := self.log_level:
318328
await self._client.set_logging_level(log_level)
319329

tests/test_mcp.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1474,3 +1474,13 @@ def test_load_mcp_servers(tmp_path: Path):
14741474

14751475
with pytest.raises(FileNotFoundError):
14761476
load_mcp_servers(tmp_path / 'does_not_exist.json')
1477+
1478+
1479+
async def test_server_info(mcp_server: MCPServerStdio) -> None:
1480+
with pytest.raises(
1481+
AttributeError, match='The `MCPServerStdio.server_info` is only instantiated after initialization.'
1482+
):
1483+
mcp_server.server_info
1484+
async with mcp_server:
1485+
assert mcp_server.server_info is not None
1486+
assert mcp_server.server_info.name == 'Pydantic AI MCP Server'

0 commit comments

Comments
 (0)