All docs
Extend

Build an integration (for coding agents)

TL;DR

To connect another system to Agent Planners, pick a credential, read GET /api/v1/capabilities, find tools with GET /api/v1/tools?q=…&schema=1 and run them with POST /api/v1/tools/{name}. A 202 means a person must approve the write; the six verify checks below prove the integration works.

Decide: MCP, an API key or an OAuth app

You are buildingUseCredential
Track 1 — an AI assistant or coding agent session that works for a person (Claude, Codex, Cursor, Grok …): not this pageThe MCP server https://www.agentplanners.com/api/mcp — see Connect Agent Planners to Claude, Codex, Grok and MuseSign in from the agent (it handles OAuth itself), or an API key in an environment variable
A script, job or backend that works in your own workspaceThe REST API https://www.agentplanners.com/api/v1An API key from API & MCP → New key
An app people sign in to, in your own workspaceThe REST APIA private OAuth app (API & MCP → Your own OAuth apps, Only this workspace) — the workspace's own app: no approval step
A product that many Agent Planners workspaces connectThe REST APIA published OAuth app (Any workspace on Agent Planners); each customer's admin approves it and your server uses that customer's token
Every option reaches the same tools, scopes, approvals, guardrails, credits and audit trail. Platform credentials (Google, Meta, store tokens) never leave Agent Planners.

The call sequence

  1. 1Authenticate. API key: send it as Authorization: Bearer. OAuth: authorization code + PKCE S256 at https://www.agentplanners.com/oauth/authorize with resource=https://www.agentplanners.com/api/v1 (a token requested without resource works only on the MCP server), then exchange the code at https://www.agentplanners.com/oauth/token with the same resource — resource on both requests. A server app authenticates there with HTTP Basic (client_id:client_secret) and does not also send client_secret in the body; a public app sends client_id only. Check state and iss (always sent) first. Read the granted scope from the token response: tools:* scopes are dropped unless an admin on a paid plan approved.
  2. 2GET /api/v1/me — check the workspace (organization.id) and, for OAuth, oauth.clientId and oauth.connectionId. Store the tokens under that connection: every consent makes a new connection, so after a customer reconnects, revoke the previous connection's refresh token.
  3. 3GET /api/v1/capabilities — read tools.enabled, tools.families, tools.writes (queued_for_approval, apply_with_guardrails, not_allowed, or unavailable when the write setting could not be read — retry), assembly (assembly.writesRun: immediately, queued_for_approval or not_allowed), tasks, limits and errors. Stop and tell the user when a family you need is missing or tools.notEnabledBecause is set.
  4. 4GET /api/v1/accounts — pick the accountId for each platform: each row has id, family (the tool family, e.g. ga4), provider and name, and accountId also accepts the platform's own account id or the exact account name. Never pick by list position; match the account the user named. A missing, ambiguous or unknown accountId answers 422 with the candidates.
  5. 5GET /api/v1/tools?q=<what you want to do>&schema=1 — choose the tool; check requiredScope and runs. GET /api/v1/tools/{name} for its full documentation.
  6. 6Read the current state with the read tool (for example google_ads__get_tracking), then POST /api/v1/tools/{name} with the arguments as the JSON body. For a write, send Idempotency-Key, and try it with dryRun:true on a test account first. 200: done (the tool's answer is result.result). 202: { queued, requestId, statusUrl } — poll GET /api/v1/requests/{id} with back-off (or wait for the write.decided webhook) until executed, failed, rejected or expired.
  7. 7No tool fits? Only with tools:raw: GET /api/v1/tools/<family>__raw_request to read the rules, then POST it with { accountId, method, host, path, query, body } (host optional; body a JSON object) — it runs through the customer's connected account and its stored platform token. Reads run at once; writes are queued for a person unless an admin pre-authorized the API key — your own app's raw writes run at once, any other app's OAuth connection always queues them.
  8. 8Afterwards: GET /api/v1/requests (what you queued), GET /api/v1/audit (your audit trail), GET /api/v1/usage (your credits), GET /api/v1/organization (plan, credits left, connected platforms).

Design for these defaults

  • Writes: your own app (an OAuth app registered in the workspace it connects to) has NO approval step — every write applies at once, raw writes and deletes included — so the approval is yours to build: show the person the change and send it after their yes. Any other app's OAuth connection (a published app in a customer's workspace) waits for an admin or editor by default (an admin may choose Apply ordinary changes at once when connecting) and always queues raw writes. An API key's ordinary writes apply at once inside the guardrails by default, unless it was created with Require approval for this key's write tools; its raw writes are queued unless an admin pre-authorized it. Except for your own app, permanent deletes and archives always wait. GET /api/v1/capabilities says which applies.
  • Raw platform API access (tools:raw) is ticked by default on the consent page and granted to a client that asks for no scope — when the approver is an admin on a paid plan. Ask only for what you use.
  • Logging: each connection's Record tool and API calls switch (an admin's, on API & MCP) is on by default — GET /api/v1/audit returns its call records (tool, account, outcome, time; never values, bodies or tokens). Off, calls are not recorded; credit usage and the connection's security events are always kept.
  • Waiting writes expire after 24 hours unanswered, and at most 50 can wait per workspace (one more answers 429 with Retry-After). Show them as pending; poll with back-off from 30 s to 5 min, list several with GET /api/v1/requests?status=pending, or use webhooks; stop at expiresAt.
  • dryRun on a credential whose writes wait is queued like any write — preview with the read tool there.
  • Idempotency-Key: the same key with the same arguments within 24 hours returns the first answer (a queued write: the same requestId; a decided one: 200 if it executed, 409 if it was rejected, expired or failed); a failed write runs again; other arguments are a new write. Raw request writes take it too. Wait for the first answer before retrying.
  • Limits: 60 requests per 60 s per credential, 120 tool calls per 60 s per workspace, 20 task starts per 10 minutes per workspace plus the plan's limit on concurrent tasks. A 429 or 503 carries Retry-After.
  • Your system never sees a platform token, and it cannot connect a platform, choose platforms, widen its scopes or approve anything: a person does that in Agent Planners (an OAuth customer by connecting again).

