Skip to content

Building AI agents, atomically

linting

KennyVaneetvelde9d215eb46b05
diff --git a/.flake8 b/.flake8
index 67d5c32..afb12a1 100644
--- a/.flake8
+++ b/.flake8
@@ -4,6 +4,7 @@ max-complexity = 10
count = true
statistics = true
ignore = E203
+exclude = .venv,venv,__pycache__,build,dist
per-file-ignores =
*/__main__.py:C901
diff --git a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
index 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 asyncio
import 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, cast
from contextlib import AsyncExitStack
import shlex
@@ -113,7 +111,7 @@ class MCPToolFactory:
# Create new connection
service = 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 service
raise
@@ -267,7 +265,6 @@ class MCPToolFactory:
return None
tool_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 schemas
ToolParameterUnion = 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.py
index 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 logging
from typing import Any, Dict, List, Optional, Type, Tuple, Literal, cast
-from pydantic import BaseModel, Field, create_model
+from pydantic import Field, create_model
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
diff --git a/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py b/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py
index 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 asyncio
import logging
import shlex
from 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.py
index 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 asyncio
from pydantic import BaseModel
from 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 MCPToolDefinition
from 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 client
class DummySessionPersistent:
async def call_tool(self, name, arguments):
return {"content": "persist-ok"}
- loop = asyncio.new_event_loop()
client = DummySessionPersistent()
# Stub definition fetch for persistent
definitions = [
@@ -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 MCPToolDefinition
defs = [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() == defs
factory_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 ToolDefinitionService
async 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.py
index 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, Optional
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
from atomic_agents.lib.factories.schema_transformer import SchemaTransformer
diff --git a/atomic-agents/tests/lib/factories/test_tool_definition_service.py b/atomic-agents/tests/lib/factories/test_tool_definition_service.py
index 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 asyncio
import pytest
-import shlex
from unittest.mock import AsyncMock, MagicMock, patch
-import logging
from 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.py
index 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 Field
from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
from atomic_agents.lib.components.agent_memory import AgentMemory
-from typing import Union, Type, Dict, Optional
+from typing import Union, Type, Dict
from 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_name
console.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 memory
result_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.py
index 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 point
def main():
- global stdio_session, stdio_loop, stdio_exit_stack # Ensure access if cleanup is needed
try:
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_name
console.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 memory
result_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.py
index 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, connection
console.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.py
index 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, ClassVar
from pydantic import BaseModel, Field
diff --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.py
index 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 support
T = 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.py
index 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 argparse
import sys
-from typing import Literal
def 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.py
index 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 Request
from starlette.routing import Mount, Route
from mcp.server import Server
import uvicorn
-from typing import List, Dict, Any
+from typing import List
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
diff --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.py
index 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 List
from example_mcp_server.services.tool_service import ToolService
from example_mcp_server.services.resource_service import ResourceService
diff --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.py
index 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, List
import re
-import inspect
from mcp.server.fastmcp import FastMCP
from 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 lookups
self._resources[uri] = resource
return resource
diff --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.py
index 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, Any
from 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, ToolContent
from pydantic import Field
diff --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.py
index 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, Union
from pydantic import Field, BaseModel, ConfigDict
-from ..interfaces.tool import Tool, BaseToolInput, ToolResponse, ToolContent
+from ..interfaces.tool import Tool, BaseToolInput, ToolResponse
class 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.py
index 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, Union
from pydantic import Field, BaseModel, ConfigDict
-from ..interfaces.tool import Tool, BaseToolInput, ToolResponse, ToolContent
+from ..interfaces.tool import Tool, BaseToolInput, ToolResponse
class DivideNumbersInput(BaseToolInput):