Agent Loop 标志

Agent Loop

社区
AlessandroAnnini

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

发布者AlessandroAnnini
代码仓库agent-loop
语言Python
复刻数
4
星标数
28
可用工具
0
传输类型stdio
分类
链接
  • 将工具接入 AI 工作流

    Agent Loop 提供 MCP 功能,可供兼容的 AI 客户端和智能体使用。

  • 0 个可用工具

    浏览下方可调用的操作;如果服务器提供了名称和描述,也会一并显示。

  • 可直接复制的配置

    使用安装配置片段,在您首选的 MCP 客户端中配置此服务器。

  • 开源社区热度

    关联的代码仓库有 28 个星标和 4 个复刻。

Agent Loop

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


Python uv Anthropic OpenAI MCP Version

Tools

Bash Python Node.js SymPy CLI Plot Filesystem HTTP Curl Git Docker Project Inspector Codebase Search File Search Grep Search List Dir Kubectl AWS CLI Jira Confluence


Requirements

  • Python: >= 3.12
  • Core Python dependencies:
    • anthropic >= 0.51.0
    • halo >= 0.0.31
    • mcp[cli] >= 1.9.2
    • openai >= 1.79.0
    • plotext >= 5.3.2
    • python-dotenv >= 1.1.0
    • requests >= 2.32.3
    • sympy >= 1.14.0
  • Recommended for installation:
    • uv (for fast dependency installation)
  • Optional/for full tool support:
    • Node.js (for some MCP server integrations, e.g., Brave Search, Obsidian)
    • Docker, Git, AWS CLI, kubectl, etc. (for full tool support)
  • Platform:
    • Linux, macOS, or Windows Subsystem for Linux (WSL)
  • API Keys (for full functionality):
    • Anthropic API key (for Claude models)
    • OpenAI API key (for GPT models)
    • (Optional) Jira and Confluence API keys for those integrations

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

bash
# In ~/.config/agent-loop/.env or local .env
MAX_ITERATIONS=20              # Maximum thinking cycles
PROMPT_ON_COMPLETION=true      # Ask before stopping on completion
bash
# 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

