semantic-saga-mcp
semantic-saga-mcp
一个独立的 Model Context Protocol (MCP) 服务器,将 Saga 模式应用于智能体工作流。它执行白名单中的副作用操作,维护持久的 SQLite 日志,并在某个步骤失败或 MCP 客户端请求回滚时,按相反顺序自动调用补偿操作。
保证
写前意图: 步骤在发出前向请求之前以
EXECUTING状态存储。进程崩溃后,此类不确定步骤有资格进行补偿。自动回滚: 失败的步骤会将 saga 标记为失败,并回滚该步骤及之前已完成的步骤。失败的请求也会被包含在内,因为网络错误可能发生在远程变更之后。
逆序补偿: 已完成的变更按从新到旧的顺序回退。
幂等性: 前向请求和补偿请求都会收到稳定的
Idempotency-Key请求头。端点必须遵循这些键,因为网络无法提供恰好一次(exactly-once)的投递保证。持久性与可检查性: saga、结果、错误和重试次数都存储在 SQLite 中,可通过
get_saga获取。会话隔离: 每个 saga 都由其传输会话所拥有。来自其他已连接智能体的查找、提交、步骤和回滚操作,其行为就像该 saga 不存在一样。
模式强制: Pydantic 严格模型会在协调器代码运行之前拒绝缺失、类型错误或意外的 JSON-RPC 工具参数。
安全操作面: 智能体只能选择管理员配置的操作;它们无法提供任意的 URL 或凭据。
这是一个协调框架,而非跨越独立系统的 ACID 事务。补偿操作本身也可能失败。该状态会以 ROLLBACK_FAILED 报告,以便操作员或客户端重试,而不会被隐藏。
Related MCP server: sagashield-mcp
快速开始
需要 Python 3.11 或更高版本。
python -m pip install -e .
semantic-saga-mcp --actions ./examples/actions.json --database ./semantic-saga.db示例 MCP 客户端配置:
{
"mcpServers": {
"semantic-saga": {
"command": "semantic-saga-mcp",
"args": ["--actions", "/absolute/path/actions.json", "--database", "/absolute/path/sagas.db"]
}
}
}环境变量 SAGA_ACTIONS_FILE 和 SAGA_DATABASE 可替代命令行标志。
远程 SSE 传输
默认的 stdio 传输适用于本地 IDE 和桌面集成。对于远程智能体,请改用 MCP SSE 传输:
semantic-saga-mcp --transport sse --host 0.0.0.0 --port 8000 \
--actions ./examples/actions.json --database ./semantic-saga.db如果需要,可以设置 SAGA_TRANSPORT、SAGA_HOST 和 SAGA_PORT 来代替相应的标志。SSE 客户端连接到 GET /sse;服务器会为该连接生成唯一的 POST /messages?session_id=... 端点。在私有网络之外暴露该服务时,请部署在受信任的反向代理之后,并启用 TLS 和身份验证。
配置操作
操作配置由服务器操作员控制。每个操作将一个前向 HTTP 请求与一个回滚请求配对:
{
"charge_card": {
"forward": {
"url": "https://payments.internal/charges",
"method": "POST",
"headers": {"Authorization": "Bearer configured-secret"},
"body": {"amount": "${input.amount}", "account": "${input.account}"},
"timeout_seconds": 15
},
"rollback": {
"url": "https://payments.internal/refunds",
"method": "POST",
"headers": {"Authorization": "Bearer configured-secret"},
"body": {"charge_id": "${result.charge_id}"}
}
}
}整个字符串可以是类型化模板值。支持的根为 input、result、saga 和 step,例如 ${input.amount}、${result.charge_id}、${saga.id} 和 ${step.id}。请勿在操作文件中提交机密信息;应生成受保护的运行时配置。
MCP 工具
工具 | 用途 |
| 创建一个 |
| 运行已配置的操作。失败时自动开始回滚。 |
| 完成一个成功的 saga 并阻止后续回滚。 |
| 按相反顺序显式补偿符合条件的步骤。 |
| 返回持久的 saga 和步骤日志。 |
典型的客户端流程如下:
调用
begin_saga并保留id。使用该
saga_id为每个变更调用execute_saga_step。仅在整个工作流被接受时才调用
commit_saga。在客户端验证错误或幻觉(hallucination)时调用
rollback_saga。服务器端的操作错误会自动触发此操作。
开发
python -m unittest discover -s tests -vMCP 传输仅将 JSON-RPC 消息写入 stdout。请将应用程序诊断信息保留在 stderr 中,以便客户端能够解析协议流。
Available Tools
18 toolsapprove_saga_stepC
Approve or reject a workflow node; approvals are subject to tenant governance while rejection remains fail-safe.
Inputs: node_id (required), saga_id (required), reason, approved.
begin_sagaB
Start a durable transactional workflow.
Inputs: metadata.
checkpoint_sagaC
Persist a named workflow checkpoint and operator/agent-provided checkpoint data.
Inputs: name (required), saga_id (required), data.
commit_sagaC
Commit a completed saga after current tenant governance checks.
Inputs: saga_id (required).
execute_saga_stepC
Immediately execute an action after current governance, schema, and action-policy checks.
Inputs: input (required), action (required), saga_id (required).
get_actionA
Inspect one registered action contract by id and optional version.
Inputs: action (required), version.
get_audit_eventsC
Read append-only audit events without exposing action inputs, results, or secret material.
Inputs: saga_id (required), limit, event_types.
get_policy_decisionsB
Read durable governance decisions and safety overrides for one tenant-owned saga.
Inputs: saga_id (required), limit.
get_policy_statusB
Inspect the effective governance backend, revision, budgets, approval threshold, and rule ids for the caller tenant.
Inputs: tenant_id.
get_sagaA
Inspect saga, workflow DAG, checkpoints, action versions, results, approvals, and recovery state.
Inputs: saga_id (required).
get_saga_timelineC
Inspect a payload-safe timeline combining steps, workflow nodes, audit evidence, and integrity status.
Inputs: saga_id (required), limit.
list_actionsA
List active action contracts, schemas, semantic effects, risk, hashes, and execution policies.
Inputs: no named parameters.
plan_saga_stepB
Persist a version-pinned workflow node; governance may add an approval gate or reject the plan.
Inputs: input (required), action (required), saga_id (required), key, +2 more.
retry_saga_stepC
Return a failed/rejected/blocked workflow node to scheduling after current governance checks.
Inputs: node_id (required), saga_id (required), force.
rollback_sagaC
Compensate saga steps in reverse order; rollback remains available as the safety path.
Inputs: saga_id (required).
run_ready_stepsC
Re-evaluate current governance and execute ready DAG nodes in bounded dependency waves.
Inputs: saga_id (required), max_steps, max_parallel.
trigger_rollbackB
Immediately start compensation after a client-detected failure.
Inputs: saga_id (required).
verify_audit_chainC
Verify the per-saga SHA-256 audit hash chain.
Inputs: saga_id (required), limit, event_types.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Most tools have distinct purposes, but several pairs create real ambiguity: trigger_rollback vs rollback_saga both initiate compensation, and execute_saga_step vs run_ready_steps overlap as execution entry points. The descriptions help clarify intent, but an agent could easily select the wrong tool in failure and execution scenarios.
All tools follow a consistent snake_case verb_noun pattern, such as begin_saga, get_saga, plan_saga_step, and commit_saga. The naming is predictable and clearly signals the resource being acted on, with no mixing of conventions.
At 18 tools, the server is on the heavier side but each tool addresses a distinct facet of saga orchestration, governance, audit, and action management. The count feels slightly high but is justified by the domain complexity.
The saga lifecycle is well covered: begin, plan, execute, approve, retry, checkpoint, commit, rollback, and inspect. Minor gaps exist, such as no list_sagas endpoint for enumerating existing sagas and no action registration tools, but agents can work around these limitations.
Maintenance
Related MCP Connectors
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Compensation registry for agent actions: inverses registered before effects land, with rewind
Runtime permission, approval, and audit layer for AI agent tool execution.
Reliable async execution for agent tool calls: schema gating, retries, idempotency, audit trail.
Related MCP Servers
- AlicenseAqualityDmaintenanceProvides transactional intelligence for AI agents, enabling safe tool execution with pre-flight invariant checks, sub-second filesystem snapshots/rollback, causal tracing, belief contradiction detection, and 15 native MCP tools for Claude Code.15MIT
- AlicenseNot gradedqualityBmaintenanceEnables MCP clients to run agent tool calls as ACID saga transactions with Step-0 security screening, state-machine authorization, write-ahead logging, idempotency, crash recovery, and automatic compensation on failure.1Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables durable, crash-safe control of long-running AI-agent workflows with idempotent operations and scope-aware reconciliation over MCP filesystem and execution tools.1Apache 2.0
- AlicenseNot gradedqualityCmaintenanceProvides transactional rollback and compensating sagas for MCP tools, enabling atomic multi-step execution and automatic restoration of external systems to a clean state upon failure.Apache 2.0