agenthold

io.github.edobusy由 GitHub 账号 edobusy 发布v0.10.0更新于 Oct 24, 2026

Shared versioned state for multi-agent AI workflows

概览

AI 生成的概览

为多个 AI 代理提供带版本的共享状态与冲突检测,使并发写入被拒绝而不是静默覆盖。

可以做什么
agenthold 是一个 MCP 服务器,为多代理工作流提供带版本的共享状态,采用乐观并发控制:每个值都带版本号,若写入时传入的版本已过期,写入会被拒绝并返回 ConflictError。标准模式提供五个协调工具——register、claim、release、status 和 wait——让代理对某个资源取得独占访问、记录 modified、created、deleted 或 moved 等结果,并等待被占用的资源释放。高级模式增加直接读写版本化存储的底层原语,包括 get、set、list、history、delete、watch、clear 和 export。它也可以作为 Python 库直接调用。
适用场景
当多个代理或进程可能先读取再写入同一个值、文件或资源,而静默覆盖会破坏结果时使用,例如共享预算、订单记录或并发编辑的文件。也适合需要带审计轨迹的占用与释放协议、想了解谁改动了什么的场景。它不是编排框架,而是位于编排层之下。
运行要求
以 Python 包形式在本地运行(pip 或 uvx),由 MCP 客户端通过 stdio 启动。需要通过 --db 指定 SQLite 数据库路径,首次运行会自动创建。可选参数可配置工作区、占用超时以及 HTTP 传输的主机、端口和路径。HTTP 模式可通过 AGENTHOLD_AUTH_TOKEN 环境变量或 --auth-token 要求 bearer 令牌。无需账号或 API 密钥。
安装前请注意
在 HTTP 模式下,若绑定到 localhost 之外且未设置令牌会打印警告;bearer 令牌的私密性取决于传输通道,建议通过反向代理加 TLS;令牌通过 Authorization 头传递,也可用 AGENTHOLD_AUTH_TOKEN 设置。占用与状态写入会修改共享数据,存储是 SQLite 文件,应像其他数据库一样备份。长时间运行的服务器尚不会清理闲置代理记录,建议设置占用超时并定期重启。

安装

在 SourceWeft 中

  1. 打开 控制台中的 agenthold,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

agenthold

Stop your AI agents from silently overwriting each other.

When two agents update the same value, the second write quietly destroys the first. No error, no exception, just wrong data and a system that keeps running. agenthold is an MCP server that gives agents shared, versioned state with conflict detection built in. Think of it as git for your agents' working memory.

[CI] [PyPI version] [PyPI Downloads] [Coverage 80%+] [Python 3.11+] [Ruff] [Glama score] [License: MIT]


The problem

When two agents update the same value at the same time, the second write silently overwrites the first. No exception is raised. The value is wrong. The system keeps running.

[Without agenthold: the silent overcommit problem]

Two agents read a $10,000 budget and allocate from it independently. Total committed: $15,000. The budget object never complains. This is a read-modify-write conflict: each agent's write assumes nothing changed since its read.


How it works

agenthold solves this with optimistic concurrency control (OCC), the same mechanism Postgres uses in UPDATE ... WHERE version = N and DynamoDB uses in conditional writes.

Every value stored in agenthold has a version number. When an agent writes, it passes the version it read. If the stored version has changed since the read, the write is rejected with a ConflictError that includes the current value. The agent re-reads, recalculates, and retries.

[With agenthold: conflict-safe allocation]

The losing agent detects the conflict, re-reads the real remaining budget ($2,000), and adjusts its allocation. The total committed is always exactly $10,000. Every write is tracked.

OCC is the right fit for agent workflows because:

  • Agents do work between reads and writes (network calls, LLM inference). You cannot hold a database lock across that work.
  • Conflicts are rare. Retrying once is cheaper than acquiring a lock on every read.
  • The retry logic is simple, explicit, and fully in the agent's control.

Works with any agent framework

agenthold connects via MCP (Model Context Protocol), the open standard for tool integration. Any framework that speaks MCP can use agenthold with zero glue code.

FrameworkHow to connect
Claude Desktop / Claude CodeBuilt-in: add to mcpServers config
Cursor / Continue / WindsurfBuilt-in: add to MCP config
LangChain / LangGraphlangchain-mcp-adapters
CrewAINative mcps field on Agent
OpenAI Agents SDKBuilt-in mcp_servers param
Google ADKBuilt-in MCP Toolbox
AutoGenautogen_ext.tools.mcp
PydanticAINative MCP integration

