refactor: move MCP lifecycle out of AgentLoop (#5343)

This commit is contained in:
chengyongru authored and GitHub committed 2026-08-12 17:51:04 +08:00
1 parent 686dd0603e
commit 19997d20bb
39 files changed
+1192 -846

No files matched your search

+24 -4
View File
@@ -10,6 +10,8 @@ from typing import Any
from nanobot.agent.hook import AgentHook, SDKCaptureHook
from nanobot.agent.hooks import create_file_edit_activity_hook
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.mcp import MCPProvider
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.config.schema import Config
from nanobot.providers.image_generation import image_gen_provider_configs
from nanobot.sdk.clients import MemoryClient, RuntimeClient, SessionClient
@@ -71,9 +73,16 @@ class Nanobot:
print(result.content)
"""
def __init__(self, loop: AgentLoop, *, config: Config | None = None) -> None:
def __init__(
self,
loop: AgentLoop,
*,
config: Config | None = None,
mcp_provider: MCPProvider | None = None,
) -> None:
self._loop = loop
self._config = config
self._mcp_provider = mcp_provider
self.sessions = SessionClient(loop)
self.memory = MemoryClient(loop)
self.runtime = RuntimeClient(loop)
@@ -120,12 +129,15 @@ class Nanobot:
elif model_preset is not None:
config.agents.defaults.model_preset = model_preset
tools = ToolRegistry()
mcp_provider = MCPProvider.from_config(config, tools)
loop = AgentLoop.from_config(
config,
image_generation_provider_configs=image_gen_provider_configs(config),
hook_factories=[create_file_edit_activity_hook],
tool_registry=tools,
)
return cls(loop, config=config)
return cls(loop, config=config, mcp_provider=mcp_provider)
async def run(
self,
@@ -178,6 +190,8 @@ class Nanobot:
)
if runtime is not None:
kwargs["runtime"] = runtime
if self._mcp_provider is not None:
await self._mcp_provider.connect()
response = await self._loop.process_direct(
message,
**kwargs,
@@ -259,6 +273,8 @@ class Nanobot:
if override_runtime is not None:
kwargs["runtime"] = override_runtime
try:
if self._mcp_provider is not None:
await self._mcp_provider.connect()
response = await self._loop.process_direct(
message,
**kwargs,
@@ -327,8 +343,12 @@ class Nanobot:
await run.aclose()
async def aclose(self) -> None:
"""Release resources held by this instance (MCP connections, etc.)."""
await self._loop.close_mcp()
"""Release resources held by this instance."""
try:
await self._loop.aclose()
finally:
if self._mcp_provider is not None:
await self._mcp_provider.aclose()
async def __aenter__(self) -> Nanobot:
return self