Ratchet

com.ratchetgate由 ratchetgate.com 發布官方發布者v0.3.0更新於 Oct 24, 2026

Your agent asks before it acts, so the same real-world action is attempted at most once.

已驗證Streamable HTTP可網頁執行效率與工作流開發者工具安全與監控

概覽

AI 產生的概覽

Ratchet 是一道效果閘門,讓 AI 助理在執行不可回復的真實操作前先請求許可,並記錄持久決策。

可以做什麼
在副作用操作執行前後申請、回報與延長租約,讓每個操作最多只發起一次,後續呼叫者重播已記錄的結果而不重複執行。查詢單一效果或整個執行的已記錄狀態,並在向第三方核實後解決處於不確定狀態的效果。檢視近期效果、多步驟工作流程群組,以及部分失敗時依相反順序復原所需的補償操作。讀取工作區策略、方案用量與支出上限,並列出每次決策(含拒絕)的簽章收據。核對供應商回報的操作鍵,並統計過去 30 天被拒絕的重複操作。
適用情境
當助理執行無法撤回的操作(例如傳送訊息、扣款、部署或發佈),且需要在當機、重試和多個獨立助理程序之間保證最多發起一次時使用。也適合在重新啟動或上下文壓縮後接續任務,以及稽核一次執行實際做了什麼。
執行需求
需要 Ratchet 主控台建立的 API 金鑰,放在 RATCHET_API_KEY 中。可使用遠端端點,或透過 stdio 執行本機 npm 套件 ratchet-mcp(需要 Node.js)。自架需要 Node 20.11+、Postgres(本機開發可用 Docker)、DATABASE_URL 與 AUTH_SECRET,並以 RATCHET_BASE_URL 指向該執行個體。
安裝前請注意
Ratchet 位於關鍵路徑上:需事先決定服務無法連線時助理是放行執行還是拒絕執行。閘門只有在助理遵守決策並如實回報時才有效;誤報 failed 可能導致重複操作。內容只存指紋不存原文,但效果中介資料與冪等鍵會傳送到該服務。依受控效果計費,有付費方案與預付超額額度。尚無第三方稽核或 SOC 2 報告。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Ratchet,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

交給代理程式安裝

把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。

閱讀 https://sourceweft.com/mcp/com.ratchetgate%2Fratchet/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。

檢視代理程式所依據的安裝指南

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。

{
  "mcpServers": {
    "ratchet": {
      "type": "http",
      "url": "https://ratchetgate.com/mcp"
    }
  }
}

README

[Ratchet — an effect gate for AI agents]

[CI] [CodeQL] [npm] [License] [OpenSSF Scorecard] [OpenSSF Best Practices] [NIST SSDF] [REUSE]

An effect gate for AI agents. Your agent asks before it does anything it cannot take back — charge a card, ship a deploy, publish a package, send the email — and gets a durable decision, so the same real-world action is attempted at most once across crashes and retries. Agents can also read back what a run already did, and spend against a limit they cannot raise.

Agents retry. LLM control flow is non-deterministic, network calls fail ambiguously, and processes die mid-action. The result is duplicate emails, double charges, and repeated writes — and nothing in the stack knows which. Vendor idempotency keys help for the few vendors that offer them, and never across separate agent processes or model providers.

Ratchet does not execute your actions. It holds a durable decision record in front of them.

POST /v1/effects/begin  →  decision: execute | duplicate | in_flight
                                    | blocked | approval_required | denied

Only execute authorises the caller to act.


Project documents

ArchitectureHigh-level design — what the gate is and what it deliberately is not
Assurance caseThreat model, trust boundaries, and the argument for each security requirement — including what is not defended
RoadmapWhat the next year holds, and what will never be built
GovernanceWho decides, and what happens if they stop
ContributingHow to report a bug or propose a change
Security policyHow to report a vulnerability, and how fast you hear back
Code of conductWhat is expected, and who to tell
Known limitationsEverything that is not true yet, stated plainly

The part that matters

If your process dies between "go" and "done", most systems quietly let the next caller retry. Ratchet won't. The lease expires and the effect becomes indeterminate — a known unknown, surfaced instead of buried. What happens next is the policy you declared for that effect type:

