Retry Oracle MCP Server: Retry, Mutate or Abort API Calls avatar

Retry Oracle MCP Server: Retry, Mutate or Abort API Calls

Pricing

from $0.50 / 1,000 retry decisions

Go to Apify Store
Retry Oracle MCP Server: Retry, Mutate or Abort API Calls

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

Actor stats

0

Bookmarked

1

Total users

0

Monthly active users

a day ago

Last modified

Categories

Features

Limited permissionsSingle-tenantServer interface

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 requests
import os, requests
from tenacity import retry, stop_after_attempt
ORACLE = 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= hook
if not rs.outcome.failed:
return False
exc = 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 delay
return _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 decisions
const 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 requests
import os, requests
from langchain_core.tools import tool
ORACLE = os.environ.get("RETRY_ORACLE_URL", "https://skilled-glee--retry-oracle-agent-utility.apify.actor") + "/decide"
@tool
def 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 Oracle
import json, os, requests
ORACLE = 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.

FieldMeaning
attempt1-based number of the attempt that just failed (required)
statusCodeHTTP status of the failure (required unless errorMessage)
errorMessageRaw error text, e.g. read ECONNRESET, connect ETIMEDOUT, getaddrinfo ENOTFOUND (required unless statusCode)
headersRaw 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
methodHTTP method. GET, HEAD, OPTIONS, PUT, DELETE are idempotent; POST/PATCH need idempotencyKey (or an Idempotency-Key header) to replay indeterminate failures
provideropenai, anthropic, stripe, github, shopify, apify or generic. Auto-detected from url host or headers
url, keyCircuit-breaker key. Default: provider:host from url, else the detected provider; a generic call with neither is not pooled (circuit.state: "untracked")
presetconservative (default), aggressive, paid-api, idempotent-by-method
policyOptional overrides: maxAttempts, baseDelay, maxDelay, maxWait, breakerThreshold, breakerWindow, breakerCooldown, assumeIdempotent
sessionId, spent, nextAttemptCost, sessionBudgetSession spend guard, tracked server-side by sessionId
responseBodyOptional provider error body (OpenAI/Anthropic/Stripe error object, Shopify GraphQL errors + extensions.cost)
deadlineSeconds, elapsedSecondsOptional deadline
explainInclude the rule trace
dryRunEvaluate 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)

RuleCodeDecisionWhen
R00INVALID_INPUT-Input fails validation (needs attempt plus statusCode or errorMessage). HTTP 400, not charged.
R01ALREADY_SUCCEEDEDABORT2xx status (and no Shopify GraphQL THROTTLED error): nothing to retry. Closes the circuit for the key.
R02CIRCUIT_OPENABORTShared circuit for this key is open: returns circuit.state=open and retryAt.
R03ATTEMPTS_EXHAUSTEDABORTattempt >= maxAttempts (preset or override).
R04DEADLINE_EXHAUSTEDABORTelapsedSeconds >= deadlineSeconds (only when a deadline is given).
R05SPEND_EXHAUSTEDABORTSession amountSpent (server-side by sessionId) or amountSpent + nextAttemptCost exceeds the budget.
R06PROVIDER_SAYS_NO_RETRYABORTProvider explicitly forbids retry (Stripe-Should-Retry: false).
R07QUOTA_EXHAUSTEDABORTQuota / 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.
R08ALLOWED_MUTATIONMUTATE401 -> refresh-auth, 413 -> reduce-payload, 409 -> refresh-resource, 404 -> change-endpoint, when that mutation is allowed (else MUTATION_NOT_ALLOWED -> ABORT).
R09HARD_FAILUREABORTOther 4xx (not 408/425/429), 501/505, DNS-not-found, TLS/certificate errors, caller-aborted requests, provider hard errors.
R10UNSAFE_REPLAYABORTOutcome is indeterminate (5xx other than 503/529, timeout, connection reset) and the request is not idempotent (method, idempotent flag or idempotencyKey). Reconcile first.
R11UNKNOWN_FAILUREABORTNo rule can classify the failure.
R12WAIT_TOO_LONGABORTRequired wait exceeds the preset maxWait or the remaining deadline; retryAt says when a retry could work.
R13RATE_LIMITEDRETRYRate limit with a known wait: delay = max(backoff, Retry-After / reset headers).
R14TRANSIENT_FAILURERETRYTransient 408/425/429/5xx or network error: capped exponential backoff, base * 2^(attempt-1).

Presets

PresetmaxAttemptsbaseDelaymaxDelaymaxWaitAssume idempotent when method unknownCircuit
conservative31.0 s30.0 s60.0 sno3 in 60 s, open 60 s
aggressive60.25 s20.0 s120.0 syes8 in 30 s, open 15 s
paid-api22.0 s60.0 s300.0 sno3 in 120 s, open 120 s
idempotent-by-method40.5 s30.0 s120.0 sno5 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)

ProviderWhat Retry Oracle usesSource
OpenAI429 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
Anthropic429 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 → retrydocs.anthropic.com/en/api/errors, /en/api/rate-limits
StripeStripe-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 keydocs.stripe.com/rate-limits, /error-low-level
GitHub403/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 offdocs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
ShopifyREST 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 → ABORTshopify.dev/docs/api/usage/limits, /admin-rest/usage/rate-limits, /usage/response-codes
Apify429 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.