agenthold is not a framework. It is shared infrastructure that sits underneath your orchestration layer, the same way a database sits underneath your application. Your agents keep their existing tools and logic; agenthold adds the coordination primitive they are missing.

Not using MCP yet? agenthold also works as a Python library you can call directly from any framework. Import StateStore, call .get() and .set() with version checks, and you have conflict-safe shared state.


Architecture

mermaid
graph LR    A1["Agent 1    LangChain, CrewAI, etc."] -->|MCP| S["agenthold    MCP Server"]    A2["Agent 2    Claude, OpenAI, etc."] -->|MCP| S    A3["Agent 3    AutoGen, ADK, etc."] -->|MCP| S    S --> DB[("SQLite    WAL mode")]    DB -->|version 3| S    S -->|"conflict! retry"| A2

Every write carries a version number. If the stored version has changed since an agent's read, the write is rejected and the agent retries with current data. This is the same mechanism used by Postgres conditional updates and DynamoDB conditional writes.


Quick start

1. Install

bash
pip install agenthold# oruv pip install agenthold

2. Add to your MCP client config

json
{  "mcpServers": {    "agenthold": {      "command": "agenthold",      "args": ["--db", "/path/to/state.db"]    }  }}

3. Done

Agents automatically coordinate. No CLAUDE.md, no system prompt changes, no namespace design.

When an agent connects, it sees five self-documenting tools: agenthold_register, agenthold_claim, agenthold_release, agenthold_status, and agenthold_wait. The tool descriptions tell the agent when and how to use each one. Server instructions reinforce the protocol when the MCP client includes them.


Resources

agenthold identifies resources by canonical URIs. Tools accept either form:

  • Bare path (e.g. "src/main.py") — resolves against the workspace named default, or the only configured workspace if exactly one exists.
  • Explicit URI — "file://<workspace>/<path>" for files, "custom://<name>" for opaque resources.

