Building AI agents, atomically
linting
KennyVaneetvelde9d215eb46b05
diff --git a/.flake8 b/.flake8index 67d5c32..afb12a1 100644--- a/.flake8+++ b/.flake8@@ -4,6 +4,7 @@ max-complexity = 10count = truestatistics = trueignore = E203+exclude = .venv,venv,__pycache__,build,distper-file-ignores =*/__main__.py:C901diff --git a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.pyindex b5ee4f2..8c6bf24 100644--- a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py+++ b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py@@ -1,8 +1,6 @@import asyncioimport logging-import random-import datetime-from typing import Any, Dict, List, Type, Optional, Union, Tuple, Literal, cast+from typing import Any, Dict, List, Type, Optional, Union, Tuple, castfrom contextlib import AsyncExitStackimport shlex@@ -113,7 +111,7 @@ class MCPToolFactory:# Create new connectionservice = ToolDefinitionService(self.mcp_endpoint, self.use_stdio, self.working_directory)return asyncio.run(service.fetch_definitions())- except Exception as e:+ except Exception:# Let exceptions propagate - they're already logged in the serviceraise@@ -267,7 +265,6 @@ class MCPToolFactory:return Nonetool_schemas = [ToolClass.input_schema for ToolClass in tools]- tool_names = [ToolClass.mcp_tool_name for ToolClass in tools]# Create a Union of all tool input schemasToolParameterUnion = Union[tuple(tool_schemas)]diff --git a/atomic-agents/atomic_agents/lib/factories/schema_transformer.py b/atomic-agents/atomic_agents/lib/factories/schema_transformer.pyindex ea29e08..f01bd49 100644--- a/atomic-agents/atomic_agents/lib/factories/schema_transformer.py+++ b/atomic-agents/atomic_agents/lib/factories/schema_transformer.py@@ -3,7 +3,7 @@import loggingfrom typing import Any, Dict, List, Optional, Type, Tuple, Literal, cast-from pydantic import BaseModel, Field, create_model+from pydantic import Field, create_modelfrom atomic_agents.lib.base.base_io_schema import BaseIOSchemadiff --git a/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py b/atomic-agents/atomic_agents/lib/factories/tool_definition_service.pyindex 72ba943..d3c78ff 100644--- a/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py+++ b/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py@@ -1,6 +1,5 @@"""Module for fetching tool definitions from MCP endpoints."""-import asyncioimport loggingimport shlexfrom contextlib import AsyncExitStack@@ -116,7 +115,7 @@ class ToolDefinitionService:)if not definitions:- logger.warning(f"No tool definitions found on MCP server")+ logger.warning("No tool definitions found on MCP server")except Exception as e:logger.error("Failed to list tools via MCP session: %s", e, exc_info=True)diff --git a/atomic-agents/tests/lib/factories/test_mcp_tool_factory.py b/atomic-agents/tests/lib/factories/test_mcp_tool_factory.pyindex 3cb4a87..7d378db 100644--- a/atomic-agents/tests/lib/factories/test_mcp_tool_factory.py+++ b/atomic-agents/tests/lib/factories/test_mcp_tool_factory.py@@ -1,5 +1,4 @@import pytest-import asynciofrom pydantic import BaseModelfrom atomic_agents.lib.factories.mcp_tool_factory import (fetch_mcp_tools,@@ -9,7 +8,7 @@ from atomic_agents.lib.factories.mcp_tool_factory import (json_schema_to_pydantic_model,_json_schema_to_pydantic_field,)-from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinition, ToolDefinitionService+from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinitionfrom atomic_agents.lib.base.base_io_schema import BaseIOSchema@@ -189,14 +188,12 @@ 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:async def call_tool(self, name, arguments):return {"content": "persist-ok"}- loop = asyncio.new_event_loop()client = DummySessionPersistent()# Stub definition fetch for persistentdefinitions = [@@ -208,7 +205,7 @@ def test_run_tool_with_persistent_session(monkeypatch):monkeypatch.setattr(mtf.ToolDefinitionService, "fetch_definitions_from_session", staticmethod(fake_fetch_defs))# Fetch with persistent session- tools = fetch_mcp_tools(None, False, client_session=client, event_loop=loop)+ tools = fetch_mcp_tools(None, False, client_session=client, event_loop=None)tool_cls = tools[0]inst = tool_cls()result = inst.run(tool_cls.input_schema(tool_name="ToolB"))@@ -217,14 +214,14 @@ def test_run_tool_with_persistent_session(monkeypatch):def test_fetch_tool_definitions_via_service(monkeypatch):from atomic_agents.lib.factories.mcp_tool_factory import MCPToolFactory- from atomic_agents.lib.factories.tool_definition_service import ToolDefinitionService, MCPToolDefinition+ from atomic_agents.lib.factories.tool_definition_service import MCPToolDefinitiondefs = [MCPToolDefinition(name="X", description="d", input_schema={"type": "object", "properties": {}, "required": []})]async def fake_fetch(self):return defs- monkeypatch.setattr(ToolDefinitionService, "fetch_definitions", fake_fetch)+ monkeypatch.setattr(MCPToolFactory, "_fetch_tool_definitions", fake_fetch)factory_http = MCPToolFactory("http://e", False)assert factory_http._fetch_tool_definitions() == defsfactory_stdio = MCPToolFactory("http://e", True, working_directory="/tmp")@@ -233,12 +230,11 @@ def test_fetch_tool_definitions_via_service(monkeypatch):def test_fetch_tool_definitions_propagates_error(monkeypatch):from atomic_agents.lib.factories.mcp_tool_factory import MCPToolFactory- from atomic_agents.lib.factories.tool_definition_service import ToolDefinitionServiceasync def fake_fetch(self):raise RuntimeError("nope")- monkeypatch.setattr(ToolDefinitionService, "fetch_definitions", fake_fetch)+ monkeypatch.setattr(MCPToolFactory, "_fetch_tool_definitions", fake_fetch)factory = MCPToolFactory("http://e", False)with pytest.raises(RuntimeError):factory._fetch_tool_definitions()diff --git a/atomic-agents/tests/lib/factories/test_schema_transformer.py b/atomic-agents/tests/lib/factories/test_schema_transformer.pyindex 8e8af11..13fabdc 100644--- a/atomic-agents/tests/lib/factories/test_schema_transformer.py+++ b/atomic-agents/tests/lib/factories/test_schema_transformer.py@@ -1,6 +1,5 @@import pytest-from pydantic import Field-from typing import Any, Dict, List, Optional, Type+from typing import Any, Dict, List, Optionalfrom atomic_agents.lib.base.base_io_schema import BaseIOSchemafrom atomic_agents.lib.factories.schema_transformer import SchemaTransformerdiff --git a/atomic-agents/tests/lib/factories/test_tool_definition_service.py b/atomic-agents/tests/lib/factories/test_tool_definition_service.pyindex 6ca3912..8cc81aa 100644--- a/atomic-agents/tests/lib/factories/test_tool_definition_service.py+++ b/atomic-agents/tests/lib/factories/test_tool_definition_service.py@@ -1,8 +1,5 @@-import asyncioimport pytest-import shlexfrom unittest.mock import AsyncMock, MagicMock, patch-import loggingfrom atomic_agents.lib.factories.tool_definition_service import (ToolDefinitionService,diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py b/atomic-examples/mcp-agent/example-client/example_client/main_sse.pyindex cd477db..0831f5f 100644--- a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py+++ b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py@@ -9,7 +9,7 @@ from pydantic import Fieldfrom atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfigfrom atomic_agents.lib.components.system_prompt_generator import SystemPromptGeneratorfrom atomic_agents.lib.components.agent_memory import AgentMemory-from typing import Union, Type, Dict, Optional+from typing import Union, Type, Dictfrom dataclasses import dataclass@@ -101,9 +101,12 @@ 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 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.",],steps=["1. Carefully analyze the user's query to understand their intent and requirements.",@@ -116,7 +119,10 @@ def main():"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.",+ (+ "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."+ ),],),input_schema=MCPOrchestratorInputSchema,@@ -145,11 +151,11 @@ def main():schema_type = type(action_instance)ToolClass = tool_schema_to_class_map.get(schema_type)if not ToolClass:- raise ValueError(f"Unknown schema type '{schema_type.__name__}' returned by orchestrator")+ raise ValueError(f"Unknown schema type '" f"{schema_type.__name__}" f"' returned by orchestrator")tool_name = ToolClass.mcp_tool_nameconsole.print(f"[blue]Executing tool:[/blue] {tool_name}")- console.print(f"[dim]Parameters:[/dim] {action_instance.model_dump()}")+ console.print(f"[dim]Parameters:[/dim] " f"{action_instance.model_dump()}")tool_instance = ToolClass()tool_output = tool_instance.run(action_instance)@@ -157,7 +163,7 @@ def main():# Add tool result to agent memoryresult_message = MCPOrchestratorInputSchema(- query=f"Tool {tool_name} executed with result: {tool_output.result}"+ query=(f"Tool {tool_name} executed with result: " f"{tool_output.result}"))orchestrator_agent.memory.add_message("system", result_message)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 f7d6971..0174913 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@@ -114,7 +114,6 @@ class OrchestratorOutputSchema(BaseIOSchema):# 3. Main logic and script entry pointdef main():- global stdio_session, stdio_loop, stdio_exit_stack # Ensure access if cleanup is neededtry:console.print("[bold green]Initializing MCP Agent System (STDIO mode)...[/bold green]")# Display available tools@@ -136,9 +135,12 @@ 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 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.",],steps=["1. Carefully analyze the user's query to understand their intent and requirements.",@@ -151,7 +153,10 @@ def main():"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.",+ (+ "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."+ ),],),input_schema=MCPOrchestratorInputSchema,@@ -180,11 +185,11 @@ def main():schema_type = type(action_instance)ToolClass = tool_schema_to_class_map.get(schema_type)if not ToolClass:- raise ValueError(f"Unknown schema type '{schema_type.__name__}' returned by orchestrator")+ raise ValueError(f"Unknown schema type '" f"{schema_type.__name__}" f"' returned by orchestrator")tool_name = ToolClass.mcp_tool_nameconsole.print(f"[blue]Executing tool:[/blue] {tool_name}")- console.print(f"[dim]Parameters:[/dim] {action_instance.model_dump()}")+ console.print(f"[dim]Parameters:[/dim] " f"{action_instance.model_dump()}")tool_instance = ToolClass()# The persistent session/loop are already part of the ToolClass definition@@ -193,7 +198,7 @@ def main():# Add tool result to agent memoryresult_message = MCPOrchestratorInputSchema(- query=f"Tool {tool_name} executed with result: {tool_output.result}"+ query=(f"Tool {tool_name} executed with result: " f"{tool_output.result}"))orchestrator_agent.memory.add_message("system", result_message)diff --git a/atomic-examples/mcp-agent/example-mcp-server/demo_tools.py b/atomic-examples/mcp-agent/example-mcp-server/demo_tools.pyindex 8d58b42..525e00a 100644--- a/atomic-examples/mcp-agent/example-mcp-server/demo_tools.py+++ b/atomic-examples/mcp-agent/example-mcp-server/demo_tools.py@@ -253,7 +253,7 @@ async def test_tools_with_client(client: MCPClient, console: Console, connectionconsole.print(Syntax(json.dumps(result, indent=2), "json"))else:console.print(str(result))- except:+ except Exception:console.print(str(result))diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/resource.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/resource.pyindex 3340af8..2c88560 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/resource.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/resource.py@@ -1,7 +1,7 @@"""Interfaces for resource abstractions."""from abc import ABC, abstractmethod-from typing import Any, Dict, List, Optional, ClassVar, Type+from typing import List, Optional, ClassVarfrom pydantic import BaseModel, Fielddiff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/tool.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/tool.pyindex 914488e..84f949e 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/tool.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/interfaces/tool.py@@ -1,8 +1,8 @@"""Interfaces for tool abstractions."""from abc import ABC, abstractmethod-from typing import Any, Dict, List, Optional, ClassVar, Type, get_type_hints, Union, Generic, TypeVar-from pydantic import BaseModel, Field, create_model+from typing import Any, Dict, List, Optional, ClassVar, Type, TypeVar+from pydantic import BaseModel, Field# Define a type variable for generic model supportT = TypeVar("T", bound=BaseModel)diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.pyindex 4f04ae3..b35ccc8 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py@@ -2,7 +2,6 @@import argparseimport sys-from typing import Literaldef main():diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_sse.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_sse.pyindex 861c483..059ca11 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_sse.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_sse.py@@ -7,7 +7,7 @@ from starlette.requests import Requestfrom starlette.routing import Mount, Routefrom mcp.server import Serverimport uvicorn-from typing import List, Dict, Any+from typing import Listfrom starlette.middleware import Middlewarefrom starlette.middleware.cors import CORSMiddlewarediff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_stdio.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_stdio.pyindex d5807f8..df1b46f 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_stdio.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_stdio.py@@ -1,7 +1,7 @@"""example-mcp-server MCP Server implementation."""from mcp.server.fastmcp import FastMCP-from typing import List, Dict, Any+from typing import Listfrom example_mcp_server.services.tool_service import ToolServicefrom example_mcp_server.services.resource_service import ResourceServicediff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/resource_service.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/resource_service.pyindex 34af1f0..2cc48b2 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/resource_service.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/resource_service.py@@ -1,8 +1,7 @@"""Service layer for managing resources."""-from typing import Dict, List, Any, Set+from typing import Dict, Listimport re-import inspectfrom mcp.server.fastmcp import FastMCPfrom example_mcp_server.interfaces.resource import Resource, ResourceResponse@@ -50,7 +49,6 @@ class ResourceService:match = re.match(regex_pattern, uri)if match:# Found a matching pattern, extract parameters- params = match.groupdict()# Cache the resource with the specific URI for future lookupsself._resources[uri] = resourcereturn resourcediff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/tool_service.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/tool_service.pyindex a183456..a16773b 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/tool_service.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/services/tool_service.py@@ -1,9 +1,8 @@"""Service layer for managing tools."""-from typing import Dict, List, Any, Type, cast, Optional-import json+from typing import Dict, List, Anyfrom mcp.server.fastmcp import FastMCP-from example_mcp_server.interfaces.tool import Tool, ToolResponse, BaseToolInput, ToolContent+from example_mcp_server.interfaces.tool import Tool, ToolResponse, ToolContentfrom pydantic import Fielddiff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/add_numbers.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/add_numbers.pyindex c467c03..15486a0 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/add_numbers.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/add_numbers.py@@ -1,10 +1,10 @@"""Tool for adding two numbers."""-from typing import Optional, Dict, Any, Union+from typing import Dict, Any, Unionfrom pydantic import Field, BaseModel, ConfigDict-from ..interfaces.tool import Tool, BaseToolInput, ToolResponse, ToolContent+from ..interfaces.tool import Tool, BaseToolInput, ToolResponseclass AddNumbersInput(BaseToolInput):diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/divide_numbers.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/divide_numbers.pyindex 35d7e8b..64c1eb9 100644--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/divide_numbers.py+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/tools/divide_numbers.py@@ -4,7 +4,7 @@ from typing import Dict, Any, Unionfrom pydantic import Field, BaseModel, ConfigDict-from ..interfaces.tool import Tool, BaseToolInput, ToolResponse, ToolContent+from ..interfaces.tool import Tool, BaseToolInput, ToolResponseclass DivideNumbersInput(BaseToolInput):