Checking registration availability…

FOR YOUR APP, AGENT OR PIPELINE

You build it.
We post it.

You already have the content and the workflow. Add social publishing to your app, agent or pipeline through one REST API or MCP connection.

Free to start · No credit card · Try a practice post first

A brilliant mind.
A terrible copy-paste arrangement.
A cheerful lime-brained AI hands a stack of posts to an exhausted human at a laptop.
Time to give the human a break.
ONE CONNECTION. EIGHT PLACES TO POST.

X / Twitter · Instagram · Facebook · LinkedIn · TikTok · YouTube · Threads · Bluesky

Your workflow already works.
Give it somewhere to post.

Connect a local MCP host or use the REST API from your backend or automation tool. Start with a simulated post before choosing a real destination.

Choosing or copying a setup does not connect your account. Verify it with a sandbox result.

Read static REST and MCP examples without JavaScript →
  1. Sign in or create a free account, then open Settings → API Keys. Use your existing credentials if you have them. A replacement secret invalidates the previous one.
  2. Keep your credentials in your private host configuration or secret store. Never paste them into chat, a URL or a shared workflow. This page does not need your secret.
  3. For this test, your API scopes need accounts:read and posts:write. The REST, n8n and Make recovery and verification steps also need posts:read. You can change scopes in Settings → API Keys; request a new token afterward.

This uses a local stdio MCP server. Node.js 18+ and npx must be available to the host process. A client that accepts only a remote URL cannot use this configuration.

Merge this table into ~/.codex/config.toml, preserving other servers. Supply both variables privately to the environment that launches Codex, then restart it. A desktop app launched from the Dock may not inherit your shell environment.

Codex configuration
[mcp_servers.socialcannon]
command = "npx"
args = ["-y", "@socialcannon/mcp@1.2.1"]
env_vars = ["SOCIALCANNON_CLIENT_ID", "SOCIALCANNON_CLIENT_SECRET"]
Select code manually
Host setup reference →

After the server starts, paste this prompt into your agent to verify access and run one practice post.

Sandbox verification prompt
Verify my SocialCannon connection using list_accounts. An empty account list is fine; it does not prevent a sandbox test.
Then create exactly one simulated post using create_post with accountId="sandbox" and content="My first SocialCannon sandbox post". Do not set scheduledAt. Do not post to real accounts.
Report success only after the tool confirms it, and show the returned post ID and status. A sandbox result is not a real social publication. If a request fails or its outcome is uncertain, stop and explain the error; do not repeatedly create new posts. Keep credentials out of this chat.
Before any later real publication or schedule, show me the destination and final content and obtain my explicit approval.
Select code manually

Ready for a real account?

Connect the destination in Accounts, then list accounts again and verify its ID. In a request, replace sandbox with that account ID. Review the final content and destination before publishing or scheduling. Creating a post without scheduledAt publishes immediately; to schedule instead, add scheduledAt as an ISO 8601 timestamp within 30 days (7 days on the Free plan).

Check platform media requirements first. If a result is uncertain, inspect its status and recovery guidance before retrying.

API reference and recovery guidance →

These examples work without JavaScript on this page. Select the code and copy it manually. Sign in or create a free account, then open Settings → API Keys and supply your credentials privately in your server or host environment.

REST sandbox example

REST sandbox example

Run with Node.js 18+ on a Linux/macOS server using local storage that supports file and directory fsync. The script checks directory-sync support before any API request or action-file creation. On unsupported storage, including typical Windows setups, use the local MCP setup below or a manual HTTP recipe for a new test; preserve any existing uncertain action and its key. It verifies account access, saves a sandbox action file before creation and checks recovery on reruns. Only a recorded known expired-token, missing-publishing-scope or rate-limit refusal allows a corrected same-key retry after any required Retry-After wait and a lookup finding no record. An uncertain outcome never does. Keep the file after an error. It needs the accounts:read, posts:write and posts:read scopes, and a writable directory for the action file: by default it is written next to the script, so that a rerun from another directory finds the same one. Set SOCIALCANNON_SANDBOX_ACTION_FILE to an absolute path to keep it somewhere else. It never publishes to a real account.

// Node.js 18+ on Linux/macOS, using local storage that supports file and
// directory fsync. Save as socialcannon-test.mjs and run on your server.
// Supply SOCIALCANNON_CLIENT_ID and SOCIALCANNON_CLIENT_SECRET privately.
// Scopes: accounts:read to list accounts, posts:write to create the sandbox
// post, and posts:read to check a recovery result. Change them in Settings ->
// API Keys, request a new token, and rerun this file.
// Reruns recover the SAME action. Keep the action file after a timeout.
// Gitignore every file this script writes, because they all carry the live
// action key: socialcannon-sandbox-action.json, its .conflict marker and any
// .tmp- file left by an interrupted run. A glob such as
// socialcannon-sandbox-action.json* covers all of them.
const { readFile, writeFile, rename, link, rm, open, realpath } = await import('node:fs/promises');
const { createHash, createHmac, randomUUID } = await import('node:crypto');
const { resolve, dirname, basename } = await import('node:path');
const { fileURLToPath } = await import('node:url');
const base = 'https://socialcannon.app';
const clientId = process.env.SOCIALCANNON_CLIENT_ID;
const clientSecret = process.env.SOCIALCANNON_CLIENT_SECRET;
if (!clientId || !clientSecret) throw new Error('Set your credentials first.');
// Anchor the default action file to this script, not to the working
// directory. A rerun from another directory then finds the same action
// instead of starting a second one and losing the first outcome.
const scriptDir = dirname(fileURLToPath(import.meta.url));
// A relative override is resolved against the script, not the working
// directory, so a rerun from elsewhere still finds the same action file.
const actionFile = process.env.SOCIALCANNON_SANDBOX_ACTION_FILE
  ? resolve(scriptDir, process.env.SOCIALCANNON_SANDBOX_ACTION_FILE)
  : resolve(scriptDir, 'socialcannon-sandbox-action.json');