on_indeterminateBehaviourUse for
block (default)No automatic retry. A human or verifying agent resolves it.Anything irreversible
retryA fresh attempt is granted, up to max_attempts.Vendors that are genuinely idempotent
probeCaller must verify at the vendor and record evidence first.Charges, transfers, payouts

Exactly-once delivery is not achievable in a distributed system and this project does not claim it. What Ratchet guarantees is at-most-once initiation, a recorded outcome that later callers replay, and an explicit state for the case nobody else admits exists.


Quick start

Requirements: Node 20.11+, Docker (for local Postgres).

npm install
cp .env.example .env          # defaults work for local development
npm run dev:db                # Postgres on :5433 via Docker
npm run migrate
npm run dev                   # control plane on :8787
npm run dev:worker            # lease reaper + webhook delivery (separate terminal)

Then open http://localhost:8787, or drive it from the shell:

bash examples/curl/walkthrough.sh

npm run seed populates a workspace with realistic state — a completed effect, a duplicate, an indeterminate one, and one awaiting approval — so the console has something to show.

Or with Docker Compose

AUTH_SECRET=$(openssl rand -base64 32) docker compose up --build

The core loop

# 1. Ask, before you act.
curl -X POST http://localhost:8787/v1/effects/begin \
  -H "Authorization: Bearer $RATCHET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "effect_type": "email.send",
    "idempotency_key": "welcome:user_123",
    "payload": { "to": "[email protected]" },
    "estimated_cost_micros": 800
  }'
# → { "decision": "execute", "effect_id": "eff_...", "lease_token": "lt_..." }

# 2. Do the real thing, yourself. Ratchet never touches it.

# 3. Say what happened.
curl -X POST http://localhost:8787/v1/effects/eff_.../report \
  -H "Authorization: Bearer $RATCHET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "lease_token": "lt_...", "outcome": "succeeded",
        "result": { "message_id": "msg_9f2" } }'

# Any later caller with the same key now gets:
# → { "decision": "duplicate", "result": { "message_id": "msg_9f2" } }

The one rule: report failed only when you know the action did not reach the outside world. If you are unsure — a timeout, a dropped connection — report nothing. The lease lapses and Ratchet records an honest indeterminate. A false failed is worse than silence, because it licenses a duplicate.

Idempotency keys

Derive the key from the work, deterministically.

GoodBroken
welcome-email:user_123uuid4()
invoice:2026-08:acct_88123"send-" + Date.now()
pr:acme/api:feature-authf"job-{attempt_number}"

A key that changes on every attempt makes every retry look like new work.


When Ratchet is unreachable

Ratchet sits in your critical path, so decide this before integrating: on an outage your agent either acts without the gate (fail-open) or refuses to act (fail-closed). Use fail-closed for anything you would have to apologise for; fail-open where the vendor deduplicates anyway.

Full contract, client patterns, and the honest availability posture: docs/FAILURE_MODES.md.

Architecture

                    ┌──────────────────────────────┐
  agents ──────────▶│  control plane (stateless)   │
  REST + MCP        │  Fastify · /v1 · /mcp · web  │
                    └──────────────┬───────────────┘
                                   │
                    ┌──────────────▼───────────────┐
                    │  Postgres                    │
                    │  effects · policies · ledger │
                    │  spend windows · audit       │
                    └──────────────▲───────────────┘
                                   │
                    ┌──────────────┴───────────────┐
  webhooks ◀────────│  worker (long-running)       │
                    │  lease reaper · delivery · GC│
                    └──────────────────────────────┘

The control plane is stateless and scales horizontally — it may run on serverless infrastructure. The worker may not. It expires leases on a timer whether or not a request is in flight; a serverless function cannot do that. Run it as a long-running container. Multiple replicas are safe (every claim uses FOR UPDATE SKIP LOCKED).

At-most-once is enforced by a database unique constraint on (workspace_id, effect_type, idempotency_key) — not by application logic.

Full detail: docs/handoff/ARCHITECTURE.md.


Deploying

The control plane is stateless and can scale freely. The worker cannot — it expires leases on a timer whether or not a request arrives, so it must be a long-running process. That single constraint rules out purely serverless hosts (Vercel, Netlify functions) despite their being easier, and is why fly.toml runs both process groups from one image.

brew install flyctl && fly auth login   # once, needs your browser
npm run deploy:fly