Minimal client: Node (fetch)

Node 18 or later, no dependencies. It runs the OAuth sign-in for a Public app registered on API & MCP → Your own OAuth apps with the redirect URI http://127.0.0.1:8787/callback, then makes two reads and one write — a dry run on one campaign — and polls the write if it waits. A private app connected to its own workspace is that workspace's own app, so the dry run answers 200 at once (no approval step). Point it at a test account, never a live campaign. With an API key instead, skip the sign-in and set the access token to the key (with an API key the dry run answers 200 unless the key requires approval). A server app adds an Authorization: Basic header to the token requests instead of client_id; a long-running backend refreshes before expires_in runs out, one refresh per connection at a time.

javascript
// node ap-client.mjs — credentials come from the environment, never from the repository
import crypto from "node:crypto";
import http from "node:http";

const ISSUER = "https://www.agentplanners.com";
const API = ISSUER + "/api/v1";
const CLIENT_ID = process.env.AGENTPLANNERS_CLIENT_ID; // apc_… of your Public app
const REDIRECT = "http://127.0.0.1:8787/callback";     // registered on the app, exactly
const b64url = (buf) => buf.toString("base64url");

// 1. PKCE + state, fresh for every sign-in
const verifier = b64url(crypto.randomBytes(32));
const challenge = b64url(crypto.createHash("sha256").update(verifier).digest());
const state = b64url(crypto.randomBytes(16));
const authorize = new URL("/oauth/authorize", ISSUER);
authorize.search = new URLSearchParams({
  response_type: "code", client_id: CLIENT_ID, redirect_uri: REDIRECT,
  code_challenge: challenge, code_challenge_method: "S256",
  scope: "accounts:read tools:read tools:write", state, resource: API,
}).toString();
console.log("Open this URL and approve:", authorize.href);

// 2. The redirect back: check state and iss before using the code
const code = await new Promise((resolve, reject) => {
  const server = http.createServer((req, res) => {
    const q = new URL(req.url, REDIRECT).searchParams;
    res.end("You can close this tab.");
    server.close();
    if (q.get("state") !== state || q.get("iss") !== ISSUER) return reject(new Error("state or iss mismatch"));
    if (q.get("error")) return reject(new Error(q.get("error")));
    resolve(q.get("code"));
  }).listen(8787, "127.0.0.1");
});

async function token(params) {
  const r = await fetch(ISSUER + "/oauth/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({ client_id: CLIENT_ID, ...params }),
  });
  const body = await r.json();
  if (!r.ok) throw new Error(r.status + " " + body.error + ": " + (body.error_description || ""));
  return body; // { access_token, token_type, expires_in, refresh_token, scope }
}
let tok = await token({ grant_type: "authorization_code", code, redirect_uri: REDIRECT, code_verifier: verifier, resource: API });
await saveRefreshToken(tok.refresh_token); // every refresh replaces it — keep only the newest