const body = { accountId: 'sandbox', content: 'My first workflow sandbox post' };
// A conflict marker is kept beside the action file. The action file records
// the refusal too, but that write can fail, and a conflict must never be
// forgotten: a separate marker survives an action-file write failure, so a
// later run still refuses to accept a recovered post under a conflicting key.
const conflictFile = actionFile + '.conflict';
// The exact refusal bodies the API returns. They are the only refusals that
// may be retried under the same key, so they are named once here and matched
// by value below.
const INVALID_TOKEN_BODY = 'Invalid or expired token';
const MISSING_SCOPE_BODY = "Insufficient scopes. Missing: posts:write";
const RATE_LIMIT_BODY = 'Rate limit exceeded';
// The recovery lookup needs its own scope body, because it reads posts and
// not posts that are written.
const MISSING_READ_SCOPE_BODY = "Insufficient scopes. Missing: posts:read";
// The exact bodies the API returns for the refusals that may be retried
// under the same key. A retry permission records which of them was seen, so
// the persisted state carries the evidence for the permission rather than a
// bare status.
const CORRECTABLE_REFUSAL_BODIES = {
  401: INVALID_TOKEN_BODY,
  403: MISSING_SCOPE_BODY,
  429: RATE_LIMIT_BODY,
};
// Bind the action file to this API client without storing the client id or
// the secret. A file created under one client must not be reused under
// another, so a stored retry permission cannot cross tenants. The random
// salt is stored and the fingerprint is derived from it, so the file does
// not contain a stable pseudonym of the client.
const fingerprintFor = (salt) => createHash('sha256').update('socialcannon-action:' + salt + ':' + clientId).digest('hex').slice(0, 32);
// Authenticate a saved retry permission using the private client secret that
// is already in memory. The file stores only this MAC, never the secret. A
// matching status/body pair alone is not evidence if the file was edited.
// This is a local-state proof, not a server-signed receipt: anyone holding
// the client secret can author it. Keep credentials and action files private.
// Once consumed, this flag is kept by every later state write, including
// recovery waits and receipt settlement. It can never grant another retry.
let retryConsumed = false;
const retryProofFor = (state) => createHmac('sha256', clientSecret).update(JSON.stringify([
  'socialcannon-retry-v2', state.key, body, state.salt, state.client,
  state.retryConsumed === true,
  state.retryableStatus, state.retryableBody, state.retryNotBefore ?? null,
])).digest('hex');
// Redirects are not followed. A 307 or 308 keeps the request body, so a
// redirect to another origin would resend the client secret to it. The API
// does not redirect, so an answer that is a redirect is refused instead.
const send = (path, options = {}) => fetch(base + path, {
  ...options, redirect: 'manual', signal: AbortSignal.timeout(30000),
}).then(async (response) => {
  if (response.status >= 300 && response.status < 400) {
    throw new Error('The API answered with a redirect (' + response.status + '). Refusing to follow it, because the request body would be resent to another origin. Check the API base URL: ' + base);
  }
  return response;
});

// Parse an IMF-fixdate Retry-After value strictly. A format check alone is
// not enough: Date.parse accepts a date whose weekday contradicts its
// calendar date, so a malformed value could become a deadline in the past
// and let a retry run before the server asked. The components are therefore
// parsed and validated, including the weekday, and anything else is NaN.
const HTTP_DATE = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) ([A-Z][a-z]{2}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) GMT$/;
// HTTP requires a recipient to accept the two obsolete date forms as well as
// the IMF-fixdate, so they are parsed too: an RFC 850 date and an asctime
// date. All three carry a weekday, which must match the calendar date.
const HTTP_DATE_RFC850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), ([0-9]{2})-([A-Z][a-z]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) GMT$/;
// The asctime form pads the day to two characters with a space.
const HTTP_DATE_ASCTIME = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) ([A-Z][a-z]{2}) ([ 0-9][0-9]) ([0-9]{2}):([0-9]{2}):([0-9]{2}) ([0-9]{4})$/;
const MONTHS = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
const WEEKDAYS = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
const FULL_WEEKDAYS = { Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6, Sunday: 0 };
const parseHttpDate = (value) => {
  if (typeof value !== 'string') return NaN;
  let day, year, month, hour, minute, second, weekday = null;
  const imf = HTTP_DATE.exec(value);
  const rfc850 = imf ? null : HTTP_DATE_RFC850.exec(value);
  const asctime = imf || rfc850 ? null : HTTP_DATE_ASCTIME.exec(value);
  if (imf) {
    const parts = imf;
    weekday = parts[1]; month = MONTHS[parts[3]]; year = Number(parts[4]);
    day = Number(parts[2]); hour = Number(parts[5]); minute = Number(parts[6]); second = Number(parts[7]);
  } else if (rfc850) {
    const parts = rfc850;
    weekday = parts[1]; month = MONTHS[parts[3]]; year = Number(parts[4]);
    day = Number(parts[2]); hour = Number(parts[5]); minute = Number(parts[6]); second = Number(parts[7]);
    // RFC 9110: a year more than fifty years in the future denotes the
    // most recent past year with the same final two digits. The weekday
    // validates that result; it must not choose a different century.
    const limit = new Date();
    limit.setUTCFullYear(limit.getUTCFullYear() + 50);
    year = Math.floor(limit.getUTCFullYear() / 100) * 100 + year;
    if (Date.UTC(year, month, day, hour, minute, second) > limit.getTime()) year -= 100;
  } else if (asctime) {
    const parts = asctime;
    weekday = parts[1]; month = MONTHS[parts[2]]; year = Number(parts[7]);
    day = Number(parts[3]); hour = Number(parts[4]); minute = Number(parts[5]); second = Number(parts[6]);
  } else {
    return NaN;
  }
  if (month === undefined) return NaN;
  if (hour > 23 || minute > 59 || second > 59) return NaN;
  const stamp = Date.UTC(year, month, day, hour, minute, second);
  const parsed = new Date(stamp);
  // Reject a date the calendar does not have (such as 31 February), which
  // Date.UTC would roll over into the next month.
  if (parsed.getUTCFullYear() !== year || parsed.getUTCMonth() !== month || parsed.getUTCDate() !== day) return NaN;
  // Reject a date whose weekday contradicts its calendar date. The IMF-fixdate
  // and asctime forms carry a day-name; RFC 850 validates the year resolved
  // by the fifty-year rule, so all three are checked.
  const expectedWeekday = WEEKDAYS[weekday] ?? FULL_WEEKDAYS[weekday];
  if (expectedWeekday !== undefined && parsed.getUTCDay() !== expectedWeekday) return NaN;
  return stamp;
};