json
{
  "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.


Installation

Option 1: Using the installation script (Recommended)

  1. Download the installation package:

    sh
    git clone https://github.com/your-org/agent-loop.git
    cd agent-loop
  2. Run the installation script:

    sh
    ./install.sh

    This script will:

    • Create a virtual environment at ~/.local/share/agent-loop/venv
    • Install all required dependencies
    • Install the agent-loop package
    • Create a command wrapper at ~/.local/bin/agent-loop
  3. Add to your PATH (if needed):

    sh
    echo 'export PATH="$PATH:$HOME/.local/bin"' >> ~/.bashrc
    source ~/.bashrc

Option 2: Manual installation

  1. Clone the repository:

    sh
    git clone https://github.com/your-org/agent-loop.git
    cd agent-loop
  2. Install dependencies:

    Using uv, a much faster Python package manager:

    sh
    uv pip install -r requirements.txt

    If you don't have uv installed, you can install it with:

    sh
    curl -LsSf https://astral.sh/uv/install.sh | sh

Uninstalling

To uninstall Agent Loop, simply run:

sh
./install.sh uninstall

This will remove the command wrapper and the virtual environment.

Windows Subsystem for Linux (WSL) Installation

Agent Loop works great on Windows through WSL. Here's how to set it up:

  1. Install WSL if you don't have it already:

    • Open PowerShell as Administrator and run:

      powershell
      wsl --install
    • Restart your computer after installation completes

    • For detailed instructions, see Microsoft's WSL installation guide

  2. Install Agent Loop in WSL:

    • Open your WSL terminal

    • Follow the same installation instructions as above:

      sh
      git clone https://github.com/your-org/agent-loop.git
      cd agent-loop
      ./install.sh
  3. Configuration in WSL:

    • Create the config directory in your WSL home:

      sh
      mkdir -p ~/.config/agent-loop
    • Add your API keys to .env file:

      sh
      nano ~/.config/agent-loop/.env
    • Optional: Add a custom system prompt:

      sh
      nano ~/.config/agent-loop/SYSTEM_PROMPT.txt
  4. WSL-specific considerations:

    • The agent-loop can access both Linux and Windows files
    • Windows files are mounted at /mnt/c/, /mnt/d/, etc.
    • To access Windows directories, use paths like /mnt/c/Users/YourName/Documents
    • For best performance, keep your projects within the WSL filesystem

Configuration

API Keys and Environment Variables

Create a .env file in the ~/.config/agent-loop directory with your API keys and other configuration:

sh
# Create the config directory if it doesn't exist
mkdir -p ~/.config/agent-loop

# Create your .env file
nano ~/.config/agent-loop/.env

You can also create a local .env file in your project directory, which will take priority over the global configuration.

You can use the .env.example file from the source repository as a template. At minimum, include one of these API keys:

text
# AI Configuration
AI_PROVIDER=anthropic  # Choose: anthropic (default) or openai
AI_TEMPERATURE=0.7     # Model temperature: 0.0-2.0 (default: 0.7)

# Anthropic
ANTHROPIC_API_KEY=your_anthropic_api_key
ANTHROPIC_MODEL=claude-sonnet-4-20250514  # Optional, defaults to claude-3-7-sonnet-latest

# OpenAI
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4o  # Optional, defaults to gpt-4o

# Jira (Optional)
JIRA_BASE_URL=your_jira_instance_url
JIRA_EMAIL=your_jira_email
JIRA_API_TOKEN=your_jira_api_token

# Confluence (Optional)
CONFLUENCE_BASE_URL=your_confluence_instance_url
CONFLUENCE_EMAIL=your_confluence_email
CONFLUENCE_API_TOKEN=your_confluence_api_token

Configuration Priority:

  • Local .env file in your current directory (highest priority)
  • Global .env file in ~/.config/agent-loop/ (fallback)

AI Provider Selection:

  • Set AI_PROVIDER=anthropic to use Claude models (default)
  • Set AI_PROVIDER=openai to use GPT models
  • If the preferred provider's API key is missing, the application will automatically fall back to the available provider

Temperature Control:

  • AI_TEMPERATURE controls response creativity and randomness (0.0 = deterministic, 1.0 = creative)
  • Valid range: 0.0 to 2.0
  • Default: 0.7 (balanced)

Custom System Prompt

You can customize the system prompt by creating a SYSTEM_PROMPT.txt file in the same directory:

sh
nano ~/.config/agent-loop/SYSTEM_PROMPT.txt

This allows you to give specific instructions or personality to the assistant. If this file doesn't exist, the default system prompt will be used.

MCP Server Configuration

To enable MCP integration, create a file at ~/.config/agent-loop/mcp.json as shown above. Each server entry should specify the command, arguments, and any required environment variables. All services from these servers will be available as tools in your agent session.

Usage

Basic

sh
agent-loop

Model Selection

sh
agent-loop --model gpt-4o

or

sh
agent-loop --model claude-3-7-sonnet-latest

Safe Mode (Human Confirmation)

sh
agent-loop --safe
  • You will be shown each command and asked to confirm before execution.

Debug Mode

sh
agent-loop --debug
  • Prints tool input/output for transparency.

Combined

sh
agent-loop --safe --debug

Example Session

bash
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)

bash
💬 Agent:
# Docker Containers

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

Example (Plain Text Output)

bash
💬 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:

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

License

This project is licensed under the GNU Affero General Public License v3.0, with additional terms prohibiting commercial use and requiring attribution.

See LICENSE for full details.

安装

TypingMind
前提条件:

Node.js 18+

{
  "mcpServers": {
    "alessandroannini-agent-loop": {
      "command": "",
      "args": []
    }
  }
}

将 Agent Loop MCP 与多个 AI 模型配合使用

TypingMind 在工作区级别连接 MCP 工具,因此连接 Agent Loop 后,您就可以在 TypingMind 中搭配不同的 AI 模型使用,无需为每个模型单独设置。 此 MCP 通过您设备上的 TypingMind MCP 连接器在本地运行。

本地连接器设置指南

如果 MCP 服务器需要访问您电脑上的本地文件、应用或私有资源,请选择此方式。

1

打开 MCP 设置