// 3. One helper: refresh once on 401, wait out 429 / 503 once, same Idempotency-Key on the retry.
//    (A long-running backend refreshes BEFORE expires_in runs out, under a per-connection lock; a 5xx on the
//    refresh does not spend the refresh token — retry the same one; invalid_grant means the person connects again.)
async function call(method, path, body, idempotencyKey, retried = false) {
  const headers = { Authorization: "Bearer " + tok.access_token };
  if (body) headers["Content-Type"] = "application/json";
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
  const r = await fetch(API + path, { method, headers, body: body ? JSON.stringify(body) : undefined });
  if (!retried && r.status === 401) {
    tok = await token({ grant_type: "refresh_token", refresh_token: tok.refresh_token, resource: API });
    await saveRefreshToken(tok.refresh_token);
    return call(method, path, body, idempotencyKey, true);
  }
  if (!retried && (r.status === 429 || r.status === 503)) {
    await new Promise((ok) => setTimeout(ok, 1000 * Number(r.headers.get("Retry-After") || 30)));
    return call(method, path, body, idempotencyKey, true);
  }
  return { status: r.status, body: await r.json() };
}

// 4. Discover, read, write (a dry run on a TEST account), poll
const caps = (await call("GET", "/capabilities")).body;
if (!caps.tools.enabled) throw new Error("Tools are off: " + caps.tools.notEnabledBecause);
const accounts = (await call("GET", "/accounts")).body.accounts;
const gads = accounts.find((a) => a.family === "google_ads"); // match the test account the user named, not the first one
const health = await call("POST", "/tools/google_ads__get_account_health", { accountId: gads.id });
console.log(health.status, health.body.result?.result); // 200 → { ok, result: { ok, tool, kind, accountId, result } }

// Read the campaign's tracking first, then change one UTM parameter as a dry run (nothing is applied).
const campaign = { accountId: gads.id, level: "campaign", ids: ["111222333"] };
console.log((await call("POST", "/tools/google_ads__get_tracking", campaign)).body.result?.result);
const write = await call("POST", "/tools/google_ads__update_tracking", {
  ...campaign,
  finalUrlSuffixSet: { utm_source: "google" },
  dryRun: true,
}, "utm-suffix-campaign-111222333-v1");
console.log("writes:", caps.tools.writes, "→", write.status); // queued_for_approval → 202; apply_with_guardrails → 200
if (write.status === 202) {
  let decision;
  let waitMs = 30_000; // back off from 30 s to 5 min; stop at the request's expiresAt
  do {
    await new Promise((ok) => setTimeout(ok, waitMs));
    waitMs = Math.min(waitMs * 2, 300_000);
    decision = (await call("GET", "/requests/" + encodeURIComponent(write.body.requestId))).body.result;
  } while ((decision.status === "pending_approval" || decision.status === "approved") && Date.now() < Date.parse(decision.expiresAt));
  console.log("decided:", decision.status); // executed | failed | rejected | expired
}

async function saveRefreshToken(rt) { /* write it to your secret store — not a file in the repository */ }

Minimal client: Python (requests)

Python 3.9 or later with requests. The same flow — two reads and a dry-run write against a test account; the person pastes the URL they were sent back to, so no local server is needed.

python
# python ap_client.py — credentials come from the environment, never from the repository
import base64, hashlib, os, secrets, time, urllib.parse
import requests

ISSUER = "https://www.agentplanners.com"
API = ISSUER + "/api/v1"
CLIENT_ID = os.environ["AGENTPLANNERS_CLIENT_ID"]   # apc_... of your Public app
REDIRECT = "http://127.0.0.1:8787/callback"          # registered on the app, exactly