// Write the action file atomically AND durably: a crash mid-write must not
// leave invalid JSON behind, because that would strand the outcome of a post
// that may really exist, and the file must survive a power loss, because a
// lost or stale action file could publish a replacement post. The temporary
// name is unique, so two concurrent runs cannot write over each other.
//
// The content is synced before the rename, and the directory entry is synced
// after it, so the file on disk is the file that was written. Without the
// directory sync, a crash could leave the renamed file missing.
const syncPath = async (path) => {
  const handle = await open(path, 'r');
  try { await handle.sync(); } finally { await handle.close(); }
};

const writeAction = async (state) => {
  const { retryProof: _oldProof, ...stored } = state;
  if (retryConsumed) stored.retryConsumed = true;
  if (stored.retryableStatus !== undefined) stored.retryProof = retryProofFor(stored);
  const temporary = actionFile + '.tmp-' + randomUUID();
  await writeFile(temporary, JSON.stringify(stored), { mode: 0o600 });
  await syncPath(temporary);
  await rename(temporary, actionFile);
  await syncPath(dirname(actionFile));
};

// The first write claims the path exclusively, so two concurrent runs cannot
// both create an action. The content is written to a unique temporary file
// and linked into place: link() fails with EEXIST when the target already
// exists, and a concurrent reader never sees a half-written file.
const createAction = async (state) => {
  const temporary = actionFile + '.tmp-' + randomUUID();
  try {
    await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
    await syncPath(temporary);
    try {
      await link(temporary, actionFile);
    } catch (error) {
      // Some filesystems cannot make hard links. Fall back to an exclusive
      // create, which still refuses to overwrite an existing action.
      if (!['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV'].includes(error.code)) throw error;
      await writeFile(actionFile, JSON.stringify(state), { flag: 'wx', mode: 0o600 });
      await syncPath(actionFile);
    }
    // The directory entry is synced after the file is in place. If that
    // fails, the action identity is not durable, so the run stops before it
    // dispatches anything: a lost action file would let a later run create a
    // new key and publish a replacement post. Only the hard link and the
    // exclusive create decide whether this run claimed the path, so a sync
    // failure never turns a fresh action into a pre-existing one.
    await syncPath(dirname(actionFile));
  } finally {
    await rm(temporary, { force: true });
  }
};

// Serialize runs on this server with an OS-owned loopback listener. The port
// is derived from the canonical action-file path; it never receives secrets
// or serves HTTP. Exclusive bind admits one owner, and the OS releases it
// even after SIGKILL. No heartbeat, stale-file takeover or check-then-unlink
// can evict a live owner. Keep the action file on this same server for reruns;
// this is not a distributed lock for files shared between machines.
// A hash collision or an unrelated listener only blocks a run safely: it
// never permits two runs or chooses a replacement action/key.
const { createServer } = await import('node:net');
const canonicalPath = resolve(await realpath(dirname(actionFile)), basename(actionFile));
const lockPort = 49152 + createHash('sha256').update(canonicalPath).digest().readUInt16BE(0) % 16384;
let lockServer;
const acquireLock = async () => {
  for (let attempt = 0; attempt < 5; attempt++) {
    const server = createServer((socket) => socket.destroy());
    try {
      await new Promise((resolve, reject) => {
        const failed = (error) => { server.off('listening', ready); reject(error); };
        const ready = () => { server.off('error', failed); resolve(); };
        server.once('error', failed);
        server.once('listening', ready);
        server.listen({ host: '127.0.0.1', port: lockPort, exclusive: true });
      });
      server.unref();
      lockServer = server;
      return;
    } catch (error) {
      if (error.code !== 'EADDRINUSE') throw error;
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }
  throw new Error('Another run is using this action file, or its local lock port is occupied. Wait for it to finish, then rerun this SAME file.');
};
const releaseLock = async () => {
  const server = lockServer;
  lockServer = undefined;
  if (server) await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
};

// Check the storage prerequisite before any HTTP or action-file creation.
// Some filesystems (including typical Windows setups) cannot sync directory
// entries. Silently omitting that sync would weaken crash durability; writing
// the action first would strand a fresh test in recovery-only state.
try {
  await syncPath(dirname(actionFile));
} catch (error) {
  throw new Error('This REST sandbox example requires local storage with file and directory fsync (Linux/macOS server storage). Directory durability could not be confirmed (' + error.code + '). No API request or action-file creation was attempted. Keep any existing action file and its original key. Use the local MCP setup or manual HTTP recipe for a separate new sandbox test; never replace an uncertain action.');
}

const auth = await send('/api/v1/auth/token', {
  method: 'POST', headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }),
});
if (!auth.ok) {
  // The token endpoint has its own per-IP and per-client rate limit.
  const retryAfter = auth.headers.get('Retry-After');
  throw new Error('Authentication failed: ' + auth.status
    + (auth.status === 429
      ? (retryAfter
        ? ' Retry-After: ' + retryAfter + (/^[0-9]+$/.test(retryAfter) ? ' seconds.' : '.')
        : ' Respect Retry-After.')
      : '')
    + (auth.status === 401 ? ' Check SOCIALCANNON_CLIENT_ID and SOCIALCANNON_CLIENT_SECRET.' : ''));
}
const token = await auth.json().catch(() => ({}));
if (!token.success || !token.data?.access_token) throw new Error('No access token returned.');
// The token response names the scopes it was issued for. A retry after a
// missing-scope refusal is only allowed once the scope is actually there.
const grantedScopes = new Set(String(token.data.scope || '').split(' ').filter(Boolean));
const authorization = { Authorization: 'Bearer ' + token.data.access_token };
const accounts = await send('/api/v1/accounts', { headers: authorization });
const accountsBody = await accounts.json().catch(() => ({}));
if (!accounts.ok) {
  // The API names the missing scope, so show its reason instead of a generic
  // failure. The token endpoint is rate limited separately from the v1 tier.
  const reason = accountsBody?.error ? ' The API said: ' + accountsBody.error : '';
  throw new Error('Account access was not confirmed (HTTP ' + accounts.status + ').' + reason
    + (accounts.status === 403 ? ' Grant accounts:read in Settings -> API Keys and request a new token.'
      : accounts.status === 429 ? ' Respect Retry-After before trying again.'
      : ''));
}
if (!accountsBody?.success) throw new Error('Account access was not confirmed.');
// An empty account list is valid for the sandbox.

