Labsco
AlessandroAnnini logo

Agent Loop

β˜… 28

from AlessandroAnnini

An AI Agent with optional Human-in-the-Loop Safety and Model Context Protocol (MCP) integration.

πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedAccount requiredAdvanced setup

Agent Loop

An AI Agent with optional Human-in-the-Loop Safety, Model Context Protocol (MCP) integration, and beautiful, themeable CLI output



Tools


Overview

Agent Loop is a command-line AI assistant. It leverages Anthropic's Claude or OpenAI's GPT models and a suite of powerful tools to automate, inspect, and manage your development environmentβ€”while keeping you in control with optional human confirmation for every action.

  • Human-in-the-Loop: Add --safe to require confirmation before any tool runs.
  • Functional Programming: Clean, composable, and testable code.
  • DevOps Ready: Integrates with Bash, Python, Docker, Git, Kubernetes, AWS, and more.
  • Multi-Provider: Supports both Anthropic Claude and OpenAI GPT models.
  • MCP Integration: Dynamically loads and uses tools/services from any MCP-compatible server (see below).

Code Structure

  • main.py β€” Main event loop and orchestration
  • cli_input.py β€” Terminal input handling (CTRL+C, CTRL+Q, backspace, etc.)
  • signals.py β€” Signal handling (SIGINT for interruption)
  • constants.py β€” User-facing strings and help messages
  • exceptions.py β€” Custom exceptions for clean exit and error handling

All components are designed for modularity, minimalism, and functional programming style.


Loop Control and Pragmatic Stopping

Agent Loop includes intelligent stopping mechanisms to prevent runaway iterations and excessive token usage:

Iteration Limits

  • Maximum iterations: Configurable hard limit (default: 20) prevents infinite loops
  • Progress display: Shows current iteration count in real-time
  • Configuration: Set via MAX_ITERATIONS env var or --max-iterations CLI flag

Completion Detection

The agent automatically detects when a task is complete by recognizing:

  • Explicit completion phrases ("task complete", "finished", "done")
  • Brief responses with no further tool calls
  • Agent providing summaries without requesting more actions

When completion is detected, the system prompts you to confirm before stopping, allowing you to:

  • Stop: End the session if the task is truly complete
  • Continue: Give the agent more iterations if additional work is needed

Repetition Detection

Prevents infinite loops by detecting argument-aware patterns:

  • Same tool with identical arguments called 5+ times consecutively
  • Alternating patterns with identical calls (e.g., same bash command β†’ same file write β†’ repeat...)
  • Repeated sequences of tool calls with identical arguments

Important: The detection is argument-aware, meaning:

  • βœ… Calling bash with different commands (legitimate investigation) is allowed
  • ❌ Calling bash with the same command 5+ times is blocked

This prevents false positives while still catching true stuck behaviors.

When repetition is detected, the agent stops immediately with a clear explanation.

Configuration

# In ~/.config/agent-loop/.env or local .env
MAX_ITERATIONS=20              # Maximum thinking cycles
PROMPT_ON_COMPLETION=true      # Ask before stopping on completion
# Via CLI
agent-loop --max-iterations 50                # Override iteration limit
agent-loop --no-prompt-on-completion          # Auto-stop without prompting

System Prompt Guidance

The agent is instructed to:

  • Complete requested tasks precisely, then stop
  • Avoid "while I'm here" improvements
  • Not add unrequested features, documentation, or tests
  • Provide summaries when work is complete instead of continuing

This ensures the agent stays focused on your actual request and doesn't waste tokens on unnecessary elaboration.


Graceful Exit and Signal Handling

  • CTRL+C: Interrupts the current operation and returns to the prompt (does not exit).
  • CTRL+D or typing exit/quit at the prompt: Exits the application cleanly, with no traceback or error.
  • Only SIGINT (CTRL+C) is handled as a signal for async safety; quit is handled at the prompt for robust, async-safe shutdown.

Async-Aware LLM Support

Agent Loop automatically supports both synchronous and asynchronous LLM functions, ensuring optimal performance and compatibility. The main event loop will call your LLM function in the most efficient way, whether it is sync or async.


Features

  • Conversational AI agent powered by Anthropic Claude or OpenAI GPT
  • Configurable AI provider and temperature via environment variables
  • Pragmatic loop control with iteration limits and completion detection
  • Tool execution with optional human confirmation (--safe mode)
  • Debug mode for transparency (--debug)
  • Custom tools support with automatic discovery and display
  • Visual tool differentiation with distinct icons for built-in, MCP, and custom tools
  • Modular, extensible tool system
  • Functional programming style throughout
  • Enhanced error handling with detailed diagnostic information
  • Flexible configuration with local .env file priority
  • MCP (Model Context Protocol) integration for external tool/service discovery and use

MCP (Model Context Protocol) Integration

New in v2.0!

Agent Loop can now connect to any number of MCP-compatible servers, dynamically discovering and using their services as tools. This means you can:

  • Add new capabilities (search, knowledge, automation, etc.) by simply running or configuring an MCP server.
  • Use tools from remote or local MCP servers as if they were built-in.
  • Aggregate services from multiple sources (e.g., Brave Search, Obsidian, custom servers) in one agent.

ℹ️ The MCP server configuration format is identical to that used by Cursor AI IDE. See the Cursor MCP documentation for more details and advanced options.