def b64url(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def save_refresh_token(rt): pass  # write it to your secret store, not a file in the repository

verifier = b64url(secrets.token_bytes(32))
challenge = b64url(hashlib.sha256(verifier.encode()).digest())
state = b64url(secrets.token_bytes(16))
print("Open this URL and approve:", ISSUER + "/oauth/authorize?" + urllib.parse.urlencode({
    "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT,
    "code_challenge": challenge, "code_challenge_method": "S256",
    "scope": "accounts:read tools:read tools:write", "state": state, "resource": API}))
back = urllib.parse.parse_qs(urllib.parse.urlparse(input("Paste the URL you were sent back to: ")).query)
if back.get("state") != [state] or back.get("iss") != [ISSUER]: raise SystemExit("state or iss mismatch")
if "error" in back: raise SystemExit(back["error"][0])

def token(**params):
    r = requests.post(ISSUER + "/oauth/token", data={"client_id": CLIENT_ID, **params}, timeout=30)
    body = r.json()
    if r.status_code != 200: raise RuntimeError(f"{r.status_code} {body.get('error')}: {body.get('error_description', '')}")
    return body

tok = token(grant_type="authorization_code", code=back["code"][0], redirect_uri=REDIRECT, code_verifier=verifier, resource=API)
save_refresh_token(tok["refresh_token"])  # every refresh replaces it: keep only the newest

def call(method, path, json=None, idempotency_key=None, retried=False):
    global tok
    headers = {"Authorization": "Bearer " + tok["access_token"]}
    if idempotency_key: headers["Idempotency-Key"] = idempotency_key
    r = requests.request(method, API + path, json=json, headers=headers, timeout=60)
    if not retried and r.status_code == 401:  # a backend refreshes before expires_in runs out, one refresh per connection
        tok = token(grant_type="refresh_token", refresh_token=tok["refresh_token"], resource=API)
        save_refresh_token(tok["refresh_token"])
        return call(method, path, json, idempotency_key, True)
    if not retried and r.status_code in (429, 503):
        time.sleep(int(r.headers.get("Retry-After", "30")))
        return call(method, path, json, idempotency_key, True)
    return r.status_code, r.json()

_, caps = call("GET", "/capabilities")
if not caps["tools"]["enabled"]: raise SystemExit("Tools are off: " + caps["tools"]["notEnabledBecause"])
_, accts = call("GET", "/accounts")
gads = next(a for a in accts["accounts"] if a["family"] == "google_ads")  # match the TEST account the user named
status, health = call("POST", "/tools/google_ads__get_account_health", {"accountId": gads["id"]})
print(status, health.get("result", {}).get("result"))  # 200 → { ok, result: { ok, tool, kind, accountId, result } }

# Read the campaign's tracking first, then change one UTM parameter as a dry run (nothing is applied).
campaign = {"accountId": gads["id"], "level": "campaign", "ids": ["111222333"]}
print(call("POST", "/tools/google_ads__get_tracking", campaign)[1].get("result"))
status, write = call("POST", "/tools/google_ads__update_tracking", {
    **campaign,
    "finalUrlSuffixSet": {"utm_source": "google"},
    "dryRun": True,
}, idempotency_key="utm-suffix-campaign-111222333-v1")
print("writes:", caps["tools"]["writes"], "->", status)  # queued_for_approval -> 202; apply_with_guardrails -> 200
if status == 202:
    wait = 30  # back off from 30 s to 5 min
    while True:
        time.sleep(wait)
        wait = min(wait * 2, 300)
        _, r = call("GET", "/requests/" + urllib.parse.quote(write["requestId"]))
        if r["result"]["status"] not in ("pending_approval", "approved"): break
    print("decided:", r["result"]["status"])  # executed | failed | rejected | expired

Rules an agent must not break

  • Never store a key, token, client secret or webhook secret in the repository, a URL, a log, a test fixture or a browser bundle. Read it from the environment or a secret store (AGENTPLANNERS_TOKEN, AGENTPLANNERS_CLIENT_ID in these examples) and keep env files out of version control.
  • Never retry a write blindly. Send an Idempotency-Key (up to 128 characters) that names the change, reuse the same key on every retry of that change, wait for the first answer before retrying, and after a 500 or a timeout read GET /api/v1/requests and GET /api/v1/audit before deciding to send it again. Within 24 hours the same key and arguments return the first answer; other arguments with the same key are a new write. A 422 means change the arguments, not resend them.
  • Never test a write on a live campaign. Read first, use dryRun:true, and point the integration at a test account until a person has seen it work.
  • Never try to approve your own write. A 202 waits for a person in the workspace (API & MCP → Write approvals); no endpoint approves. Tell the user, poll GET /api/v1/requests/{id} with back-off or wait for the write.decided webhook.
  • Never send a write the person has not seen and approved in your product when the connection is your own app: it has no approval step in Agent Planners, so a write — a raw request or a delete included — applies the moment you send it.
  • Never ask the person to paste a key, a token or a client secret into a chat or a prompt — including this agent's. Read them from the environment; if one was pasted, tell the person to revoke the key (or rotate the secret) on API & MCP.
  • Keep the newest refresh token. Each refresh returns a new refresh token and spends the one you sent: store the new one before using the new access token. Presenting a spent refresh token later ends the whole connection. Refresh one connection at a time (a lock), and store tokens per connection — a reconnect is a new connection.
  • Discover, never guess: tool names from GET /api/v1/tools, account ids from GET /api/v1/accounts, request ids from your own 202 answers. A 404 means re-discover.
  • Prefer a dedicated tool. Use <family>__raw_request only when no tool does the job — never to get around a refusal or a guardrail.
  • Respect the answer: 402 and 403 are not retried (tell the user); 429 and 503 wait Retry-After; slow down when RateLimit-Remaining is low.
  • Ask only for the scopes you use (the consent page shows them to a person), and request resource=https://www.agentplanners.com/api/v1 for a REST token.

Errors to handle

StatusWhat to do
400The request or arguments are malformed: fix them (GET /api/v1/tools/{name} has the schema). Do not resend unchanged.
401Refresh the OAuth token once, then sign in again. code wrong_resource: authorize again with resource=https://www.agentplanners.com/api/v1 (a refresh cannot change it).
402The workspace is out of credits: stop and tell the user to top up. Do not retry.
403Missing scope (insufficient_scope), the platform is not exposed to this credential, or autoApprove was refused (code auto_approve_not_allowed — GET /api/v1/capabilities, tasks.autoApprove, says in advance): read GET /api/v1/capabilities and ask the user to reconnect with it. Do not retry.
404Unknown tool or request (or one this credential did not queue): re-discover.
409No account of that platform is connected or exposed to this credential: ask the user to connect or expose it. Also: a write a person already rejected, or that expired or failed, sent again with its Idempotency-Key; or a task's key reused with another goal (code idempotency_key_reused) — use a new key.
413The body is over 1 MB: send less per call.
422The tool or the platform refused: read error, change the arguments. A missing, ambiguous or unknown accountId lists the candidates as id (name) — pass one from GET /api/v1/accounts. A raw read the platform refused carries result.status and result.error.
429Rate limited, or 50 writes already wait in the workspace: wait Retry-After seconds; retry with the same Idempotency-Key. “Too many failed authentication attempts” (20 in 5 minutes from one address) is an auth failure: fix the token first.
500Unexpected error: retry a read; before resending a write, check GET /api/v1/requests and GET /api/v1/audit, then reuse the Idempotency-Key.
503Temporarily unavailable (the database, the plan or the credential's policy could not be read; nothing ran — a task start answers code write_policy_unreadable): wait Retry-After, retry the same request.

Prove it works

  1. 1GET /api/v1/me → 200 and the expected workspace.
  2. 2GET /api/v1/capabilities → tools.families contains every family the integration needs; note tools.writes (queued_for_approval or apply_with_guardrails).
  3. 3POST /api/v1/tools/google_ads__get_account_health (or another read tool you use) → 200; POST /api/v1/tools/google_ads__get_tracking reads the test campaign before the change.
  4. 4A dry-run write on a test account — google_ads__update_tracking with {"level":"campaign","ids":["111222333"],"finalUrlSuffixSet":{"utm_source":"google"},"dryRun":true}. Only when tools.writes is queued_for_approval: → 202 with a requestId that GET /api/v1/requests?status=pending lists; a person rejects it on API & MCP → Write approvals so nothing changes. With apply_with_guardrails: → 200 with the preview, nothing changes. Never a live campaign.
  5. 5GET /api/v1/audit → an event for that write (a queued one names its requestId).
  6. 6GET /api/v1/usage?days=1 → totalCredits and calls above 0.
The REST API guide has every endpoint, the full status table and webhooks; the OAuth guide has registration, scopes, lifetimes and the token errors; the OpenAPI document is https://www.agentplanners.com/api/v1/openapi.json.

Frequently asked questions

Which endpoint should an agent call first?
GET /api/v1/capabilities (after GET /api/v1/me to confirm the workspace). It says which tool families the credential may use, whether writes wait for a person, what may be assembled raw, the rate limit and how to handle each error — all as JSON.
Can an agent approve the changes it proposes?
No. A write that waits answers 202 with a requestId; a person in the workspace decides it on API & MCP → Write approvals. The agent polls GET /api/v1/requests/{id} or waits for the write.decided webhook.
MCP or REST for a coding agent?
If the agent itself should use Agent Planners while it works, connect the MCP server. If the agent is writing code for another system that will call Agent Planners, that code uses the REST API with an API key or OAuth token, as on this page.

Related