在 TypingMind 中,依次前往“设置”、“高级设置”和“模型上下文协议”,然后选择“设置连接器”。

  1. 在您的浏览器中打开 TypingMind。
  2. 点击“设置”图标。
  3. 进入“高级设置”。
  4. 打开“模型上下文协议”部分。
  5. 点击“设置连接器”,然后选择“此设备”。
TypingMind MCP 连接器设置界面,已选择“此设备”
2

运行连接器命令

选择“此设备”,从 TypingMind 复制命令并在终端中运行。使用 MCP 时,请保持该进程运行。

  1. 复制 TypingMind 显示的设置命令。
  2. 在 macOS 上打开“终端”,或在 Windows 上打开 Windows Terminal。
  3. 粘贴并运行命令。
  4. 如果终端询问您是否继续,请确认安装软件包。
  5. 使用 MCP 工具时,请勿关闭终端窗口或停止其中的连接器进程。
3

将 Agent Loop 添加为服务器

当连接器状态为“就绪”时,点击“编辑服务器”,然后粘贴 MCP 服务器配置。

  1. 等待连接器状态显示为“就绪”。
  2. 点击“编辑服务器”。
  3. 粘贴 Agent Loop MCP 服务器配置。
  4. 保存服务器列表。
  5. 如需确认连接器是否仍处于就绪状态,请刷新。
TypingMind MCP 设置界面,显示正在运行的服务器和“编辑服务器”按钮
{
  "mcpServers": {
    "alessandroannini-agent-loop": {
      "command": "npx",
      "args": [
        "-y",
        "agent-loop"
      ]
    }
  }
}
4

在不同模型中使用同一连接

保存服务器列表,打开“插件”,启用 Agent Loop MCP 工具,然后在 TypingMind 中选择任意受支持的 AI 模型,即可在聊天中使用这些工具,或将其分配给智能体。

  1. 在 TypingMind 中打开“插件”页面。
  2. 启用 Agent Loop MCP 工具。
  3. 开始聊天并选择您想使用的 AI 模型。
  4. 在聊天中使用 MCP 工具,或将其分配给 AI 智能体。
  5. 根据需要随时切换到其他 AI 模型,无需重新连接 MCP。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 Agent Loop 帮我完成这项任务吗?
Agent Loop
当然,我看过了。
以下是我使用 Agent Loop 得到的结果。

常见问题

Agent Loop MCP 服务器有什么用途?

Agent Loop 是一个 MCP 服务器,可让兼容的 AI 客户端连接外部工具并获取上下文。在 TypingMind 中,只需添加一次此 MCP 服务器,即可在您的 AI 工作区中使用其工具。

可以在 TypingMind 中让多个 AI 模型使用 Agent Loop MCP 吗?

可以。TypingMind 在工作区层面连接 MCP 工具,因此您无需为每个模型单独配置 MCP 服务器,就能在 Claude、ChatGPT、Gemini 或您在 TypingMind 中配置的其他 AI 模型中使用 Agent Loop。

为什么在 TypingMind 中使用 Agent Loop MCP?

TypingMind 将多个 AI 模型、提示词、插件、AI 智能体、API 密钥和 MCP 工具整合到同一个工作区中,是最出色的大语言模型聊天前端之一。连接 Agent Loop 后,您可以在偏好的不同模型中使用其 MCP 工具,同时在 TypingMind 中井然有序地管理聊天工作流程。

如何将 Agent Loop MCP 连接到 TypingMind?

Agent Loop 通过 TypingMind 本地 MCP 连接器运行。当 MCP 服务器需要访问您计算机上的本地文件、桌面应用、命令行工具或私有资源时,这种方式最合适。

Agent Loop MCP 在 TypingMind 中提供哪些工具?

Agent Loop 提供 MCP 功能,您可以在 TypingMind 的插件页面启用这些功能,然后在聊天中使用,或将其分配给 AI 智能体。

使用 Agent Loop MCP 需要向 TypingMind 提供我的 API 密钥吗?

不需要。TypingMind 采用本地优先的设计,让您自行选择模型提供商,并自行管理 API 密钥、提示词和 MCP 配置。如果 Agent Loop 需要身份验证,请在创建连接时,为该 MCP 服务器添加所需的请求头、OAuth 设置或本地配置。

相关 MCP 服务器

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