The script is idempotent: it creates the app, provisions managed Postgres, generates AUTH_SECRET once (never rotating it, since that would invalidate every API key), deploys both processes, and verifies readiness. It refuses to proceed unless preflight passes:

npm run deploy:preflight

Preflight runs the full suite and production build, then checks that AUTH_SECRET is strong and not the dev default, PUBLIC_URL is set (otherwise the manifest would advertise localhost), RATE_LIMIT_OVERRIDE is unset, private-network webhooks are off, CORS carries no wildcard, and — if Stripe is selected — that both the key and the webhook secret are present. It prints no secret values.

Any container platform works; only fly.toml is Fly-specific. Set DATABASE_URL, AUTH_SECRET, PUBLIC_URL, NODE_ENV=production, then run node dist/api/server.js (scale freely) and node dist/worker/main.js (at least one, always on).

To rehearse the exact production containers locally:

AUTH_SECRET=$(openssl rand -base64 32) docker compose up --build

Commands

CommandWhat it does
npm run devControl plane with reload
npm run dev:workerWorker with reload
npm run dev:db / dev:db:downLocal Postgres in Docker
npm run migrateApply migrations (advisory-locked; safe to run concurrently)
npm run seedPopulate a workspace with realistic state
npm testTypecheck + unit + integration + e2e against a disposable database
npm run test:unit / test:integration / test:e2eOne layer
npm run typecheck / lintTypeScript in strict mode
npm run buildCompile to dist/
npm start / start:workerRun the compiled build
npm run mcp:stdioMCP server over stdio
npm run openapiWrite the OpenAPI document to disk
npm run deploy:preflightVerify the build and configuration are safe to deploy
npm run deploy:flyDeploy control plane, worker, and database to Fly.io
npm run metricsOperating metrics against the pricing-review thresholds
npm run stripe:checkReport payment configuration and verify it against Stripe
npm run stripe:listenForward Stripe events to a local instance and print a webhook secret
npm run auditProduction dependency audit

Environment

Every variable, with defaults and safety notes, is in .env.example. The two that are required:

VariableNotes
DATABASE_URLPostgres connection string
AUTH_SECRET32+ random characters. Derives the API-key pepper and console session ids. Rotating it invalidates every API key and session.

In NODE_ENV=production the process refuses to start if AUTH_SECRET is the development default or shorter than 32 characters, if CORS_ORIGINS contains *, or if WEBHOOK_ALLOW_PRIVATE_NETWORK is on.


For agents

SurfacePath
OpenAPI 3.1/openapi.json — generated from the schemas the routes validate against
Capability manifest/.well-known/agent-manifest.json — including what Ratchet doesn't do
Machine docs/llms.txt
MCP tool schemas/mcp/info
MCP (Streamable HTTP)POST /mcp with Authorization: Bearer <key>
MCP (stdio)npx -y ratchet-mcp with RATCHET_API_KEY — see packages/ratchet-mcp

Seven MCP tools: ratchet_begin_effect, ratchet_report_effect, ratchet_get_effect, ratchet_resolve_effect, ratchet_list_effects, ratchet_get_policy, ratchet_get_usage.

Ready-to-use configs and code: examples/ — Python, TypeScript, curl, Claude Desktop, Cursor, and generic MCP over HTTP.


Security posture

  • Only a SHA-256 fingerprint of your payload is stored — never the payload itself.
  • API keys are stored as HMAC-SHA256 peppered with a server secret; a database leak alone yields no usable key. Comparison is constant-time and runs even for unknown prefixes.
  • Every query is workspace-scoped; a cross-tenant lookup returns 404, never a hint.
  • SSRF defence in two layers: static URL validation, then DNS re-resolution with the socket pinned to the checked address on every delivery attempt. Redirects are never followed.
  • Agent-supplied text is data, never instructions. Decisions come from stored policy and database state — nothing in a payload can widen a scope, raise a budget, or change a policy.
  • Unknown request fields are rejected, not silently dropped.

No third-party audit has been performed. There is no SOC 2 report and no penetration test. Details and threat model: docs/handoff/SECURITY_REVIEW.md.


Pricing

One meter: a gated effect — the first begin for a given (effect_type, idempotency_key). Duplicate suppression, in-flight checks, retries, reports, reads, policy changes, and webhooks are all free. You are never charged for the retry behaviour the product exists to absorb.