// The body asks for the sandbox sentinel. The API resolves it to this
// client's real sandbox account, which it creates lazily on the first post.
// So an empty list is the normal state before the first sandbox post, and the
// account may not be listed here yet. The recovered post must still be proved
// to belong to this client's sandbox account, so the check below compares the
// receipt's account id with the one the post itself reports, and requires
// that account to be the sandbox account of this client.
const sandboxAccountId = Array.isArray(accountsBody.data)
  ? accountsBody.data.find((account) => account && account.platform === 'sandbox')?.id
  : undefined;

let firstRun = false;
// The salt is stored with the action, so the fingerprint can be recomputed on
// a rerun without the file holding a stable pseudonym of the client.
let action = { key: 'sandbox-' + randomUUID(), body, salt: randomUUID(), client: '' };
action.client = fingerprintFor(action.salt);
// The lock is taken before the action file is read and held until the run
// finishes, so two runs cannot interleave their read-check-write-dispatch
// steps against the same file.
await acquireLock();
try {
  // A recorded conflict is checked before anything else, so a run never
  // accepts a recovered post under a key the API has already bound to
  // another request. The marker is written on its own, so it is still here
  // even when the action-file write that followed it failed.
  // Only a missing marker means no conflict. Any other read failure, such as
  // a permission or I/O error, stops the run rather than being read as an
  // absent marker, because a conflict must never be forgotten.
  let conflictMarker = '';
  try {
    conflictMarker = await readFile(conflictFile, 'utf8');
  } catch (error) {
    if (error.code !== 'ENOENT') {
      throw new Error('The conflict marker for this action file could not be read, so the action cannot continue safely. Inspect the file privately: ' + error.code + '.');
    }
  }
  if (conflictMarker) {
    let recorded = {};
    try { recorded = JSON.parse(conflictMarker); } catch { recorded = {}; }
    throw new Error('This action was refused with 409 IDEMPOTENCY_CONFLICT: that key already belongs to a different request, so this action must not be sent again and no recovered post under it can be accepted. Keep the action file, choose a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path, and start a new action there.'
      + (recorded.key ? ' The conflicting key was ' + recorded.key + '.' : ''));
  }
  // The lock is held for the whole read-check-write-dispatch sequence and
  // released in the finally block, so a failed run does not leave the next
  // run waiting on a lock nobody holds.
  // The inner try below is only the exclusive creation: it turns the
  // already-exists answer into the existing action. The outer try is the one
  // whose finally releases the lock.
  try {
  // Exclusive creation: concurrent runs cannot both create a new post.
  // Save only sandbox identity/body, a client fingerprint and retry/refusal
  // state, never credentials.
  await createAction(action);
  firstRun = true;
} catch (error) {
  if (error.code !== 'EEXIST') throw error;
  const saved = await readFile(actionFile, 'utf8');
  try { action = JSON.parse(saved); } catch {
    throw new Error('Existing action file is not valid JSON. Stop and inspect it privately.');
  }
  if (!action || typeof action !== 'object'
      || Object.keys(action).some(key => !['key', 'body', 'salt', 'client', 'refused', 'refusedKind', 'retryableStatus', 'retryableBody', 'retryProof', 'retryConsumed', 'retryNotBefore', 'lookupNotBefore'].includes(key))) {
    throw new Error('Existing action file has unexpected fields. Stop and inspect it privately.');
  }
  if (typeof action.key !== 'string' || !/^[!-~]{8,128}$/.test(action.key)
      || JSON.stringify(action.body) !== JSON.stringify(body)
      || typeof action.salt !== 'string' || !/^[!-~]{8,128}$/.test(action.salt)
      || typeof action.client !== 'string' || !/^[0-9a-f]{32}$/.test(action.client)
      || action.client !== fingerprintFor(action.salt)
      || (action.refused !== undefined && (!Number.isInteger(action.refused) || action.refused < 400 || action.refused > 499))
      || (action.refusedKind !== undefined && !['conflict', 'manual'].includes(action.refusedKind))
      || (action.retryableStatus !== undefined && ![401, 403, 429].includes(action.retryableStatus))
      || (action.retryConsumed !== undefined && action.retryConsumed !== true)
      // A 429 permission only means something together with the deadline it
      // was granted under, and a permission without a recorded refusal body
      // is not evidence that the API refused with the correctable body. The
      // two are validated together; the MAC below separately checks that
      // a saved permission was written with the private client secret.
      || (action.retryableStatus === 429 && action.retryNotBefore === undefined)
      || (action.retryableStatus !== undefined && action.retryableBody === undefined)
      || (action.retryableBody !== undefined && !Object.values(CORRECTABLE_REFUSAL_BODIES).includes(action.retryableBody))
      // The recorded body must be the one that belongs to the recorded
      // status, so a file cannot claim one refusal and carry another's body.
      || (action.retryableStatus !== undefined && CORRECTABLE_REFUSAL_BODIES[action.retryableStatus] !== action.retryableBody)
      // A conflict is always a 409, so the kind and the status travel together.
      || (action.refusedKind === 'conflict' && action.refused !== 409)
      || (action.refusedKind === undefined && action.refused !== undefined)
      || (action.lookupNotBefore !== undefined && (!Number.isFinite(action.lookupNotBefore) || action.lookupNotBefore < 0))
      || (action.retryNotBefore !== undefined && (!Number.isFinite(action.retryNotBefore) || action.retryNotBefore < 0))) {
    throw new Error('Existing action file is invalid, has a different body, or belongs to a different API client. Stop and inspect it. To start a new action, choose a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path.');
  }
  // A refusal the API documents as correctable is recorded as a retry
  // permission (retryableStatus), never as a refusal. So any refusal recorded
  // here is one that must NOT be sent again under this key: a conflict means
  // the key already belongs to another request, and a quota refusal or an
  // unknown 4xx needs a human decision.
  if (action.refused) {
    if (action.refusedKind === 'conflict') {
      throw new Error('This action was refused with 409 IDEMPOTENCY_CONFLICT: that key already belongs to a different request, so this action must not be sent again. Keep the action file, choose a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path, and start a new action there.');
    }
    throw new Error('This action was refused (' + action.refused + ') and the API does not mark that refusal as correctable, so it must not be sent again under this key. Keep the action file and inspect the cause before doing anything else.');
  }
  retryConsumed = action.retryConsumed === true;
  if (action.retryableStatus !== undefined && (retryConsumed || action.retryProof !== retryProofFor(action))) {
    // A consumed allowance, missing/edited or old proof, or rotated credentials
    // must never authorize a create. Preserve the identity and recover only,
    // so even secret rotation cannot strand an uncertain original outcome.
    const { retryProof, retryableStatus, retryableBody, retryNotBefore, ...readOnly } = action;
    action = readOnly;
    await writeAction(action);
    console.log('Saved retry permission is consumed or could not be authenticated. Recovering the original key without permission to create.');
  }
  if (action.retryNotBefore > Date.now()) throw new Error('Respect Retry-After; wait before rerunning this action file.');
  // The lookup was rate limited and asked for a wait, so the run waits for
  // that deadline before it looks at the record again.
  if (action.lookupNotBefore > Date.now()) throw new Error('The last recovery lookup was rate limited, so it asked for a wait. Wait for it to pass, then rerun this SAME file.');
  // A missing-scope refusal may only be retried with a token that now carries
  // the scope it was missing. Without proof of the correction, the retry would
  // be refused again.
  if (action.retryableStatus === 403 && !grantedScopes.has('posts:write')) {
    throw new Error('This action is waiting for the posts:write scope. Grant it in Settings -> API Keys, request a new token, then rerun this SAME file.');
  }
  // A 401 needs no separate gate. The script authenticates again at the start
  // of every run, so the token that failed once is never the token it retries
  // with. The cause, an expired token, is corrected by that fresh request.
}

// Clear the retry permission durably. A recorded correctable refusal is the
// only thing that can authorize another create, so once an outcome is
// terminal, uncertain or refused, that permission is removed and the action
// can only be recovered, never dispatched again.
//
// A failed lookup is not a create refusal, so it never records one. The
// lookup may have failed because the token lacked a scope or the rate limit
// was hit, and those are fixed by the operator. Recording them as a create
// refusal would strand the action permanently, because a recorded refusal is
// never sent again and never recovered either.
const settleWithoutRetry = async (status, reason, recordRefusal) => {
  if (action.retryableStatus === undefined && action.refused === undefined) return;
  // Without a refusal to record, the permission is kept as it is. A lookup
  // failure must not consume it, or a transient failure would strand the
  // action.
  if (!recordRefusal) return;
  await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
    ...(recordRefusal && typeof status === 'number' && status >= 400 && status <= 499
      ? { refused: status, refusedKind: 'manual' } : {}) });
};

