Retry Oracle MCP Server: Retry, Mutate or Abort API Calls
Pricing
from $0.50 / 1,000 retry decisions
Retry Oracle MCP Server: Retry, Mutate or Abort API Calls
Retry Oracle for AI agents and MCP clients: send a failed API call (status, raw headers, error, attempt) and get RETRY, MUTATE or ABORT with delay, retryAt and a shared circuit breaker. AI integrations, MCP server, developer tools.
Pricing
from $0.50 / 1,000 retry decisions
Rating
0.0
(0)
Developer
EchoEmpire Machine Foundry (EchoEmpire LLC)
Maintained by CommunityActor stats
0
Bookmarked
1
Total users
0
Monthly active users
a day ago
Last modified
Categories
Features
Share
Retry Oracle: RETRY, MUTATE or ABORT for failed API calls (AI integrations, MCP server, developer tools)
Send one failed API call (status code, raw response headers, error message, attempt number) and get back RETRY, MUTATE or ABORT with delaySeconds, retryAt, the rule that fired, and a shared circuit breaker state (per key, url host or known provider; unkeyed generic calls are not pooled). Deterministic rules, no LLM. Works as an AI integration for agents (LangChain, OpenAI tools), as an MCP server tool (decide_retry), and as a low-latency developer tools HTTP endpoint (Apify Standby).
Endpoint: POST https://skilled-glee--retry-oracle-agent-utility.apify.actor/decide with Authorization: Bearer <APIFY_TOKEN>. MCP: https://skilled-glee--retry-oracle-agent-utility.apify.actor/mcp.
Quick start: integration snippets
Python: tenacity retry= hook
# pip install tenacity requestsimport os, requestsfrom tenacity import retry, stop_after_attemptORACLE = os.environ.get("RETRY_ORACLE_URL", "https://skilled-glee--retry-oracle-agent-utility.apify.actor") + "/decide"AUTH = {"Authorization": f"Bearer {os.environ['APIFY_TOKEN']}"}_last = {}def oracle_retry(rs): # tenacity retry= hookif not rs.outcome.failed:return Falseexc = rs.outcome.exception()resp = getattr(exc, "response", None)body = {"attempt": rs.attempt_number, "method": "GET", "key": "api.example.com", "errorMessage": repr(exc),"statusCode": resp.status_code if resp is not None else None,"headers": dict(resp.headers) if resp is not None else {}}_last[id(rs)] = d = requests.post(ORACLE, json=body, headers=AUTH, timeout=5).json()return d["decision"] == "RETRY"def oracle_wait(rs): # tenacity wait= hook: use the oracle's delayreturn _last.pop(id(rs), {}).get("delaySeconds", 1)@retry(retry=oracle_retry, wait=oracle_wait, stop=stop_after_attempt(10), reraise=True)def get_json(url):r = requests.get(url, timeout=10)r.raise_for_status()return r.json()
JavaScript: fetch wrapper
// Node 18+ / browsers / Workers: fetch() with Retry Oracle decisionsconst ORACLE = (process.env.RETRY_ORACLE_URL ?? "https://skilled-glee--retry-oracle-agent-utility.apify.actor") + "/decide";export async function fetchWithOracle(url, init = {}, key = new URL(url).host) {for (let attempt = 1; ; attempt++) {let res, err;try { res = await fetch(url, init); if (res.ok) return res; } catch (e) { err = e; }const d = await (await fetch(ORACLE, {method: "POST",headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.APIFY_TOKEN}` },body: JSON.stringify({ attempt, key, method: init.method ?? "GET", statusCode: res?.status,headers: res ? Object.fromEntries(res.headers) : {}, errorMessage: err ? `${err.cause?.code ?? err.cause?.message ?? ""} ${err.message}` : undefined }),})).json();if (d.decision !== "RETRY") { if (res) return res; throw err; }await new Promise((r) => setTimeout(r, d.delaySeconds * 1000));}}
LangChain tool (and OpenAI function tool)
# pip install langchain-core langchain-openai requestsimport os, requestsfrom langchain_core.tools import toolORACLE = os.environ.get("RETRY_ORACLE_URL", "https://skilled-glee--retry-oracle-agent-utility.apify.actor") + "/decide"@tooldef decide_retry(attempt: int, status_code: int | None = None, error_message: str | None = None,headers: dict | None = None, method: str = "GET", key: str = "default") -> dict:"""Ask Retry Oracle whether a failed API call should RETRY, MUTATE or ABORT, and how long to wait."""body = {"attempt": attempt, "statusCode": status_code, "errorMessage": error_message,"headers": headers or {}, "method": method, "key": key}return requests.post(ORACLE, json={k: v for k, v in body.items() if v is not None},headers={"Authorization": f"Bearer {os.environ['APIFY_TOKEN']}"}, timeout=5).json()# from langchain_openai import ChatOpenAI# agent_llm = ChatOpenAI(model="gpt-4o-mini").bind_tools([decide_retry])
# pip install openai requests -- OpenAI function tool that calls Retry Oracleimport json, os, requestsORACLE = os.environ.get("RETRY_ORACLE_URL", "https://skilled-glee--retry-oracle-agent-utility.apify.actor") + "/decide"TOOL = {"type": "function", "name": "decide_retry","description": "Decide RETRY, MUTATE or ABORT for a failed API call.","parameters": {"type": "object", "properties": {"attempt": {"type": "integer"}, "statusCode": {"type": "integer"},"errorMessage": {"type": "string"}, "headers": {"type": "object"}}, "required": ["attempt"]}}def run_tool_call(call): # call = a function_call item from client.responses.create(..., tools=[TOOL])args = json.loads(call.arguments)out = requests.post(ORACLE, json=args, headers={"Authorization": f"Bearer {os.environ['APIFY_TOKEN']}"}, timeout=5).json()return {"type": "function_call_output", "call_id": call.call_id, "output": json.dumps(out)}
n8n HTTP Request node (paste into a workflow) and Make
{"name": "Retry Oracle","type": "n8n-nodes-base.httpRequest","typeVersion": 4.2,"position": [0, 0],"parameters": {"method": "POST","url": "https://skilled-glee--retry-oracle-agent-utility.apify.actor/decide","sendHeaders": true,"headerParameters": { "parameters": [ { "name": "Authorization", "value": "=Bearer {{ $env.APIFY_TOKEN }}" } ] },"sendBody": true,"specifyBody": "json","jsonBody": "={{ JSON.stringify({ attempt: $runIndex + 1, statusCode: Number($json.error?.httpCode) || null, errorMessage: $json.error?.message ?? '', key: 'api.example.com' }) }}","options": {}}}
Make: add HTTP > Make a request, URL https://skilled-glee--retry-oracle-agent-utility.apify.actor/decide, method POST, header Authorization: Bearer <APIFY_TOKEN>, body type Raw, content type JSON (application/json), request content {"attempt": 1, "statusCode": 503, "key": "api.example.com"}, and enable Parse response. Route on decision, wait delaySeconds with a Sleep module.
curl
curl -s -X POST "https://skilled-glee--retry-oracle-agent-utility.apify.actor/decide" -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \-d '{"attempt":1,"statusCode":429,"headers":{"Retry-After":"5"},"method":"GET","key":"api.example.com","explain":true}'
Request (raw-input mode)
Only two fields are required: attempt and one of statusCode / errorMessage.
| Field | Meaning |
|---|---|
attempt | 1-based number of the attempt that just failed (required) |
statusCode | HTTP status of the failure (required unless errorMessage) |
errorMessage | Raw error text, e.g. read ECONNRESET, connect ETIMEDOUT, getaddrinfo ENOTFOUND (required unless statusCode) |
headers | Raw response headers. Parsed: Retry-After (seconds or HTTP date), X-RateLimit-Remaining/Reset (epoch or delta), RateLimit-* and RateLimit (IETF draft), OpenAI x-ratelimit-*-requests/tokens, Anthropic anthropic-ratelimit-*, Stripe Stripe-Should-Retry / Stripe-Rate-Limited-Reason, Shopify X-Shopify-Shop-Api-Call-Limit |
method | HTTP method. GET, HEAD, OPTIONS, PUT, DELETE are idempotent; POST/PATCH need idempotencyKey (or an Idempotency-Key header) to replay indeterminate failures |
provider | openai, anthropic, stripe, github, shopify, apify or generic. Auto-detected from url host or headers |
url, key | Circuit-breaker key. Default: provider:host from url, else the detected provider; a generic call with neither is not pooled (circuit.state: "untracked") |
preset | conservative (default), aggressive, paid-api, idempotent-by-method |
policy | Optional overrides: maxAttempts, baseDelay, maxDelay, maxWait, breakerThreshold, breakerWindow, breakerCooldown, assumeIdempotent |
sessionId, spent, nextAttemptCost, sessionBudget | Session spend guard, tracked server-side by sessionId |
responseBody | Optional provider error body (OpenAI/Anthropic/Stripe error object, Shopify GraphQL errors + extensions.cost) |
deadlineSeconds, elapsedSeconds | Optional deadline |
explain | Include the rule trace |
dryRun | Evaluate without updating circuit/session state (includes the trace) |
Response fields: decision, ruleId, reasonCode, reason, delaySeconds, retryAt, selectedMutation, remainingAttemptBudget, remainingSpendBudget, provider, classification (category, waitSeconds, waitSource, idempotent and why), circuit (key, state closed/open/half_open, failuresInWindow, retryAt), session, inputHash, billing, serverMs, and explain when asked.
Rule table (evaluated top to bottom; first match wins)
| Rule | Code | Decision | When |
|---|---|---|---|
| R00 | INVALID_INPUT | - | Input fails validation (needs attempt plus statusCode or errorMessage). HTTP 400, not charged. |
| R01 | ALREADY_SUCCEEDED | ABORT | 2xx status (and no Shopify GraphQL THROTTLED error): nothing to retry. Closes the circuit for the key. |
| R02 | CIRCUIT_OPEN | ABORT | Shared circuit for this key is open: returns circuit.state=open and retryAt. |
| R03 | ATTEMPTS_EXHAUSTED | ABORT | attempt >= maxAttempts (preset or override). |
| R04 | DEADLINE_EXHAUSTED | ABORT | elapsedSeconds >= deadlineSeconds (only when a deadline is given). |
| R05 | SPEND_EXHAUSTED | ABORT | Session amountSpent (server-side by sessionId) or amountSpent + nextAttemptCost exceeds the budget. |
| R06 | PROVIDER_SAYS_NO_RETRY | ABORT | Provider explicitly forbids retry (Stripe-Should-Retry: false). |
| R07 | QUOTA_EXHAUSTED | ABORT | Quota / billing / spend-cap failure that waiting will not fix (OpenAI quota codes, Anthropic 402 or repeated 429 without retry-after, Shopify 402/423). Opens the circuit for 15 minutes. |
| R08 | ALLOWED_MUTATION | MUTATE | 401 -> refresh-auth, 413 -> reduce-payload, 409 -> refresh-resource, 404 -> change-endpoint, when that mutation is allowed (else MUTATION_NOT_ALLOWED -> ABORT). |
| R09 | HARD_FAILURE | ABORT | Other 4xx (not 408/425/429), 501/505, DNS-not-found, TLS/certificate errors, caller-aborted requests, provider hard errors. |
| R10 | UNSAFE_REPLAY | ABORT | Outcome is indeterminate (5xx other than 503/529, timeout, connection reset) and the request is not idempotent (method, idempotent flag or idempotencyKey). Reconcile first. |
| R11 | UNKNOWN_FAILURE | ABORT | No rule can classify the failure. |
| R12 | WAIT_TOO_LONG | ABORT | Required wait exceeds the preset maxWait or the remaining deadline; retryAt says when a retry could work. |
| R13 | RATE_LIMITED | RETRY | Rate limit with a known wait: delay = max(backoff, Retry-After / reset headers). |
| R14 | TRANSIENT_FAILURE | RETRY | Transient 408/425/429/5xx or network error: capped exponential backoff, base * 2^(attempt-1). |
Presets
| Preset | maxAttempts | baseDelay | maxDelay | maxWait | Assume idempotent when method unknown | Circuit |
|---|---|---|---|---|---|---|
conservative | 3 | 1.0 s | 30.0 s | 60.0 s | no | 3 in 60 s, open 60 s |
aggressive | 6 | 0.25 s | 20.0 s | 120.0 s | yes | 8 in 30 s, open 15 s |
paid-api | 2 | 2.0 s | 60.0 s | 300.0 s | no | 3 in 120 s, open 120 s |
idempotent-by-method | 4 | 0.5 s | 30.0 s | 120.0 s | no | 5 in 60 s, open 30 s |
Backoff is min(maxDelay, baseDelay * 2^(attempt-1)), floored by the provider wait from headers. 429/503/529, ECONNREFUSED and DNS-temporary errors mean the request was not processed, so they are safe to replay even for POST. 500/502/504, timeouts and connection resets are indeterminate and need an idempotent request.
Provider profiles (documented behavior only)
| Provider | What Retry Oracle uses | Source |
|---|---|---|
| OpenAI | 429 billing/quota codes (insufficient_quota, credit_balance_exhausted, organization_spend_limit_exceeded, project_spend_limit_exceeded, organization_usage_limit_exceeded) → ABORT; 429 rate limit / slow_down and 503 server_is_overloaded → wait for Retry-After; x-ratelimit-remaining/reset-requests/tokens (durations like 6m0s) | platform.openai.com/docs/guides/error-codes, /docs/guides/rate-limits |
| Anthropic | 429 rate_limit_error honors retry-after and anthropic-ratelimit-*-reset (RFC 3339); the spend-cap 429 has no retry-after and keeps failing, so a repeat 429 without it → ABORT; 402 billing_error → ABORT; 529 overloaded_error, 500, 504 → retry | docs.anthropic.com/en/api/errors, /en/api/rate-limits |
| Stripe | Stripe-Should-Retry: false → ABORT; 429 with Stripe-Rate-Limited-Reason = rate limit, without it = lock timeout (not processed) → retry with backoff; 402 → ABORT; 409 idempotency in progress → retry with the same key; 500 on POST is indeterminate → only with the same idempotency key | docs.stripe.com/rate-limits, /error-low-level |
| GitHub | 403/429 with x-ratelimit-remaining: 0 → wait until x-ratelimit-reset (UTC epoch seconds); retry-after honored; secondary limit without headers → wait at least 60 s then back off | docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api |
| Shopify | REST 429 + Retry-After (e.g. 2.0), X-Shopify-Shop-Api-Call-Limit: 40/40; GraphQL 200 + THROTTLED → wait (requestedQueryCost - currentlyAvailable) / restoreRate; 402 frozen, 423 locked → ABORT; 430 → ABORT | shopify.dev/docs/api/usage/limits, /admin-rest/usage/rate-limits, /usage/response-codes |
| Apify | 429 rate-limit-exceeded → exponential backoff (doubling) | docs.apify.com/api/v2 (Rate limiting) |
Shared circuit breaker and session spend guard
State lives in a named key-value store in your own Apify account (retry-oracle-state), so every agent and run using your token shares it. A key opens after the preset's failure threshold inside its window, when a provider reports the key exhausted until a reset time, or for 15 minutes after a quota/billing failure. While open, decisions return circuit.state: "open" and retryAt. POST /report {"key": "...", "outcome": "success"} closes it (free). Sessions keep amountSpent by sessionId; add spend with spent on /decide or /report, and set sessionBudget once.
State is cached in memory and written back every 2 seconds; parallel Standby runs can see up to about 7 seconds of staleness (last writer wins per record).
Other endpoints (free)
GET /rules (this table as JSON), GET /circuit/{key}, POST /report, GET /session/{id}, DELETE /session/{id}, POST /mcp (MCP tools decide_retry, get_circuit).
Batch mode and failure-log audit
Run the Actor normally with items (1-1000 failures, raw or legacy retry-oracle fields) to get one dataset row per decision. With mode: "audit" and a datasetId (or inline log of attempt records: requestId, attempt, statusCode, headers, errorMessage, method, timestamp, cost), Retry Oracle replays every attempt through the rules and reports wasted retries (attempts after the rules said ABORT, and retries fired before the provider's reset), wasted spend, a per-preset comparison and a suggested policy.
Billing
One decision-produced event per decision (each /decide result, each MCP decide_retry result, each batch item, each audited log entry). Invalid or failed requests return HTTP 400 and are not charged. Circuit, session, rules and report endpoints are free. Check the Pricing tab for the current price.
Limits
No operation is executed and no payload is needed. Do not send secrets in headers (strip Authorization and cookies). Body limit 256 KB per request; batch up to 1000 items; audit up to 10,000 entries.