Skip to content

Your lightweight open-source personal agent.

merge main into pr-554

Re-bin54d5f637e7be
diff --cc nanobot/agent/loop.py
index b15803ae9,c256a56f2..cc7a0d0ea
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@@ -112,25 -116,85 +121,96 @@@ class AgentLoop
if self.cron_service:
self.tools.register(CronTool(self.cron_service))
+ async def _connect_mcp(self) -> None:
+ """Connect to configured MCP servers (one-time, lazy)."""
+ if self._mcp_connected or not self._mcp_servers:
+ return
+ self._mcp_connected = True
+ from nanobot.agent.tools.mcp import connect_mcp_servers
+ self._mcp_stack = AsyncExitStack()
+ await self._mcp_stack.__aenter__()
+ await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack)
+
+ def _set_tool_context(self, channel: str, chat_id: str) -> None:
+ """Update context for all tools that need routing info."""
+ if message_tool := self.tools.get("message"):
+ if isinstance(message_tool, MessageTool):
+ message_tool.set_context(channel, chat_id)
+
+ if spawn_tool := self.tools.get("spawn"):
+ if isinstance(spawn_tool, SpawnTool):
+ spawn_tool.set_context(channel, chat_id)
+
+ if cron_tool := self.tools.get("cron"):
+ if isinstance(cron_tool, CronTool):
+ cron_tool.set_context(channel, chat_id)
+
+ async def _run_agent_loop(self, initial_messages: list[dict]) -> tuple[str | None, list[str]]:
+ """
+ Run the agent iteration loop.
+
+ Args:
+ initial_messages: Starting messages for the LLM conversation.
+
+ Returns:
+ Tuple of (final_content, list_of_tools_used).
+ """
+ messages = initial_messages
+ iteration = 0
+ final_content = None
+ tools_used: list[str] = []
+
+ while iteration < self.max_iterations:
+ iteration += 1
+
+ response = await self.provider.chat(
+ messages=messages,
+ tools=self.tools.get_definitions(),
+ model=self.model,
+ temperature=self.temperature,
+ max_tokens=self.max_tokens,
+ )
+
+ if response.has_tool_calls:
+ tool_call_dicts = [
+ {
+ "id": tc.id,
+ "type": "function",
+ "function": {
+ "name": tc.name,
+ "arguments": json.dumps(tc.arguments)
+ }
+ }
+ for tc in response.tool_calls
+ ]
+ messages = self.context.add_assistant_message(
+ messages, response.content, tool_call_dicts,
+ reasoning_content=response.reasoning_content,
+ )
+
+ for tool_call in response.tool_calls:
+ tools_used.append(tool_call.name)
+ args_str = json.dumps(tool_call.arguments, ensure_ascii=False)
+ logger.info(f"Tool call: {tool_call.name}({args_str[:200]})")
+ result = await self.tools.execute(tool_call.name, tool_call.arguments)
+ messages = self.context.add_tool_result(
+ messages, tool_call.id, tool_call.name, result
+ )
+ messages.append({"role": "user", "content": "Reflect on the results and decide next steps."})
+ else:
+ final_content = response.content
+ break
+
+ return final_content, tools_used
+
async def run(self) -> None:
"""Run the agent loop, processing messages from the bus."""
self._running = True
+ await self._connect_mcp()
logger.info("Agent loop started")
-
+
while self._running:
try:
- # Wait for next message
msg = await asyncio.wait_for(
self.bus.consume_inbound(),
timeout=1.0