Skip to content

Building AI agents, atomically

black and flake8 formatting

jon foxbab32c0bf984
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 223db56..f722b8a 100644
--- a/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py
+++ b/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py
@@ -23,7 +23,13 @@ class MCPToolDefinition(NamedTuple):
class ToolDefinitionService:
"""Service for fetching tool definitions from MCP endpoints."""
- def __init__(self, endpoint: Optional[str] = None, use_stdio: bool = False, use_http_stream: bool = False, working_directory: Optional[str] = None):
+ def __init__(
+ self,
+ endpoint: Optional[str] = None,
+ use_stdio: bool = False,
+ use_http_stream: bool = False,
+ working_directory: Optional[str] = None,
+ ):
"""
Initialize the service.
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_http.py b/atomic-examples/mcp-agent/example-client/example_client/main_http.py
index 1256e55..a58a61e 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_http.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_http.py
@@ -2,24 +2,26 @@
HTTP Stream transport client for MCP Agent example.
Communicates with the server_http.py `/mcp` endpoint using HTTP GET/POST/DELETE for JSON-RPC streams.
"""
+
import sys
from atomic_agents.lib.factories.mcp_tool_factory import fetch_mcp_tools
from rich.console import Console
from rich.table import Table
-from rich.markdown import Markdown
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.chat_history import ChatHistory
-import openai, os, instructor
+import openai
+import os
+import instructor
from typing import Union, Type, Dict
from dataclasses import dataclass
-import re
@dataclass
class MCPConfig:
"""Configuration for the MCP Agent system using HTTP Stream transport."""
+
mcp_server_url: str = "http://localhost:6969"
openai_model: str = "gpt-4o"
openai_api_key: str = os.getenv("OPENAI_API_KEY")
@@ -47,43 +49,44 @@ def main():
table.add_column("Input Schema", style="yellow")
table.add_column("Description", style="magenta")
for ToolClass in tools:
- schema_name = getattr(ToolClass.input_schema, '__name__', 'N/A')
+ schema_name = getattr(ToolClass.input_schema, "__name__", "N/A")
table.add_row(ToolClass.mcp_tool_name, schema_name, ToolClass.__doc__ or "")
console.print(table)
# Build orchestrator
class MCPOrchestratorInputSchema(BaseIOSchema):
"""Input schema for the MCP orchestrator that processes user queries."""
+
query: str = Field(...)
class FinalResponseSchema(BaseIOSchema):
"""Schema for the final response to the user."""
+
response_text: str = Field(...)
# Map schemas and define ActionUnion
tool_schema_map: Dict[Type[BaseIOSchema], Type] = {
- ToolClass.input_schema: ToolClass for ToolClass in tools if hasattr(ToolClass, 'input_schema')
+ ToolClass.input_schema: ToolClass for ToolClass in tools if hasattr(ToolClass, "input_schema")
}
available_schemas = tuple(tool_schema_map.keys()) + (FinalResponseSchema,)
ActionUnion = Union[available_schemas]
class OrchestratorOutputSchema(BaseIOSchema):
"""Output schema for the MCP orchestrator containing reasoning and selected action."""
+
reasoning: str
action: ActionUnion
history = ChatHistory()
- orchestrator = BaseAgent[
- MCPOrchestratorInputSchema, OrchestratorOutputSchema
- ](
+ orchestrator = BaseAgent[MCPOrchestratorInputSchema, OrchestratorOutputSchema](
BaseAgentConfig(
client=client,
model=config.openai_model,
history=history,
system_prompt_generator=SystemPromptGenerator(
- background=['You are an MCP orchestrator via HTTP.'],
- steps=['Decide and invoke tools over HTTP stream.'],
- output_instructions=['Provide reasoning and a single action schema.'],
+ background=["You are an MCP orchestrator via HTTP."],
+ steps=["Decide and invoke tools over HTTP stream."],
+ output_instructions=["Provide reasoning and a single action schema."],
),
)
)
@@ -91,15 +94,15 @@ def main():
console.print("[bold green]HTTP Stream client ready. Type 'exit' to quit.[/bold green]")
while True:
query = console.input("[bold yellow]You:[/bold yellow] ").strip()
- if query.lower() in {'exit', 'quit'}:
+ if query.lower() in {"exit", "quit"}:
break
if not query:
continue
-
+
try:
# Initial run with user query
orchestrator_output = orchestrator.run(MCPOrchestratorInputSchema(query=query))
-
+
# Handle the output similar to SSE version
if hasattr(orchestrator_output, "chat_message") and not hasattr(orchestrator_output, "action"):
# Convert BaseAgentOutputSchema to FinalResponseSchema
@@ -107,53 +110,59 @@ def main():
reasoning = "Response generated directly from chat model"
elif hasattr(orchestrator_output, "action"):
action_instance = orchestrator_output.action
- reasoning = orchestrator_output.reasoning if hasattr(orchestrator_output, "reasoning") else "No reasoning provided"
+ reasoning = (
+ orchestrator_output.reasoning if hasattr(orchestrator_output, "reasoning") else "No reasoning provided"
+ )
else:
console.print("[yellow]Warning: Unexpected response format. Unable to process.[/yellow]")
continue
-
+
console.print(f"[cyan]Orchestrator reasoning:[/cyan] {reasoning}")
-
+
# Keep executing until we get a final response
while not isinstance(action_instance, FinalResponseSchema):
# Find the matching tool class
tool_class = tool_schema_map.get(type(action_instance))
if not tool_class:
console.print(f"[red]Error: No tool found for schema {type(action_instance)}[/red]")
- action_instance = FinalResponseSchema(response_text="I encountered an internal error. Could not find the appropriate tool.")
+ action_instance = FinalResponseSchema(
+ response_text="I encountered an internal error. Could not find the appropriate tool."
+ )
break
-
+
# Execute the tool
console.print(f"[blue]Executing {tool_class.mcp_tool_name}...[/blue]")
tool_instance = tool_class()
try:
result = tool_instance.run(action_instance)
console.print(f"[green]Tool result:[/green] {result}")
-
+
# Ask orchestrator what to do next with the result
next_query = f"Based on the tool result: {result}, please provide the final response to the user's original query: {query}"
next_output = orchestrator.run(MCPOrchestratorInputSchema(query=next_query))
-
+
if hasattr(next_output, "action"):
action_instance = next_output.action
else:
# If no action, treat as final response
action_instance = FinalResponseSchema(response_text=next_output.chat_message)
-
+
except Exception as e:
console.print(f"[red]Error executing tool: {e}[/red]")
- action_instance = FinalResponseSchema(response_text=f"I encountered an error while executing the tool: {str(e)}")
+ action_instance = FinalResponseSchema(
+ response_text=f"I encountered an error while executing the tool: {str(e)}"
+ )
break
-
+
# Display final response
if isinstance(action_instance, FinalResponseSchema):
console.print(f"[bold green]Assistant:[/bold green] {action_instance.response_text}")
else:
console.print("[red]Error: Expected final response but got something else[/red]")
-
+
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py
index 001307e..edf8744 100644
--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py
+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py
@@ -11,7 +11,6 @@ from mcp.server import Server
from mcp.server.sse import SseServerTransport
import uvicorn
from typing import List
-import json
from example_mcp_server.services.tool_service import ToolService
from example_mcp_server.services.resource_service import ResourceService
@@ -37,10 +36,10 @@ def get_available_resources() -> List[Resource]:
def create_http_app(mcp_server: Server) -> Starlette:
"""Create a Starlette app supporting HTTP Stream Transport."""
-
+
# Create SSE transport for handling the connection
sse = SseServerTransport("/messages/")
-
+
async def handle_mcp(request: Request):
"""Handle MCP requests over HTTP Stream - accepts GET for connection."""
try:
@@ -55,16 +54,9 @@ def create_http_app(mcp_server: Server) -> Starlette:
write_stream,
mcp_server.create_initialization_options(),
)
-
+
except Exception as e:
- error_response = {
- "jsonrpc": "2.0",
- "id": None,
- "error": {
- "code": -32603,
- "message": f"Internal error: {str(e)}"
- }
- }
+ error_response = {"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": f"Internal error: {str(e)}"}}
return JSONResponse(error_response, status_code=500)
middleware = [
@@ -95,7 +87,7 @@ resource_service = ResourceService()
tool_service.register_tools(get_available_tools())
tool_service.register_mcp_handlers(mcp)
-# Register all resources and their MCP handlers - same as SSE
+# Register all resources and their MCP handlers - same as SSE
resource_service.register_resources(get_available_resources())
resource_service.register_mcp_handlers(mcp)
@@ -114,19 +106,13 @@ def main():
import argparse
parser = argparse.ArgumentParser(description="Run MCP HTTP Stream server")
- parser.add_argument(
- "--host", default="0.0.0.0", help="Host to bind to"
- )
- parser.add_argument(
- "--port", type=int, default=6969, help="Port to listen on"
- )
- parser.add_argument(
- "--reload", action="store_true", help="Enable auto-reload for development"
- )
+ parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
+ parser.add_argument("--port", type=int, default=6969, help="Port to listen on")
+ parser.add_argument("--reload", action="store_true", help="Enable auto-reload for development")
args = parser.parse_args()
-
+
print(f"MCP HTTP Stream Server starting on {args.host}:{args.port}")
-
+
uvicorn.run(
"example_mcp_server.server_http:app",
host=args.host,