PlanPriceIncluded effects/moOverage
Free$01,000$1.50 / 1,000, prepaid credit only
Pro$29/mo25,000$1.50 / 1,000
Customcontactabove 250,000negotiated

Free stops at its allowance unless you load prepaid credit; there is no automatic overage and no invoice. Past roughly 19,300 effects a month, Pro is cheaper than paying credit on Free, so the upgrade is arithmetic rather than a wall.

Two plans, not three: three tiers assert knowledge of three customer segments, and there is no usage history yet to support one. See docs/handoff/PRICING_AND_DISTRIBUTION_REVIEW.md for the reasoning, including why the previous ladder priced a 20x usage range at one number.

Overage draws from prepaid credit, so a runaway agent stops at your balance rather than generating an invoice. Cost model and assumptions: docs/handoff/PRICING_AND_UNIT_ECONOMICS.md.

Payments

Stripe is fully wired: startCheckout creates real Checkout Sessions, and the signed checkout.session.completed webhook credits the ledger. Card details are entered on Stripe's own page and never reach Ratchet, and credit is applied only on the signed webhook — never on the browser returning to a success URL.

Both STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET are required before checkout opens. A key alone selects Stripe but keeps checkout closed: taking a payment that cannot be confirmed would leave a customer charged and uncredited. Run npm run stripe:check to see exactly what is configured (it prints no secret values).

For local development, get a webhook secret without a public URL:

npm run stripe:listen     # prints whsec_… ; put it in .env and restart

Most of Stripe's onboarding checklist does not apply. Ratchet builds line items inline and never reads your Stripe catalog, so there is no product to create; it does not use Stripe Invoicing; and it creates Checkout Sessions through the API, not the no-code builder. What does matter before live payments: verify your account (Stripe's KYC), create a webhook endpoint pointing at your deployed /v1/billing/webhook/stripe and use that endpoint's signing secret in production, and decide whether you need tax collection (STRIPE_AUTOMATIC_TAX, off by default).

With no Stripe credentials at all, the built-in test adapter runs instead: no card is charged and no external request is made. Verified so far in Stripe test mode only — see docs/handoff/KNOWN_LIMITATIONS.md before going live, particularly regarding refunds.


Documentation

DocumentContents
PROJECT_MAP.mdWhere everything lives
ARCHITECTURE.mdState machine, concurrency, deployment topology
DECISIONS.mdEvery significant choice, with the reasoning
API_AND_DATA_CONTRACTS.mdEndpoints, schemas, error codes
SECURITY_REVIEW.mdThreat model and implemented controls
PRICING_AND_UNIT_ECONOMICS.mdCost model and scenarios
VALIDATION_REPORT.mdWhat was tested and measured
KNOWN_LIMITATIONS.mdWhat is not done, and what it would take

License

Apache-2.0.

來源:README.md,提交 35a5ef8

工具

15

ratchet_get_circuit

Check whether surge containment is holding your work

Call this when a begin returned "approval_required" or "denied" and the reason mentions a circuit breaker. A breaker opens when an effect type is being performed far more often than its configured hourly ceiling — usually because something is looping. What to do with the answer: - If a breaker is open, STOP creating effects of that type. Retrying will not help and each attempt is recorded. -…

無需輸入參數。

ratchet_begin_effect

Ask permission to perform a side effect