Equivalent inputs (./src/main.py, src\main.py, src//main.py, an absolute path inside the workspace) all canonicalize to the same internal URI, so two agents using different shorthands never fragment the keyspace. Path traversal (..) and dot segments (.) are rejected at the boundary.

On case-insensitive filesystems (Windows and macOS by default), file resources are matched case-insensitively, so src/Main.py and src/main.py resolve to the same resource — two agents can't both claim the same physical file. This follows the running platform; custom:// names are always case-sensitive.

Configure workspaces with --workspace name=path (repeatable). With no flag, agenthold creates a single default workspace at the current working directory. Multi-workspace setups let one agenthold process coordinate across separate codebases.


Tools

agenthold exposes five coordination tools by default.

agenthold_register

Register yourself and receive a unique agent ID. Must be called once before using agenthold_claim or agenthold_release.

json
{ "name": "editor-agent", "model": "claude-sonnet-4-6" }
json
{  "status": "registered",  "agent_id": "agent-a1b2c3d4",  "name": "editor-agent",  "registered_at": "2026-03-18T10:00:00+00:00"}

agenthold_claim

Claim exclusive access to a resource before modifying it. Requires a registered agent_id.

json
{ "resource": "intro.md", "agent_id": "agent-a1b2c3d4" }

Claimed (you hold exclusive access):

json
{ "status": "claimed", "resource": "file://default/intro.md", "version": 1 }

If the resource has a non-trivial prior history (deleted, moved, abandoned, or expired), the response also carries previous_outcome, previous_holder, previous_outcome_at, and a hint describing what the previous holder did. For previous_outcome: "moved", moved_to is the new resource URI.

Busy (another agent is working on this resource):

json
{  "status": "busy",  "resource": "file://default/intro.md",  "held_by": "agent-e5f6g7h8",  "claimed_at": "2026-03-18T10:00:00+00:00",  "hint": "Another agent holds this resource. Work on a different resource, or call agenthold_wait to be notified when it becomes available."}

Already claimed (you already hold this claim, idempotent):

json
{ "status": "already_claimed", "resource": "file://default/intro.md", "version": 1 }

agenthold_release

Release your claim with an explicit outcome describing what you did. The outcome is preserved in the free-state record and shown to the next claimant so they don't act on stale assumptions. Requires a registered agent_id.

json
{  "resource": "intro.md",  "agent_id": "agent-a1b2c3d4",  "outcome": "modified"}
json
{ "status": "released", "resource": "file://default/intro.md", "version": 2, "outcome": "modified" }

Outcomes: released (default — no lifecycle claim), modified (changed in place), created (didn't exist before), deleted (no longer exists at this resource), moved (relocated — also pass moved_to with the new resource).

For renames (mv old new): claim BOTH paths, do the rename on disk, then release the source with outcome: "moved", moved_to: "new" and the destination with outcome: "created".


agenthold_status

Check whether a resource is available or currently claimed. Does not require registration.

json
{ "resource": "intro.md" }

Available:

json
{ "status": "available", "resource": "file://default/intro.md" }

If a previous holder declared a non-trivial outcome (deleted, moved, abandoned, expired), the response also includes previous_outcome, previous_holder, previous_outcome_at, and a hint. For moved, moved_to is the new resource URI.

Claimed:

json
{  "status": "claimed",  "resource": "file://default/intro.md",  "held_by": "agent-e5f6g7h8",  "agent_name": "editor-agent",  "agent_model": "claude-sonnet-4-6",  "claimed_at": "2026-03-18T10:00:00+00:00",  "version": 3}

agenthold_wait

Wait for a claimed resource to become available. Blocks the agent turn until the holder releases, or the timeout expires.

json
{ "resource": "intro.md", "timeout_seconds": 30 }

Available (resource was released):

json
{ "status": "available", "resource": "file://default/intro.md", "elapsed_seconds": 2.4 }

When the wait fires on a release with a non-trivial outcome, the response also carries previous_outcome, previous_holder, previous_outcome_at, optional moved_to, and a hint. An agent that was waiting to edit a moved or deleted resource learns why the path became available.

Timeout:

json
{  "status": "timeout",  "resource": "file://default/intro.md",  "held_by": "writer-2",  "elapsed_seconds": 30.2,  "hint": "The resource was not released within the timeout. Try working on a different resource, or call agenthold_wait again with a longer timeout."}

Advanced tools

For custom coordination protocols, agenthold exposes eight low-level primitives via --tools advanced:

agenthold_get · agenthold_set · agenthold_list · agenthold_history · agenthold_delete · agenthold_watch · agenthold_clear_namespace · agenthold_export

These give agents direct read/write/watch access to the versioned state store with full OCC conflict detection. No server instructions are sent in this mode.

See the full advanced tools reference →


Conflict detection

The read-modify-write pattern with expected_version is the core of agenthold. Here is the canonical retry loop:

python
from agenthold.store import StateStorefrom agenthold.exceptions import ConflictError
store = StateStore("./state.db")
record = store.get("campaign", "budget")   # read once before doing workdo_expensive_work()                         # LLM call, API request, etc.
while True:    new_value = compute_new_value(record.value)    try:        store.set(            "campaign", "budget", new_value,            updated_by="my-agent",            expected_version=record.version,        )        break   # write succeeded    except ConflictError:        record = store.get("campaign", "budget")   # re-read and retry

Why this works: The version number is the contract. If the stored version has advanced since your read, another agent wrote first. You take the current value, recalculate, and try again. The number of retries is bounded by the number of concurrent writers. In practice, agents almost never conflict more than once.

Why not locks? Locks require a lease mechanism (what happens if the agent crashes holding a lock?), add latency on every read, and interact badly with the long I/O waits inherent in agent workflows. OCC pays a cost only when there actually is a conflict.


Use as a Python library

python
from agenthold.store import StateStorefrom agenthold.exceptions import ConflictError
store = StateStore("./state.db")
# Write a value (first write, no conflict check needed)store.set("order-1234", "status", "received", updated_by="intake-agent")
# Read it back; always get the version number toorecord = store.get("order-1234", "status")print(record.value)    # "received"print(record.version)  # 1
# Write with conflict detection; pass the version you readtry:    store.set(        "order-1234", "status", "processing",        updated_by="fulfillment-agent",        expected_version=record.version,  # rejected if another agent wrote first    )except ConflictError as e:    # Another agent wrote between your read and write.    # e.detail has the current version, value, and who wrote it.    record = store.get("order-1234", "status")    # ... recalculate and retry

What it looks like in practice

In a multi-agent session, the coordination is automatic. An agent's tool calls look like this:

Agent A: agenthold_register(name="writer", model="claude-sonnet-4-6")         → agent_id: "agent-a1b2c3d4"
Agent A: agenthold_claim(resource="chapter-3.md", agent_id="agent-a1b2c3d4")         → status: "claimed", resource: "file://default/chapter-3.md"
Agent B: agenthold_claim(resource="chapter-3.md", agent_id="agent-e5f6g7h8")         → status: "busy", hint: "Work on a different resource..."
Agent A: agenthold_release(resource="chapter-3.md", agent_id="agent-a1b2c3d4", outcome="modified")         → status: "released", outcome: "modified"

No system prompt engineering. The tool descriptions guide the agents.

Worked examples

Two worked examples are included, each with a "before" and "after" script.

Order processing: two agents update the same order record concurrently:

bash
uv run python examples/order_processing/without_agenthold.py   # silent overwriteuv run python examples/order_processing/with_agenthold.py      # conflict detection + retry

Budget allocation: two agents draw from a shared marketing budget:

bash
uv run python examples/budget_allocation/without_agenthold.py  # $10k budget → $15k committeduv run python examples/budget_allocation/with_agenthold.py     # exact allocation, full audit trail

Configuration

bash
agenthold --db ./state.db                              # standard mode (default)agenthold --db ./state.db --tools advanced             # advanced modeagenthold --db ./state.db --claim-ttl 1800             # standard + 30 min TTLagenthold --workspace myproj=/abs/path                 # named workspaceagenthold --workspace a=/x --workspace b=/y            # multiple workspacesagenthold --transport http --port 8417                 # serve over HTTP (see below)
FlagDefaultDescription
--db./agenthold.dbPath to the SQLite database file. Use :memory: for an in-process store (testing only; data is lost when the process exits).
--toolsstandardTool set: standard (register/claim/release/status/wait) or advanced (get/set/delete/watch/list/history/clear/export).
--claim-ttlNone (no expiry)Seconds before an inactive agent's claims expire. Only applies in standard mode. When set, claims held by agents whose last activity exceeds this value are treated as expired and can be taken by other agents. Recommended with --transport http.
--workspaceone workspace named default at the current working directoryConfigure a workspace as name=path (e.g. myproj=/abs/path) or as an absolute path (name derived from the basename). Repeatable. Multiple workspaces let one agenthold process coordinate across separate codebases against the same database. Bare paths in tool inputs resolve against the workspace named default, or against the only configured workspace if exactly one exists.
--transportstdiostdio (one local subprocess per agent) or http (one long-lived server many agents connect to over Streamable HTTP).
--host127.0.0.1HTTP bind address. Only used with --transport http.
--port8417HTTP port. Only used with --transport http.
--path/mcpHTTP endpoint path the MCP transport is mounted at. Only used with --transport http.
--json-responseoffReturn JSON responses instead of SSE streams over HTTP. Only used with --transport http.
--allowed-hostnoneEnable DNS-rebinding protection and allow this Host header value. Repeatable. When omitted, protection stays disabled (localhost-friendly). Only used with --transport http.
--auth-tokennoneRequire this bearer token on every HTTP request (Authorization: Bearer <token>). Repeatable. Also settable via the AGENTHOLD_AUTH_TOKEN env var (comma-separated), which is preferred. Only used with --transport http.

The database file is created automatically on first run. Back it up like any other SQLite file.

HTTP transport

By default agenthold speaks stdio: your MCP client spawns one agenthold subprocess per agent, and those subprocesses coordinate through the shared SQLite file on the same machine. That is perfect for local, single-machine multi-agent runs.

To coordinate agents that live in different processes, containers, or hosts, run one long-lived agenthold server over Streamable HTTP and point every agent at it:

bash
agenthold --db ./state.db --transport http --host 127.0.0.1 --port 8417 --claim-ttl 1800

Then connect MCP clients by URL instead of by command:

json
{  "mcpServers": {    "agenthold": {      "url": "http://127.0.0.1:8417/mcp"    }  }}

All five standard tools (and the advanced set, with --tools advanced) work identically over HTTP — only the transport changes. Because a single server now serves many agents over its lifetime, set --claim-ttl so a claim held by an agent that disconnects is automatically reclaimable.

Authentication

To require a bearer token on every HTTP request, set one or more tokens. Prefer the environment variable so the token doesn't appear in process listings:

bash
AGENTHOLD_AUTH_TOKEN=s3cr3t agenthold --db ./state.db --transport http --host 0.0.0.0# or, less privately:agenthold --transport http --auth-token s3cr3t --auth-token another-token

Clients then send the token in the Authorization header:

json
{  "mcpServers": {    "agenthold": {      "url": "http://your-host:8417/mcp",      "headers": { "Authorization": "Bearer s3cr3t" }    }  }}

Requests without a valid token are rejected with 401 before reaching the store. Tokens are compared in constant time. Authentication applies to --transport http only (stdio is a trusted local transport). This release is all-or-nothing authentication; per-namespace scoping is on the roadmap.

The AGENTHOLD_AUTH_TOKEN value is split on commas, so a token itself must not contain a comma (use repeated --auth-token for such tokens). If authentication is requested but every token is blank, the server refuses to start rather than serving without auth.

Security. Bearer tokens are only as private as the transport carrying them — put TLS in front of agenthold (a reverse proxy) for any real deployment. The default bind address is 127.0.0.1 (localhost only); binding beyond localhost without --auth-token prints a startup warning. Pass --allowed-host <host> (repeatable) to enable DNS-rebinding (Host-header) protection — note this is not authentication and does not replace --auth-token.

Long-lived servers. agenthold does not yet reap idle agent records, so a server that runs for a very long time with high agent churn will accumulate agent metadata. Set --claim-ttl (so disconnected agents' claims recover) and restart periodically if needed. Automatic reaping is on the roadmap.


Inspecting the store

An agenthold database is just a SQLite file, but you rarely want to open it by hand. The agenthold command doubles as a read-only inspector so you can see what agents are doing at a glance — no MCP client required. These commands are strictly read-only (the database is opened with query_only and no schema writes), so they never modify the store — even if you point --db at the wrong file.

bash
agenthold agents --db ./state.db          # who is registeredagenthold claims --db ./state.db          # what is currently claimed, and by whomagenthold claims --db ./state.db --all    # also show freed/moved/deleted claimsagenthold namespaces --db ./state.db      # namespaces + record countsagenthold keys orders --db ./state.db     # keys in a namespaceagenthold history orders order-1 --db ./state.db   # a key's version history

Example:

$ agenthold claims --db ./state.dbRESOURCE                    STATE    BY            SINCE--------------------------  -------  ------------  ------custom://chapter-1          claimed  editor-agent  2s agofile://default/src/main.py  claimed  review-bot    2s ago

Every command accepts --db PATH (default ./agenthold.db) and --json for machine-readable output. A bare agenthold (no subcommand) still starts the MCP server exactly as before — the inspector is purely additive.


Development

bash
git clone https://github.com/edobusy/agenthold.gitcd agentholduv sync --all-extras --dev

Run the tests:

bash
uv run pytest tests/ -v

Check coverage:

bash
uv run pytest tests/ --cov=agenthold --cov-report=term-missing

Lint and type-check:

bash
uv run ruff check src/ tests/uv run ruff format src/ tests/uv run mypy src/

CI runs on Python 3.11 and 3.12 on every push to main. See CONTRIBUTING.md for detailed guidelines.


Technical notes (design decisions for engineers)

Why SQLite? SQLite is the right tool for this scope. It is zero-dependency, ships in the Python stdlib, and runs everywhere. WAL mode is enabled so that read-only operations (exports, watches) do not block writers across processes. Write transactions use BEGIN IMMEDIATE to acquire the write lock upfront, ensuring OCC conflict detection works correctly even when multiple agenthold processes share the same database file. busy_timeout is set to 5 seconds so a second writer waits rather than failing immediately. Postgres adds an ops dependency with no benefit at this scale. The storage backend is behind a clean interface (StateStore) that can be swapped for Postgres when the need arises. Choosing a simple tool deliberately is not a limitation.

Why OCC instead of pessimistic locking? Locks require the holder to release them, which means the system must handle crashes, timeouts, and stale holders. That complexity is not worth it when conflicts are rare. OCC pays a cost only when a conflict actually occurs: one extra read and one retry. For multi-agent workflows where agents do significant work between reads and writes (LLM inference, API calls, tool execution), OCC is the correct choice.

What the versioning guarantees: Each key has a version that starts at 1 and increments by exactly 1 on every write. The state_history table is append-only and records every write before the live record is updated, so a crash between the two writes leaves history consistent. Deletions also write a tombstone entry to state_history (with event_type: "delete") before removing the live record, so the full lifecycle of a key is visible in history. The ordering guarantee is per-key, not global; two different keys can have their versions updated in any order.

What would change for production scale: Mainly one thing: replace SQLite with Postgres for better concurrent write throughput, replication, and managed hosting. The StateStore interface is already designed to make this a contained change. The network transport and authentication already exist — agenthold serves Streamable HTTP via the MCP SDK's StreamableHTTPSessionManager (so remote agents connect over the network instead of a local process), and --auth-token gates access with a bearer token (see Authentication). Put TLS in front via a reverse proxy for production, and note that per-namespace/tenant scoping of tokens is not yet implemented.


License

MIT. See LICENSE.


mcp-name: io.github.edobusy/agenthold

来源:README.md,提交 d93a54c

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v0.10.0最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分