// Record a conflict durably, in a marker of its own. The marker is written
// atomically and durably, so a crash cannot leave it half-written, and it is
// written before the action file, so it survives a failure of that write. A
// conflict must never be forgotten, because a key that the API has bound to
// another request can never be accepted as a successful recovery here.
const recordConflict = async (key) => {
  const markerTemporary = conflictFile + '.tmp-' + randomUUID();
  try {
    await writeFile(markerTemporary, JSON.stringify({ key, at: new Date().toISOString() }), { mode: 0o600 });
    await syncPath(markerTemporary);
    await rename(markerTemporary, conflictFile);
    await syncPath(dirname(conflictFile));
  } finally {
    await rm(markerTemporary, { force: true });
  }
};

async function recover(allowMissing = false) {
  const response = await send('/api/v1/posts/idempotency', {
    headers: { ...authorization, 'Idempotency-Key': action.key },
  });
  // A 404 alone is never permission to create. This exception requires a
  // recorded, correctable create refusal and reuses the exact same key/body.
  if (response.status === 404) {
    // Only the API's own confirmed no-record answer counts. A proxy 404 or a
    // misrouted deployment would otherwise look like "no record" and grant a
    // create that must not happen.
    const detail = await response.json().catch(() => ({}));
    if (detail?.success === false && detail.code === 'IDEMPOTENCY_NOT_FOUND' && allowMissing) return false;
    if (!allowMissing) {
      throw new Error('Recovery did not confirm the outcome (404). Keep the action file and rerun this same file later: the same key never publishes twice, a same-key lookup returns the original result once the post is durable. Do not create a replacement under a new key.');
    }
    throw new Error('The idempotency lookup returned an unexpected 404 ('
      + (detail?.code ? 'code ' + detail.code : 'no code')
      + '). Keep the action file and check that the API base URL is correct; do not create a replacement. Rerun this same file later: the same key never publishes twice.');
  }
  if (!response.ok) {
    // A missing scope here reads like an uncertain publish unless we name it.
    const detail = await response.json().catch(() => ({}));
    const reason = detail?.error ? ' The API said: ' + detail.error : '';
    // A failed lookup is not a create refusal. A missing posts:read scope or
    // a rate limit is fixed by the operator, so nothing is recorded and the
    // retry permission is left as it is: recording one of those as a refusal
    // would strand the action permanently, because a recorded refusal is never
    // sent again and never recovered either.
    //
    // Nothing else ends the action. A quota refusal, an unknown 4xx and a
    // server error all come from the lookup, which says nothing about how the
    // create was answered, so the permission is kept and the action stays
    // recoverable. Only a conflict and an invalid key change it, and both are
    // handled below.
    // A 429 from the lookup is fixable, but only when the server asked for a
    // wait and said so. The wait is recorded with the action, so the next run
    // waits for it before it can dispatch under the key.
    //
    // The wait is NOT a retry permission. A permission is evidence that the
    // CREATE was refused with a correctable body, and a rate-limited lookup
    // says nothing about that. Recording one here would let a lookup 429
    // authorize a create under a key that may already have been refused, so
    // only the deadline is stored, and only when the body is the exact
    // rate-limit body.
    const recoveryRetryAfter = response.status === 429 ? response.headers.get('Retry-After') : null;
    const recoveryRetryAt = recoveryRetryAfter && /^[0-9]+$/.test(recoveryRetryAfter)
      ? Date.now() + Number(recoveryRetryAfter) * 1000
      : (recoveryRetryAfter ? parseHttpDate(recoveryRetryAfter) : NaN);
    // The exact rate-limit shape, the same one the create path requires: an
    // unsuccessful answer with no code and exactly that error body. A body
    // that merely carries the same words is not the API's rate-limit answer.
    const exactRateLimit = detail?.success === false && detail?.code === undefined
      && detail?.error === RATE_LIMIT_BODY;
    const fixable = (response.status === 403 && detail?.error === MISSING_READ_SCOPE_BODY)
      || (response.status === 401 && detail?.error === INVALID_TOKEN_BODY)
      || (response.status === 429 && exactRateLimit && Number.isFinite(recoveryRetryAt))
      || response.status >= 500;
    if (response.status === 429 && exactRateLimit && Number.isFinite(recoveryRetryAt) && recoveryRetryAt > Date.now()) {
      // Only the deadline is stored, in its own field. A lookup 429 never
      // creates or changes a create permission.
      await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
        ...(action.retryableStatus !== undefined
          ? { retryableStatus: action.retryableStatus, retryableBody: action.retryableBody,
              ...(action.retryNotBefore !== undefined ? { retryNotBefore: action.retryNotBefore } : {}) }
          : {}),
        lookupNotBefore: Math.max(action.lookupNotBefore ?? 0, recoveryRetryAt) });
    }
    if (!fixable) {
      // A conflict found during recovery is recorded the same way the create
      // path records one, marker included, so it can never be forgotten and a
      // later run cannot accept a recovered post under this key.
      if (response.status === 409 && detail?.code === 'IDEMPOTENCY_CONFLICT') {
        // Both records are written, and neither write may skip the other: the
        // action file clears the retry permission, and the marker is what
        // survives an action-file write failure. So each is attempted on its
        // own, and a failure of either one stops the run, so nothing is
        // dispatched under a conflicting key.
        let recorded = false;
        try {
          await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
            refused: response.status, refusedKind: 'conflict' });
          recorded = true;
        } catch { /* The marker below is still written. */ }
        try {
          await recordConflict(action.key);
          recorded = true;
        } catch { /* The action file above is still written. */ }
        if (!recorded) {
          throw new Error('This key returned 409 IDEMPOTENCY_CONFLICT, so it must never be sent again, but neither the action file nor the conflict marker could be written. Nothing was sent. Keep the action file, delete it only after inspecting it, and start a new action with a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path.');
        }
        throw new Error('The recovery lookup found that this key already belongs to a different request (409 IDEMPOTENCY_CONFLICT). That key must not be sent again and no recovered post under it can be accepted. Keep the action file, choose a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path, and start a new action there.');
      }
      // A refusal from the lookup is not a create refusal and never becomes
      // one. It records nothing, so a valid create permission survives and
      // the action stays recoverable.
      //
      // The one exception is an invalid key. The lookup answers 400
      // INVALID_IDEMPOTENCY_KEY when the key itself is unusable, and no
      // request under that key can ever succeed, so the action ends here
      // rather than keeping a permission for a key that cannot work.
      if (response.status === 400 && detail?.code === 'INVALID_IDEMPOTENCY_KEY') {
        await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
          refused: response.status, refusedKind: 'manual' });
        throw new Error('The recovery lookup rejected this action key as invalid (' + response.status + ' INVALID_IDEMPOTENCY_KEY), so this key can never be used again. Keep the action file and choose a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path.');
      }
    }
    throw new Error('Recovery did not confirm the outcome (' + response.status + ').' + reason
      + (response.status === 403
        // The lookup needs posts:read, so a 403 here is a missing scope. It
        // says nothing about the create, so the action stays as it is and the
        // operator can grant the scope and rerun the same file.
        ? (detail?.error === MISSING_READ_SCOPE_BODY
          ? ' Recovery needs posts:read; grant it in Settings -> API Keys and request a new token, then rerun this SAME file.'
          : ' Keep the action file; inspect before taking further action.')
        : response.status === 401 ? ' The token expired; authenticate again.'
        : response.status === 429
          ? (exactRateLimit && Number.isFinite(recoveryRetryAt) && recoveryRetryAt > Date.now()
            ? ' The lookup is rate limited. The wait is recorded with this action, so rerun this SAME file after the Retry-After deadline has passed.'
            : ' The lookup is rate limited, but no wait was recorded: the deadline had already passed, or the answer was not the exact rate-limit answer. Keep this action file and rerun it later.')
        : ' Keep the action file; inspect before taking further action.'));
  }
  const result = await response.json().catch(() => ({}));
  if (!result.success || !result.data) {
    // A 200 that reports a failure is still a failure of the lookup, not of
    // the create, so it records nothing and the action stays exactly as it
    // was. The two lookup answers that do end the action are handled above,
    // where the conflict marker and the invalid key are recorded.
    throw new Error('Recovery was not confirmed. Keep the action file.');
  }
  if (result.data.outcome === 'not_published') {
    // The post settled as not published, so this key is done. The retry
    // permission is cleared before the error, so the key can never be sent
    // again even if the record is later removed and a lookup finds nothing.
    await settleWithoutRetry(result.data.status, 'the sandbox test did not publish', true);
    throw new Error('The sandbox test did not publish. Keep the action file and inspect before taking further action.');
  }
  if (result.data.outcome !== 'published' || result.data.status !== 'published' || !result.data.id) {
    // An unresolved or settling outcome is not a permission to create. The
    // retry permission is cleared, so the only way forward is another
    // recovery, never another create.
    await settleWithoutRetry(result.data.status, 'the outcome is not a confirmed publication', true);
    throw new Error('A published sandbox post is not confirmed yet. Keep the action file and check recovery later. Do not create a replacement.');
  }
  // Verify the tenant-owned post itself too. A recovery ID alone cannot prove
  // that it belongs to this sandbox body if a local refusal write failed.
  // The lookup already proved the key is published, so the action is terminal
  // from here on: the retry permission is cleared before the receipt is read,
  // so a failed receipt read cannot leave a live permission behind.
  await settleWithoutRetry(result.data.status, 'the recovery lookup proved the post is published', true);
  let receipt;
  try {
    receipt = await send('/api/v1/posts/' + encodeURIComponent(result.data.id), { headers: authorization });
  } catch (error) {
    throw new Error('The recovery read of the published post failed, so the post is not confirmed yet. The action is settled because the key is published, so it must not be created again. Keep the action file and read the post again later: ' + (error && error.message ? error.message : 'read failed') + '.');
  }
  const post = receipt.ok ? await receipt.json().catch(() => undefined) : undefined;
  if (!post?.success || post.data?.id !== result.data.id || post.data.platform !== 'sandbox'
      // The post must belong to this client's sandbox account. The account id
      // is required, because a receipt without one cannot be matched to the
      // original body. The API creates the sandbox account lazily, so it may
      // not have been listed before the create, and the listing is only used
      // to confirm the id when the listing already has one.
      || typeof post.data.accountId !== 'string' || !post.data.accountId
      || (sandboxAccountId !== undefined && post.data.accountId !== sandboxAccountId)
      || post.data.content !== body.content || post.data.status !== 'published'
      || post.data.scheduledAt || post.data.isThread
      // The original body carries no media. A recovered post that has media
      // is a different post that happens to share this content, so it must
      // never be reported as this sandbox test.
      || (post.data.mediaUrls && post.data.mediaUrls.length)
      || (post.data.mediaFilenames && post.data.mediaFilenames.length)
      || (post.data.platformOptions && Object.keys(post.data.platformOptions).length)) {
    // The receipt did not confirm this request, so the action is not
    // settled by it. The retry permission is cleared, so the key can never
    // be dispatched again on the strength of an earlier refusal.
    await settleWithoutRetry(result.data.status, 'the recovered post did not confirm the request', true);
    throw new Error('Recovered post does not confirm this sandbox request. Stop and inspect the original key.');
  }
  console.log('Simulated sandbox post recovered:', post.data.id, post.data.status);
  // The action is settled. Clear any retry permission so a later lookup that
  // cannot find the record can never authorize another create.
  await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client });
  return true;
}