Call this IMMEDIATELY BEFORE performing any side effect that touches the outside world (sending a message, charging a card, creating a resource, writing to someone else's system). Returns a decision you MUST obey. If the response carries budget_warning, a spend ceiling exists but nothing was counted toward it — surface that to the operator rather than ignoring it. If it carries…

輸入參數run_idvendorpayloadagent_idgroup_keydimensionseffect_type必填compensation另有 4 個

ratchet_report_effect

Report the outcome of an effect you executed

Call this IMMEDIATELY AFTER performing an action that ratchet_begin_effect authorised. Pass the lease_token you were given. Report "succeeded" with a result — future duplicate callers replay that result instead of repeating the action. Report "failed" ONLY when you are certain the action did NOT reach the outside world (for example, a validation error before the request was sent). That permits a…

輸入參數resultoutcome必填effect_id必填lease_token必填failure_reasonactual_cost_micros

ratchet_extend_lease

Say you are still working on an effect

Call this periodically during a long action you were authorised to perform, before the lease expires. It tells Ratchet you are alive and extends your hold. Use it when work turns out to take longer than the lease you asked for — a slow vendor, a large export, a retrying upload. Without it, the lease expires while you are still working, the effect is recorded as having an UNKNOWN outcome, and your…

輸入參數effect_id必填lease_token必填extend_seconds

ratchet_get_effect

Check whether an action has already been done

Look up the recorded state of an action WITHOUT reserving a lease and without consuming your plan allowance. Use it to answer "did I already do this?" — for example when resuming after a crash, or when a user asks whether something went through. To actually perform work, use ratchet_begin_effect instead; this tool never grants permission.

輸入參數effect_type必填idempotency_key必填

ratchet_resolve_effect

Settle an effect whose outcome was unknown

Use ONLY after you have checked the third-party system and now know what really happened to an effect that was left "indeterminate". Record "succeeded" if the action did occur, "failed" if it did not, or "cancelled" to abandon it. Include how you verified it in `evidence`. Never guess: resolving incorrectly is exactly the duplicate or lost action this service exists to prevent.

輸入參數resultoutcome必填evidenceeffect_id必填

ratchet_get_run

What have I already done in this run?

Recall the work already gated under a run id, before doing anything that might repeat it. Call this FIRST when resuming a task — after a restart, a handoff, or when your context has been compacted and you are no longer certain what you did. It returns what succeeded with the recorded results, what is still in flight, what failed, and — separately, because it is the only category that can hurt you…

輸入參數run_id必填

ratchet_list_effects

List recent gated effects

Review recent effects for this workspace, optionally filtered by state or run. Use it to find unresolved work — filter by state "indeterminate" to see every action whose outcome is unknown and still needs verification.

輸入參數limitstaterun_ideffect_type

ratchet_get_policy

Read the policy for an effect type

Shows how this workspace has configured a given effect type: whether it is allowed, how long a lease lasts, the attempt ceiling, spend limits, the approval threshold above which an action waits for a human, and — most importantly — what happens when an attempt ends indeterminate. Check this before designing a retry strategy.

輸入參數effect_type必填

ratchet_unwind_group

Roll back a multi-step unit of work

Call this when a multi-step workflow fails partway and the steps that already succeeded must be undone — a booking made but not paid for, a resource created but not configured. Returns the exact compensations to perform, in the order to perform them, which is the REVERSE of the order they succeeded in. Undoing forwards can strand a step that depended on an earlier one. Ratchet does NOT perform…

輸入參數reasongroup_key必填

ratchet_get_group

Inspect a unit of work

Shows every step in a multi-step unit of work: what succeeded, what can still be undone, what has already been undone, what is irreversible, and what has an unknown outcome. Use it to answer "where did this workflow actually get to?" after a crash, without changing anything.

輸入參數group_key必填

ratchet_get_usage

Check plan, credit balance, and spend

Returns the current plan, remaining included effects for the month, prepaid credit balance, and today's declared external spend against each budget ceiling. Use it to warn a user before a long run exhausts an allowance or a budget.

無需輸入參數。

ratchet_list_receipts

Get signed proof of the decisions on an effect

Returns a signed receipt for every decision made about one effect, refusals included. Each signature is over the exact bytes in `body` and verifies offline against the Ed25519 key published at /.well-known/ratchet-receipt-key — you do not have to trust this server to check them. Use this when a human asks you to PROVE an action was or was not authorised, rather than asserting it.

輸入參數effect_id必填

ratchet_reconcile_effects

Find real-world actions that bypassed the gate

Given the idempotency keys for actions a vendor says actually happened, returns which ones went through Ratchet and which it has never seen. The unseen ones are code paths that acted WITHOUT asking, so a retry there can act twice — a bug the operator almost certainly does not know about. Send references only; never send credentials.

輸入參數keys必填effect_type必填

ratchet_get_prevented_loss

What the gate has actually saved

Counts duplicate actions refused in the last 30 days and what they would have cost. Only counts refusals where a cost was declared on the effect, so it under-reports rather than flatters. IMPORTANT: pass estimated_cost_micros on ratchet_begin_effect or this reads zero — the number is only as good as what callers declare. This is money not spent at your vendors, never money paid to Ratchet.

無需輸入參數。

版本歷史

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

評分

已滿足適用檢查項的 100%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通必需25 分
  • 已宣告認證方式必需10 分
  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分