Building AI agents, atomically
Cleanup
KennyVaneetvelde08de84f638ad
diff --git a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.pyindex d86a80b..d5f07c4 100644--- a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py+++ b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py@@ -1,6 +1,6 @@import asyncioimport logging-from typing import Any, Dict, List, Type, Optional, Union, Tuple, cast+from typing import Any, List, Type, Optional, Union, Tuple, castfrom contextlib import AsyncExitStackimport shlex@@ -24,28 +24,6 @@ class MCPToolOutputSchema(BaseIOSchema):result: Any = Field(..., description="The result returned by the MCP tool.")-# Keep these for backward compatibility - will be deprecated in future-def _json_schema_to_pydantic_field(prop_schema: Dict[str, Any], required: bool) -> tuple:- """- Legacy function for backward compatibility.- Use SchemaTransformer.json_to_pydantic_field instead.- """- return SchemaTransformer.json_to_pydantic_field(prop_schema, required)---def json_schema_to_pydantic_model(- schema: Dict[str, Any],- model_name: str,- tool_name_literal: str,- docstring: Optional[str] = None,-) -> Type[BaseIOSchema]:- """- Legacy function for backward compatibility.- Use SchemaTransformer.create_model_from_schema instead.- """- return SchemaTransformer.create_model_from_schema(schema, model_name, tool_name_literal, docstring)--class MCPToolFactory:"""Factory for creating MCP tool classes."""@@ -100,20 +78,16 @@ class MCPToolFactory:Returns:List of tool definitions"""- try:- if self.client_session is not None:- # Use existing session- async def _gather_defs():- return await ToolDefinitionService.fetch_definitions_from_session(self.client_session) # pragma: no cover-- return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover- else:- # Create new connection- service = ToolDefinitionService(self.mcp_endpoint, self.use_stdio, self.working_directory)- return asyncio.run(service.fetch_definitions())- except Exception:- # Let exceptions propagate - they're already logged in the service- raise+ if self.client_session is not None:+ # Use existing session+ async def _gather_defs():+ return await ToolDefinitionService.fetch_definitions_from_session(self.client_session) # pragma: no cover++ return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover+ else:+ # Create new connection+ service = ToolDefinitionService(self.mcp_endpoint, self.use_stdio, self.working_directory)+ return asyncio.run(service.fetch_definitions())def _create_tool_classes(self, tool_definitions: List[MCPToolDefinition]) -> List[Type[BaseTool]]:"""@@ -281,9 +255,7 @@ class MCPToolFactory:return orchestrator_schema-# Public API functions - these maintain backward compatibility--+# Public API functionsdef fetch_mcp_tools(mcp_endpoint: Optional[str] = None,use_stdio: bool = False,diff --git a/atomic-agents/tests/lib/factories/test_mcp_tool_factory.py b/atomic-agents/tests/lib/factories/test_mcp_tool_factory.pyindex d4c97dd..bf074d7 100644--- a/atomic-agents/tests/lib/factories/test_mcp_tool_factory.py+++ b/atomic-agents/tests/lib/factories/test_mcp_tool_factory.py@@ -1,16 +1,13 @@import pytestfrom pydantic import BaseModel+import asynciofrom atomic_agents.lib.factories.mcp_tool_factory import (fetch_mcp_tools,create_mcp_orchestrator_schema,fetch_mcp_tools_with_schema,MCPToolFactory,- json_schema_to_pydantic_model,- _json_schema_to_pydantic_field,)-from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinition-from atomic_agents.lib.base.base_io_schema import BaseIOSchema-import asyncio+from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinition, ToolDefinitionServiceclass DummySession:@@ -94,34 +91,6 @@ def test_fetch_mcp_tools_with_schema_nonempty(monkeypatch):assert schema is dummy_schema-def test_json_schema_to_pydantic_model():- schema = {- "type": "object",- "properties": {- "foo": {"type": "string", "description": "desc", "default": "bar"},- },- "required": ["foo"],- }- Model = json_schema_to_pydantic_model(schema, "TestModel", "ToolY", "TestDoc")- assert issubclass(Model, BaseIOSchema)- assert Model.__doc__ == "TestDoc"- inst = Model(foo="baz", tool_name="ToolY")- assert inst.foo == "baz"- assert inst.tool_name == "ToolY"---def test_json_to_pydantic_field_private_required_and_optional():- # required field should have non-None default and correct description- typ, field = _json_schema_to_pydantic_field({"type": "string", "description": "desc"}, required=True)- assert typ is str- assert field.default is not None- assert field.description == "desc"- # optional field should default to None and preserve description- typ2, field2 = _json_schema_to_pydantic_field({"type": "string", "description": "d2"}, required=False)- assert field2.default is None- assert field2.description == "d2"--def test_fetch_mcp_tools_with_stdio_and_working_directory(monkeypatch):input_schema = {"type": "object", "properties": {}, "required": []}definitions = [MCPToolDefinition(name="ToolZ", description=None, input_schema=input_schema)]@@ -189,7 +158,6 @@ def test_run_tool(monkeypatch, use_stdio):def test_run_tool_with_persistent_session(monkeypatch):import atomic_agents.lib.factories.mcp_tool_factory as mtf- import asyncio# Setup persistent clientclass DummySessionPersistent:@@ -248,8 +216,6 @@ def test_fetch_tool_definitions_propagates_error(monkeypatch):def test_run_tool_handles_special_result_types(monkeypatch):import atomic_agents.lib.factories.mcp_tool_factory as mtf- from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinition- from pydantic import BaseModelclass DummyTransportCM:def __init__(self, ret):@@ -309,7 +275,6 @@ def test_run_tool_handles_special_result_types(monkeypatch):def test_run_invalid_stdio_command_raises(monkeypatch):import atomic_agents.lib.factories.mcp_tool_factory as mtf- from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinitionclass DummyTransportCM:def __init__(self, ret):@@ -344,10 +309,6 @@ def test_run_invalid_stdio_command_raises(monkeypatch):def test_create_tool_classes_skips_invalid(monkeypatch):- from atomic_agents.lib.factories.mcp_tool_factory import MCPToolFactory- from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinition- from atomic_agents.lib.base.base_io_schema import BaseIOSchema-factory = MCPToolFactory("endpoint", False)defs = [MCPToolDefinition(name="Bad", description=None, input_schema={"type": "object", "properties": {}, "required": []}),@@ -358,7 +319,7 @@ def test_create_tool_classes_skips_invalid(monkeypatch):def create_model_from_schema(self, schema, model_name, tname, doc):if tname == "Bad":raise ValueError("fail")- return BaseIOSchema+ return BaseModelfactory.schema_transformer = FakeST()tools = factory._create_tool_classes(defs)@@ -384,9 +345,7 @@ def test_force_mark_unreachable_lines_for_coverage():def test__fetch_tool_definitions_service_branch(monkeypatch):"""Covers lines 112-113: ToolDefinitionService branch in _fetch_tool_definitions."""- from atomic_agents.lib.factories.mcp_tool_factory import MCPToolFactory- from atomic_agents.lib.factories.tool_definition_service import ToolDefinitionService- import asyncio+ factory = MCPToolFactory("dummy_endpoint", False)# Patch fetch_definitions to avoid real async workasync def dummy_fetch_definitions(self):@@ -395,8 +354,6 @@ def test__fetch_tool_definitions_service_branch(monkeypatch):]monkeypatch.setattr(ToolDefinitionService, "fetch_definitions", dummy_fetch_definitions)-- factory = MCPToolFactory("dummy_endpoint", False)result = factory._fetch_tool_definitions()assert result[0].name == "COV"@@ -421,7 +378,6 @@ async def test_cover_line_195_async_test():def test_run_tool_with_persistent_session_no_event_loop(monkeypatch):"""Covers AttributeError when no event loop is provided for persistent session."""import atomic_agents.lib.factories.mcp_tool_factory as mtf- import asyncio# Setup persistent clientclass DummySessionPersistent:diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.pyindex 0174913..b211da7 100644--- a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py+++ b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py@@ -23,7 +23,7 @@ from mcp.client.stdio import stdio_clientclass MCPConfig:"""Configuration for the MCP Agent system using STDIO transport."""- openai_model: str = "gpt-4o-mini"+ openai_model: str = "gpt-4o"openai_api_key: str = os.getenv("OPENAI_API_KEY")# Command to run the STDIO server.@@ -135,28 +135,21 @@ def main():memory=memory,system_prompt_generator=SystemPromptGenerator(background=[- "You are an MCP Orchestrator Agent, designed to intelligently route user queries to appropriate "- "tools or provide direct responses.",- "Your primary responsibility is to analyze user queries and determine the most effective way to "- "handle them using the available tools.",- "You have access to a variety of specialized tools, each with specific capabilities and "- "input requirements.",+ "You are an MCP Orchestrator Agent, designed to chat with users and",+ "determine the best way to handle their queries using the available tools.",],steps=[- "1. Carefully analyze the user's query to understand their intent and requirements.",- "2. Evaluate whether the query can be handled by an available tool or requires a direct response.",- "3. If using a tool: Extract and validate all necessary parameters from the query.",- "4. If providing a direct response: Formulate a clear, helpful response that addresses the query.",+ "1. Use the reasoning field to determine if one or more successive tool calls could be used to handle the user's query.",+ "2. If so, choose the appropriate tool(s) one at a time and extract all necessary parameters from the query.",+ "3. If a single tool can not be used to handle the user's query, think about how to break down the query into smaller tasks and route them to the appropriate tool(s).",+ "4. If no sequence of tools could be used, or if you are finished processing the user's query, provide a final response to the user.",],output_instructions=[- "Always provide a detailed explanation of your decision-making process in the 'reasoning' field.",- "Choose exactly one action schema that best matches the user's needs.",- "Ensure all required parameters are properly extracted and validated.",- "Maintain a professional and helpful tone in all responses.",- (- "If applicable, it is important to break down the user's query into smaller, more manageable "- "tasks and route them to the appropriate tool before responding with a final response."- ),+ "1. Always provide a detailed explanation of your decision-making process in the 'reasoning' field.",+ "2. Choose exactly one action schema (either a tool input or FinalResponseSchema).",+ "3. Ensure all required parameters for the chosen tool are properly extracted and validated.",+ "4. Maintain a professional and helpful tone in all responses.",+ "5. Break down complex queries into sequential tool calls before giving the final answer via `FinalResponseSchema`.",],),input_schema=MCPOrchestratorInputSchema,