// A retry is allowed only for a recorded correctable refusal, and only once
// the lookup confirms no post exists for the key.
if (firstRun || !(await recover(Boolean(action.retryableStatus)))) {
  // Fail closed if the listener was unexpectedly closed before dispatch.
  // A paused process keeps OS ownership; another run cannot take it over.
  if (!lockServer?.listening) {
    throw new Error('The action lock is no longer held. Keep this action file and rerun it.');
  }
  // Clear retry permission DURABLY before dispatch. A subsequent timeout or
  // crash must recover only; it cannot inherit permission for another create.
  // An uncertain outcome therefore only ever reaches the read-only recovery
  // path. Only a recorded known refusal grants a dispatch. Before the single
  // permitted retry, also persist that it was consumed: a second correctable
  // refusal must never mint another permission.
  if (!firstRun) retryConsumed = true;
  await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client });
  // The in-memory permission is cleared as well, so a later failure in this
  // run cannot write a terminal refusal based on a permission that was
  // already spent by this dispatch.
  action.retryableStatus = undefined;
  action.retryNotBefore = undefined;
  let confirmed = false;
  let response;
  try {
    response = await send('/api/v1/posts', {
      method: 'POST',
      headers: { ...authorization, 'Content-Type': 'application/json', 'Idempotency-Key': action.key },
      body: JSON.stringify(action.body),
    });
  } catch {
    // A lost response is not proof the server did nothing.
  }
  let result;
  try { result = response ? await response.json() : undefined; } catch { /* Preserve uncertainty. */ }
  const conflict = response?.status === 409 && result?.code === 'IDEMPOTENCY_CONFLICT';
  if (conflict || [400, 422].includes(response?.status)) {
    // A conflict means this key already belongs to another request, so it must
    // never be sent again here. A validation refusal needs a changed body,
    // which the action file forbids, so it cannot be corrected under this key
    // either. Both stop the action; only a conflict names a new file.
    if (conflict) {
      // Both records are written, and neither write may skip the other: the
      // marker is what survives an action-file write failure, and the action
      // file clears the retry permission. A failure of either one stops the
      // run, so nothing is sent again under a conflicting key.
      let recorded = false;
      try {
        await recordConflict(action.key);
        recorded = true;
      } catch { /* The action file below is still written. */ }
      try {
        await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
          refused: response.status, refusedKind: 'conflict' });
        recorded = true;
      } catch { /* The marker above is still written. */ }
      if (!recorded) {
        throw new Error('This key returned 409 IDEMPOTENCY_CONFLICT, so it must never be sent again, but neither the action file nor the conflict marker could be written. Nothing further was sent. Keep the action file, delete it only after inspecting it, and start a new action with a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path.');
      }
      throw new Error('Sandbox creation was refused (409). Keep the action file and inspect; do not recover a conflicting key or create a replacement.');
    }
    await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
      refused: response.status, refusedKind: conflict ? 'conflict' : 'manual' });
    throw new Error('Sandbox creation was refused (' + response.status + '). Keep the action file and inspect; do not recover a conflicting key or create a replacement.');
  }
  const retryAfter = response?.status === 429 ? response.headers.get('Retry-After') : null;
  // Accept only the two documented Retry-After forms: integer seconds or an
  // HTTP date. A value that Date.parse happens to accept must not become a
  // wait, because that would let a retry run earlier than the server asked.
  const retryAt = retryAfter && /^[0-9]+$/.test(retryAfter)
    ? Date.now() + Number(retryAfter) * 1000
    : parseHttpDate(retryAfter);
  // Match the API's known pre-dispatch refusals, not status alone. In
  // particular, 403 LIMIT_EXCEEDED is a quota refusal, not a scope problem.
  // The exact refusal bodies the API returns, from the same module it uses,
  // so a wording change cannot silently disable the retry permission.
  const correctable = result?.success === false && result.code === undefined && (
    (response?.status === 401 && result.error === INVALID_TOKEN_BODY)
    || (response?.status === 403 && result.error === MISSING_SCOPE_BODY)
    || (response?.status === 429 && result.error === RATE_LIMIT_BODY && Number.isFinite(retryAt))
  );
  if (correctable) {
    if (retryConsumed) {
      throw new Error('The one controlled same-key retry was refused (' + response.status + '). Its retry allowance is consumed. Keep this action file; later runs may only recover the original key. Inspect the cause without creating a replacement.');
    }
    await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
      retryableStatus: response.status,
      retryableBody: CORRECTABLE_REFUSAL_BODIES[response.status],
      // A 429 permission always records the deadline it was granted under,
      // even one that has already passed, so the persisted state is the whole
      // evidence of the refusal. A 401 or 403 has no deadline to record.
      ...(response.status === 429
        ? { retryNotBefore: Number.isFinite(retryAt) ? retryAt : Date.now() }
        : (Number.isFinite(retryAt) && retryAt > Date.now() ? { retryNotBefore: retryAt } : {})),
    });
    throw new Error('Sandbox creation was refused (' + response.status + '). Correct auth/scopes or respect Retry-After, then rerun this SAME file. It will inspect the original key before one controlled same-key retry.');
  }
  if (response && response.status >= 400 && response.status < 500 && response.status !== 409) {
    // Record the refusal so the next run names the cause instead of
    // re-sending the request. The refusals the API marks as correctable were
    // handled above and carry a retry permission instead, so everything that
    // reaches this point is a quota refusal or an unknown body. Both need a
    // human decision and must never be sent again under this key.
    await writeAction({ key: action.key, body: action.body, salt: action.salt, client: action.client,
      refused: response.status, refusedKind: 'manual' });
    throw new Error('Create response needs manual inspection (' + response.status + ') and nothing was published. Keep this action file and inspect the cause.');
  }
  // Every other 409, including unreadable/unknown JSON, remains uncertain.
  // The created post must be this sandbox post, not something else.
  if (response?.ok && result?.success && result.data?.id && result.data.status === 'published'
      && result.data.platform === 'sandbox' && result.data.content === body.content
      // The create answer is held to the same body match as a recovered
      // receipt, so a same-key replay that returns a different post is never
      // reported as this sandbox test.
      && typeof result.data.accountId === 'string' && !!result.data.accountId
      && (sandboxAccountId === undefined || result.data.accountId === sandboxAccountId)
      && !result.data.scheduledAt && !result.data.isThread
      && !(result.data.mediaUrls && result.data.mediaUrls.length)
      && !(result.data.mediaFilenames && result.data.mediaFilenames.length)
      && !(result.data.platformOptions && Object.keys(result.data.platformOptions).length)) {
    confirmed = true;
    console.log('Simulated sandbox post:', result.data.id, result.data.status);
  }
  if (!confirmed) await recover();
} // end of the dispatch block
} finally {
  // The action is settled, or the run failed. Either way the lock is released
  // so the next run is not blocked. If the process dies without unwinding,
  // the OS releases its loopback listener.
  await releaseLock();
}
// Nothing is posted to a real account. Do not delete/replace the action file
// to recover a failure. To deliberately start another sandbox action after
// settling this one, choose a NEW SOCIALCANNON_SANDBOX_ACTION_FILE path.

Access tokens expire; authenticate again when needed. Respect Retry-After on 429 responses. Inspect an uncertain result with its stored key before any retry.

Local MCP example

Local MCP example

For hosts using the common mcpServers format, merge this with existing configuration. Node.js 18+ and npx are required. Adapt the format to your host and supply SOCIALCANNON_CLIENT_ID and SOCIALCANNON_CLIENT_SECRET privately to the server process. This is local stdio, not a remote MCP URL.

{
  "mcpServers": {
    "socialcannon": {
      "command": "npx",
      "args": [
        "-y",
        "@socialcannon/mcp@1.2.1"
      ]
    }
  }
}

Verify with list_accounts; an empty account list is valid for the sandbox. Then create exactly one simulated post using create_post with accountId="sandbox" and content="My first SocialCannon sandbox post", without scheduledAt. Report setup success only after a published sandbox post ID and status are confirmed. Keep credentials out of chat. Obtain explicit approval before publishing or scheduling to a real account.

One account. Room to grow.

Start free with no card. Publishing, scheduling, analytics and other features have platform and plan limits. Choose the capacity you need as your workflow grows.