How it works

  • On startup, Agent Loop reads your MCP server configuration from ~/.config/agent-loop/mcp.json.
  • For each server, it starts a session and lists available services.
  • Each service is registered as a tool (named <server>-<service>) and can be called by the agent or user.
  • All MCP tools are available alongside built-in tools.

Example MCP config

{
  "mcpServers": {
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": { "BRAVE_API_KEY": "..." }
    },
    "mcp-obsidian": {
      "command": "npx",
      "args": ["-y", "mcp-obsidian", "/path/to/obsidian-vault/"]
    }
  }
}
  • Place this file at ~/.config/agent-loop/mcp.json.
  • Each server can be a local or remote MCP-compatible service.
  • All services/tools from these servers will be available in your agent session.
  • For more details, see the Cursor MCP documentation.

Available Tools

Agent Loop comes with built-in tools and supports custom tools. The application automatically distinguishes between different tool types with visual indicators:

  • πŸ› οΈ Built-in Tools: Core application tools
  • πŸ”Œ MCP Tools: External tools from Model Context Protocol servers
  • πŸ”§ Custom Tools: User-defined tools loaded from ~/.config/agent-loop/tools/

On startup, Agent Loop will display any custom tools that have been loaded:

πŸ”§ [Custom Tools] Loaded 2 custom tool(s) from ~/.config/agent-loop/tools:
  β€’ hello (hello.py) - Returns a friendly greeting
  β€’ my_tool (my_tool.py) - Custom automation tool
ToolDescription
bashExecute bash commands
pythonEvaluate Python code in a sandboxed subprocess
nodeEvaluate Node.js code in a sandboxed subprocess
sympyPerform symbolic mathematics operations using SymPy
cli_plotRender advanced terminal charts and plots using plotext
filesystemRead, create, update, append, delete files with UTF-8 encoding
list_dirList the contents of a directory for quick file discovery
codebase_searchSemantic code search for relevant code snippets in the project
file_searchFast fuzzy file search by filename or path fragment
grep_searchSearch for exact strings or regex patterns in files
httpMake HTTP requests using HTTPie with easy JSON handling
curlMake HTTP requests using curl
gitRun Git commands in the current repository
dockerRun Docker CLI commands
project_inspectorInspect the current project directory and preview source files
kubectlRun kubectl commands to interact with a Kubernetes cluster
aws_cliRun AWS CLI v2 read-only commands to interact with AWS services
jiraQuery JIRA via REST API using safe, read-only endpoints
confluenceQuery Atlassian Confluence Cloud via REST API (read-only)
MCPAll services from configured MCP servers (see above)
CustomUser-defined tools from ~/.config/agent-loop/tools/

See Creating Tools Guide for instructions on how to create your own tools.


Example Session

dev@agent-loop:~$ agent-loop --safe
> List all Docker containers
Agent: I will use the docker tool to list all containers.
[CONFIRMATION REQUIRED]
Tool: docker
Description: Run Docker CLI commands
Input: {'args': 'ps -a'}
Do you want to execute this command? [y/N]: y
STDOUT:
CONTAINER ID   IMAGE   ...

✨ Beautiful, Themeable CLI Output

Agent Loop uses Rich to render all agent replies and notifications in the terminal. By default, all agent answers are formatted in Markdown and rendered with color, style, and structure for maximum readability.

  • Default: Answers are rendered as Markdown (headings, lists, code blocks, etc.)
  • Theming: Colors and styles are fully customizable via a JSON theme file
  • Plain Text Mode: Use --simple-text or -s to disable Rich/Markdown and get pure ASCII output (great for piping or minimal terminals)

Example (Markdown Output)

πŸ’¬ Agent:
# Docker Containers

| CONTAINER ID | IMAGE | STATUS |
|--------------|-------|--------|
| 123abc       | nginx | Up     |
| ...          | ...   | ...    |

Example (Plain Text Output)

πŸ’¬ Agent:
Docker Containers
----------------
CONTAINER ID   IMAGE   STATUS
123abc         nginx   Up
...            ...     ...

🎨 Customizing the Theme

You can fully customize the CLI appearance by editing the theme file:

  • Location: ~/.config/agent-loop/theme.json
  • Format: JSON mapping style names to Rich style strings
  • Fallback: If the file is missing or invalid, a beautiful default theme is used

Example theme.json:

{
  "agent.reply": "bold cyan",
  "agent.tool": "bold magenta",
  "agent.confirm": "bold yellow",
  "agent.error": "bold red",
  "agent.info": "dim white"
}

Change colors, add emphasis, or create your own style! See the Rich style guide for options.


πŸš€ CLI Flags

FlagDescription
--simple-text, -sOutput plain ASCII text (no Rich, no Markdown)
--safeRequire confirmation before executing any tool
--debugShow tool input/output for transparency
--modelSelect the LLM model (e.g., gpt-4o, claude-3-7-sonnet-latest)
--max-iterations NSet maximum agent iteration cycles (default: 20)
--no-prompt-on-completionDisable prompting when completion detected (auto-stop instead)

πŸ› οΈ Creating Your Own Tools

Agent Loop is fully extensible! You can add your own tools in minutesβ€”no need to modify the core code.

  • Drop-in Python modules (pure functions, functional programming style)
  • Auto-discovered: Just place your .py file in agent_loop/tools/ (built-in) or ~/.config/agent-loop/tools/ (user tools)
  • No extra dependencies for user toolsβ€”see the policy in the guide

πŸ‘‰ See the full guide: CREATING_TOOLS.md