agent-loop

agent-loop is a skill for Claude Code, Codex from LuuOW/meridian-mcp. It costs 43 tokens per session (2,561 once invoked), scanned A, original, MIT.

A set of patterns for building autonomous Claude agent loops that run tasks, call tools, and keep a record of events. It includes scheduled runs, a safe dry-run mode, error handling, and monitoring hooks.

In plain words
What is it for?
Use it to build agents that run on a schedule, test workflows without making Claude API calls, catalogue callable tools, handle failed tasks, and connect runs to monitoring systems.
Why use it?
It helps prevent scheduled agents from making real API calls or failing without notice while running unattended. It also separates decisions, available tools, actions, and run history.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/luuow/meridian-mcp/agent-loop
Any agent
npx skills add LuuOW/meridian-mcp --skill agent-loop
Clone the repo
git clone --depth 1 https://github.com/LuuOW/meridian-mcp

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for agent-loop

README.md
[![agentmods](https://agentmods.dev/badge/skills/luuow/meridian-mcp/agent-loop.svg)](https://agentmods.dev/skills/luuow/meridian-mcp/agent-loop)
Your own site
<a href="https://agentmods.dev/skills/luuow/meridian-mcp/agent-loop"><img src="https://agentmods.dev/badge/skills/luuow/meridian-mcp/agent-loop.svg" alt="Measured on agentmods" height="20"></a>
Per session 43 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,561 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00043 $0.02561
Opus 5 $0.00022 $0.01281
Sonnet 5 $0.00009 $0.00512
Haiku 4.5 $0.00004 $0.00256

Measured 4d ago against content hash 66393d1fe2d9, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

agent-loop scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/agent-loop/SKILL.md · 292 lines

How it starts

The opening of the file, as written. The whole thing — 292 lines — stays where its author put it; the contents beside it link to each section on GitHub.

agent-loop

Production patterns for building autonomous agent loops with the Anthropic API. Covers the Session/Harness/Registry/Tool abstraction, safe development mode via DRY_RUN, APScheduler cron integration, and observability hooks. Designed for systems that run unsupervised on a schedule and must never silently bill or silently fail.

Core Abstraction

Four objects, one responsibility each:

Session   — append-only event log (what happened)
Harness   — drives the Claude API loop (who decides)
Registry  — tool catalogue (what can be called)
Tool      — unit of action (what gets done)
# RunContext carries credentials and settings — never sent to Claude
@dataclass
class RunContext:
    anthropic_api_key: str
    settings: Settings
    system_code: str        # e.g. "LI-01", "OB-03"
    client_id: str
    run_id: str = field(default_factory=lambda: str(uuid4()))

DRY_RUN Guard — First Line of Safety

Always gate API calls. A scheduler firing 39 jobs at noon will call the Anthropic API 39 times if this is missing.

# settings.py
class Settings(BaseSettings):
    # Default TRUE — scheduler fires, tools run, but NO Claude API calls.
    # Flip to false only when ready to go live.
    dry_run: bool = True
# harness.py — guard before the loop
async def run(self, system_prompt: str, initial_message: str, max_turns: int = 10) -> str:
    if self.ctx.settings.dry_run:
        logger.info("DRY_RUN=true — skipping Claude API call for %s", self.ctx.system_code)
        return "[dry_run] No API call made — set DRY_RUN=false to enable"

    # ... API loop follows
# .env — explicit is better than implicit
DRY_RUN=true    # change to false only when going live

Harness — The Agent Loop

class Harness:
    def __init__(self, ctx, session, registry, model=None, max_tokens=1024):
        self.ctx      = ctx
        self.session  = session
        self.registry = registry
        self.model    = model or ctx.settings.anthropic_model
        self._client  = anthropic.AsyncAnthropic(api_key=ctx.anthropic_api_key)

    async def run(self, system_prompt, initial_message, max_turns=10) -> str:
        messages = [{"role": "user", "content": initial_message}]
        tools    = self.registry.to_anthropic()

        if self.ctx.settings.dry_run:
            return "[dry_run] No API call made"

        for turn in range(max_turns):
            self.session.record_claude_request(
                messages=messages,
                system_prompt_hash=hashlib.sha256(system_prompt.encode()).hexdigest()[:16],
                model=self.model,
                max_tokens=self.max_tokens,
            )

            try:
                response = await self._client.messages.create(
                    model=self.model, max_tokens=self.max_tokens,
                    system=system_prompt, tools=tools, messages=messages,
                )
            except anthropic.APIError as exc:
                self.session.error("anthropic_api_error", str(exc))
                raise DeadLetterError(f"Anthropic API error: {exc}") from exc

            self.session.record_claude_response(
                stop_reason=response.stop_reason,
                input_tokens=response.usage.input_tokens,
                output_tokens=response.usage.output_tokens,
                tool_calls=[b.name for b in response.content if b.type == "tool_use"],
            )

            messages.append({"role": "assistant", "content": response.content})

            if response.stop_reason == "end_turn":
                return "\n".join(b.text for b in response.content if hasattr(b, "text"))

            if response.stop_reason != "tool_use":
                raise DeadLetterError(f"Unexpected stop_reason: {response.stop_reason}")

            # Execute all tool calls
            tool_results = []
            for block in response.content:
                if block.type != "tool_use":
                    continue
                tool   = self.registry.get(block.name)
                result = await self._execute_tool(tool, block)
                tool_results.append(result.to_anthropic())

            messages.append({"role": "user", "content": tool_results})

        raise DeadLetterError(f"Reached max_turns={max_turns} without end_turn")

Read the full file on GitHub · 292 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 292 lines · 43 tokens per session scan A 66393d1fe2d9

Subscribe to this mod's changes

agent-loop is a skill published in the GitHub repository LuuOW/meridian-mcp (0 stars, last pushed 2d ago), licensed MIT. It adds 43 tokens to every session and 2,561 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

lastlight-evals-loop

Drive a Last Light EVAL toward a target score with a disciplined, anti-gaming improvement loop — run → mine failures → propose candidate fix(es) → re-measure → keep the best or revert → repeat. Use when the user wants to "improve / raise the pr-review F1", "make the reviewer better against the eval", "close the loop…

nearform/lastlight · 200 tokens

open-code-review

Performs AI-powered code review on Git changes using the ocr CLI from alibaba/open-code-review. Use when the user asks to review code, review a pull request, review staged/unstaged changes, review a commit, or compare branches for code quality issues. Produces line-level review comments and can automatically apply…

alibaba/open-code-review · 98 tokens

harness-creator

Build, audit, and improve harnesses that make AI coding agents reliable: AGENTS.md/CLAUDE.md instruction files, feature/state tracking, verification gates, scope boundaries, session handoff, memory persistence, context budgets, tool-permission safety, and multi-agent coordination. Use this whenever a coding agent is…

walkinglabs/learn-harness-engineering · 142 tokens

babysit

Same-session monitoring loop for PRs, CI runs, tickets, and deployments using the monitorstart / monitorupdate / autonudgestop MCP tools. The loop re-injects your check instructions into THIS session on an idle interval — same context, same tools — and works from dashboard chat, Slack threads, and Discord DMs. Use…

kirodotdev/KiroCrew · 137 tokens

technical-writing

Write, edit, review, or audit user-facing documentation for the eve repository. Use for changes under docs/, documentation tied to eve APIs or CLI behavior, docs work based on Slack or support feedback, and requests to make eve docs clearer, more natural, or less AI-patterned while verifying claims against current…

vercel/eve · 78 tokens

langsmith-observability

LLM observability platform for tracing, evaluation, and monitoring. Use when debugging LLM applications, evaluating model outputs against datasets, monitoring production systems, or building systematic testing pipelines for AI applications.

synthetic-sciences/openscience · 45 tokens