salesascode

API & MCP

Your account is an MCP server. Issue a Bearer key at Settings → API Keys, point any MCP-compatible agent at /api/v1/mcp, and it can call the tools below against your account. Every tool is also a plain REST endpoint if you'd rather not speak MCP. This is a power-user path; the products themselves run on our servers and need none of it.

Authentication

Issue a key at /settings/api-keys. Keys are Bearer-style:

Authorization: Bearer sak_abc1…xyz

Two ways to call

Same tools, same keys, same scopes, same audit log: pick the transport that fits your client.

MCP (JSON-RPC)

Point an MCP client at https://salesascode.com/api/v1/mcp. It calls tools/list to introspect, then tools/call to invoke. This is what the Sales as Code plugins use.

REST

POST JSON to /api/v1/tools/<name> with a Bearer header:

curl -X POST https://salesascode.com/api/v1/tools/log_capture \
  -H 'authorization: Bearer sak_…' \
  -H 'content-type: application/json' \
  -d '{"source":"scheduled","text":"Acme champion confirmed Q3 budget"}'

Advanced: connect any MCP client

HTTP is the canonical transport. Any MCP-compatible client can connect to /api/v1/mcp over HTTP with your Bearer key: same tools, same scopes, same audit log, no server credentials required beyond the key. This is a power-user path; the products themselves run on our servers and need none of it.

Point your client at https://salesascode.com/api/v1/mcp and set the Authorization: Bearer header (or the environment variable your client reads, e.g. SALES_AS_CODE_API_KEY, with an optional SALES_AS_CODE_URL). The endpoint holds all the logic; auth, scopes, rate limits, and the audit log live on the server, exactly as with any direct HTTP client.

Per-user and per-team keys

Every key belongs to the user who issues it. A team owner can instead issue a team key (a toggle in the New key dialog): it still writes into the owner's workspace, but the control-plane tools resolve entitlements against the team's plan, the union of the owner's grants and every plugin the team's seat packs license. A per-user key is unchanged; it authorizes against that user's own plan. verify_session reports scope: "team" or "user" and, for team keys, the team id.

OAuth-provider mode (optional)

Instead of pasting a key, an MCP client can obtain access through a standard OAuth 2.0 authorization-code + PKCE flow. This is env-gated: off unless the deployment sets MCP_OAUTH_ENABLED=true; when off, the endpoints below return 404 and pasted Bearer keys are the only path.

The honest trick that keeps it small: the OAuth access token is a managed API key. The token endpoint mints a scoped api_keys row under the hood, so an OAuth-obtained token revokes, audits, and rate-limits exactly like a hand-issued key; you'll see it in Settings → API keys named OAuth (<client>).

Honest scope: PKCE (S256) is required. Registered clients only. There is no dynamic client registration and no self-serve path: a client_id we do not hold, or a redirect_uri that is not an exact match for one registered against it, is refused inline with invalid_request rather than redirected. The consent screen shows the registered name, never caller-supplied text. No refresh tokens either (the minted key doesn't expire; revoke it in Settings), and codes are single-use and expire in 10 minutes.

To connect a client, ask us to register it with its name and exact redirect URIs. Until then, use a Bearer key from Settings → API keys, which needs no registration and reaches the same tools with the same scopes.

Sign an agent in with a PromptReports ID agent token

Here: Live. Across the products: Switching on (the id-agent-tokens-everywhere line of family.json).

Agents do the work, and people stay in control. An agent that holds an agent token from PromptReports ID calls /api/v1/mcp, /api/v1/tools/<name> and /api/ingest/usage for the person it acts for, in place of a sak_ key. This site checks every call:

Authorization: DPoP eyJ…
DPoP: eyJ…

A refused token answers 401 with {"error": {"code", "message", "hint"}}, and the hint names the next step: a new token, a new DPoP proof, a scope the person grants, or a sign-in here. The codes and hints are the ones every PromptReports family product answers, so an agent reads the same next step for the same refusal wherever it is turned away. On /api/v1/mcp, a tool the scope does not allow answers JSON-RPC error -32001 with the same hint in data.hint.

The token's scopes decide what the agent may do. Each one maps to key scopes here, and an unknown scope grants nothing:

Scope in the tokenKey scopes hereTools it opens
salesascode:readaccount.read, brief.readread_account, pull_brief, gtm_score, gtm_signal_query, answer_about_account, answer_across_org, predict_deal, simulate_quarter, explain_prediction, whatif_deal, cost_per_outcome, check_deal_brief, investor_update_forecast, crm_read, published_grades, list_sessions, get_deal, get_snapshot
salesascode:writecapture.write, prospect.write, plan.write, meeting.write, usage.write, meddpicc.writelog_capture, set_meddpicc, update_prospect, add_to_plan, mark_meeting_outcome, gtm_enrich, gtm_find_people, gtm_build_tam, gtm_crm_write, gtm_run_play, propose_action, tag_deal_capability, propose_deal_terms, propose_crm_write, request_draft_send, request_sequence_enroll, request_audience_export
salesascode:account.readaccount.readread_account, gtm_score, gtm_signal_query, answer_about_account, answer_across_org, predict_deal, simulate_quarter, explain_prediction, whatif_deal, cost_per_outcome, check_deal_brief, investor_update_forecast, crm_read, published_grades, list_sessions, get_deal
salesascode:brief.readbrief.readpull_brief, get_snapshot
salesascode:capture.writecapture.writelog_capture
salesascode:prospect.writeprospect.writeupdate_prospect, gtm_enrich, gtm_find_people, gtm_build_tam, gtm_crm_write, gtm_run_play, propose_action, tag_deal_capability, propose_deal_terms, propose_crm_write, request_draft_send, request_sequence_enroll, request_audience_export
salesascode:plan.writeplan.writeadd_to_plan
salesascode:meeting.writemeeting.writemark_meeting_outcome
salesascode:usage.writeusage.writeNo tool; it opens /api/ingest/usage
salesascode:meddpicc.writemeddpicc.writeset_meddpicc
salesascode:site.writesite.writesite_action
salesascode:key.revokekey.revokerevoke_agent_key

A tool with no scope, such as verify_session, needs no scope in the token. Every call is decided once, before the tool runs (scope, then the seat, then your organization's policy), and every agent action is written to your audit log. These never act on their own for an agent:

Each of those carries an RFC 9396 authorization_details entry naming the action, so the person sees exactly what they approve. Your organization's policy can also refuse them outright.

Machine-readable spec

If you are writing a client (or you are an agent reading this), start with the spec rather than this page: https://salesascode.com/openapi.json. It is OpenAPI 3.1, generated from the same tool registry the server dispatches against, so it cannot describe an endpoint that does not exist. Every tool is one operation, with its name as the operationId, its input schema as the request body, and its required scope as x-required-scope. That is enough to generate function-calling definitions without reading any prose.

Also machine-readable: /llms.txt and /llms-full.txt for what the products are, /sitemap.xml for every indexable page.

The site as markdown

Every public page answers at its path plus .md. /docs/api and /docs/api.md are the same document, one rendered for a browser and one for a reader that would rather not parse HTML. Each page also advertises its twin in the head:

<link rel="alternate" type="text/markdown" href="/docs/api.md">

The markdown is converted from the page's own HTML, so it cannot drift from what a person sees. Prerendered pages get a real file written at build time; the server-rendered ones (the homepage, /pricing, the product landers) are converted per request and also honour Accept: text/markdown on their ordinary URL. /markdown-index.md lists the whole set.

A signed-in page has no markdown version. With SALESASCODE_AGENT_READABLE on, a caller that asks for one, at its .md address or with an Accept header that names markdown and no HTML type, gets 406 with Vary: Accept and links to the HTML page and the markdown index, instead of a redirect to /login.

The tools

For the PromptReports family hub there are two more documents, built from the same registry. /.well-known/promptreports-connector.json lists every tool with its effect (read or write), its scope, the JSON Schema of what it returns and, for a write that waits for a person, the approval key it waits on, plus the webhook events as triggers. /.well-known/promptreports-inventory.json lists every decision, action, setting and approval in the promptreports-inventory/v1 format: the tool, the operation and the event that reach it, or a link to the open task where none does yet.

51 tools. The groups below are how they are organised; the spec is the complete, current list.

Data verbs (scoped)

Thin facades over the same store the app uses, so external writes and in-app data converge on one record shape. Each needs the scope shown.

Control-plane tools

The bridge every plugin uses: verify the licensed session and gate on entitlement first, then report telemetry and brain state last. No extra scope: a valid key on its own account is enough.

Onboarding stays open; the rest need entitlement. A brand-new account with a key but no purchase can always call verify_session, check_entitlement, and pull_config; that's how a plugin connects and discovers it needs to buy. The telemetry and brain tools in this group (start_run, run_heartbeat, emit_telemetry, sync_brain) write your brain/run state, so they require an active entitlement just like the data verbs and return not_entitled otherwise.

Content-engine tools

Used by the Content Engine plugin to connect channels and drive the studio. Also no extra scope.

Deal evidence (scoped)

CRM connectors (scoped)

HubSpot, Salesforce, Attio and Salesloft, read from what the connection synced and written through the same review queue the scheduled work uses.

GTM company-OS tools (scoped)

The scoring, enrichment and list-building substrate the GTM Engine runs on, callable directly.

Reasoning tools (scoped)

The questions a table export cannot answer. Both return the facts the answer rests on and who established each one, and both return an honest "nothing recorded" rather than a guess.

Team reads (team owners)

Metadata only: run counts and outcomes, never email bodies, CRM records, or brain payloads. Both error unless the acting account owns the team.

Writes that wait for a person

Every write in the connector manifest (/.well-known/promptreports-connector.json) carries a risk tier: low, medium, high or critical. A write that changes code, access, credentials, money, members or what the public sees is in one of the PromptReports family's six critical classes and waits for a person, unless it only removes access. Here that is connect_integration (credentials) and studio_review_draft when it approves or schedules a draft (publishing). revoke_agent_key is a credentials write too, but it only removes access, so it carries hold_exempt: removes_access and runs at once.

Writes priced by their undo

Every action type at PromptCompute carries the price of undoing it: one_click, cleanup or none. A type nobody has classed counts as none, and only an org admin changes a class, at PromptCompute. When the operator turns on UNDO_PRICE_GATES (off by default), an agent's call to a write here whose type is cleanup or none answers undo_approval_required and runs nothing. It runs once it carries approval_id: an approval PromptCompute decided under the write's catalog key (never one a policy gave alone), with a signed grant for your org, whose final args carry input_sha256, the SHA-256 of the call's input without approval_id, so one approval covers one exact write, and it is spent when the write runs (a write that fails or refuses gives it back; a replay of the same idempotency key does not spend it). The refusal names the key and the hash to ask for. The request and proposal tools (request_*, propose_*) are one_click and pass, since PromptCompute gates the request itself; the writes above that always wait keep their own check; and a call with no agent behind it is not gated. The gate knows an agent by its PromptReports ID agent token or service account: a personal sak_ key pasted into an agent tool counts as your own call. Scheduled runs inside Sales as Code do not pass through these routes and are not gated here.

Telemetry lifecycle for plugin skills

What a well-behaved skill emits, in order. Everything here is optional beyond the final emit_telemetry (old skills keep working), but the more of it a skill sends, the better Activity gets (live "Running now" strip, honest durations, exact run ↔ brain correlation).

  1. Start. Call start_run (after verify_session / check_entitlement) with the plugin + skill. Keep the returned run_ref for the rest of the run. The run appears on Activity as running immediately.
  2. Heartbeat. For runs longer than a few minutes, call run_heartbeat with the run_ref, at most once every 60 seconds (cadence floor; heartbeats multiply rows of noise if spammed, and once per minute is all the staleness rule needs). A started run with no heartbeat for 30 minutes is flagged stale on the dashboard, so a crashed skill never looks "running" forever.
  3. Brain syncs. Pass the same run_ref on every sync_brain call the run makes. That upgrades the run drill-down from "syncs that landed around this run" (time-window guess) to exact attribution.
  4. Final. End with one emit_telemetry carrying the run_ref as run_id, plus counts, outcome, and the error taxonomy on failure. This settles the declared run (running → ok/error) in place, one run, one row. Omit duration_ms and it is computed from the declared start.

Report silent work too. If a scheduled run did exploratory or advisory work that never triggered a discrete skill (research, Q&A, drafting that wasn't saved), emit a session summary before it ends: emit_telemetry with skill: "session-summary" and honest counts (e.g. {"questions_answered": 4, "accounts_researched": 2}). Otherwise that work is invisible in Activity and the user can't see what their plugins actually did for them.

start_run        {"plugin":"gtm-engine","skill":"daily-signals"}      → {"run_ref":"run_kJ2…"}
run_heartbeat    {"run_ref":"run_kJ2…"}                               (every ≥60s while working)
sync_brain       {"scope":"signal-weights","payload":{…},"run_ref":"run_kJ2…"}
emit_telemetry   {"plugin":"gtm-engine","skill":"daily-signals",
                  "run_id":"run_kJ2…","outcome":"ok","counts":{"signals_sensed":12}}

Account scoping: account_ref

Both emit_telemetry and sync_brain accept an optional account_ref: a caller-supplied string label for the account a run worked or a brain snapshot is about, a domain ("acme.com") or an account name ("Acme Corp"). It is capped at 200 characters and otherwise unvalidated, an honest free-text label, not a foreign key and never synced CRM records or contact PII. It preserves the metadata-only trust posture: the same label the seller already sees, nothing more.

Where it surfaces: the per-account filter on your Activity scopes the run history + by-plugin summary to one account; the team Activity shows per-account, per-member activity and a "heads up, teammates worked the same account this week" deconfliction card. Both are metadata-only reporting over these labels; no account data is ever synced to render them.

Error envelope

Non-2xx responses carry a consistent JSON shape. It is nested: error is an object, not a string. (H106, 2026-08-25: this page showed a flat { "error": "unauthorized" } for months. That is the shape the browser-facing app routes use, and no /api/v1 response has ever looked like it.)

{
  "error": {
    "code": "invalid_key",
    "message": "Bearer token is unknown or revoked.",
    "hint": "Check the key is still listed at /settings/api-keys, then issue a new one."
  }
}

Branch on code; it is stable. message is for a person to read and may be reworded. hint says what to do about it and is present when there is a useful answer, so treat it as optional.

A request to a path under /api/ that matches no route returns this same envelope with code not_found, never an HTML page.

Status codes: 200 ok · 400 invalid input · 401 missing/revoked key · 403 key lacks the required scope or the account has no active entitlement (not_entitled, buy at /pricing) · 404 unknown tool / resource · 429 rate-limited · 500 server error. Over MCP JSON-RPC the entitlement denial is error code -32003.

Problem JSON

When the operator turns on SALESASCODE_AGENT_READABLE, every error under /api/ answers application/problem+json (RFC 9457) with type, title, status, detail, instance and code. The envelope above stays inside it, so code that reads error.code keeps working. A refused value names the field and the values it takes in field and accepted_values, and on /api/v1 it answers 422:

{
  "type": "https://salesascode.com/docs/api#error-invalid_input",
  "title": "Unprocessable Content",
  "status": 422,
  "detail": "entity must be one of: account, opp, prospect",
  "instance": "/api/v1/tools/crm_read",
  "code": "invalid_input",
  "field": "entity",
  "accepted_values": ["account", "opp", "prospect"],
  "error": { "code": "invalid_input", "message": "entity must be one of: account, opp, prospect" }
}

Two answers keep their own shape: the MCP endpoint answers JSON-RPC errors, and the OAuth token endpoint answers the RFC 6749 error object.

Every POST needs a JSON content-type

Send content-type: application/json on every POST. A POST with no content-type at all, or a form-encoded one, is rejected as a cross-site form submission before it reaches the route, and that rejection is plain text rather than the JSON envelope below. It looks like this, and it is not an auth failure however much it resembles one:

$ curl -X POST https://salesascode.com/api/v1/tools/log_capture
Cross-site POST form submissions are forbidden        # 403, text/plain

A client generated from the spec sends the header automatically, since every operation declares a JSON request body. Hand-written curl is where this bites.

Rate limits

Every key carries a per-minute limit (60 by default; a team owner can raise or clear it per key). You do not have to discover it by hitting it: every authenticated response carries the budget.

RateLimit-Limit: 60
RateLimit-Remaining: 57
RateLimit-Reset: 60
RateLimit-Policy: 60;w=60

With SALESASCODE_AGENT_READABLE on, the same answers also carry the combined field, RateLimit: limit=60, remaining=57, reset=60, on every answer from /api/v1/mcp, /api/v1/tools/<name>, /api/v1/webhooks and /api/ingest/usage, refusals included. Before a key is counted (a 401, say) they state a fresh window of the default limit. The limits do not change.

The same numbers repeat as X-RateLimit-* for clients that read the older spelling. Over the limit you get 429 with Retry-After: 60 and the code rate_limited. Pace against RateLimit-Remaining rather than retrying into the wall.

Webhooks: events pushed to your URL

The tools above are calls you make. Webhooks run the other way: we POST an event to a URL of yours when something happens in your account. Add one under Settings → API Keys → Webhooks, pick the events, and copy the signing secret. It is shown once. Rotating it replaces the old one at once.

EventFires whenFields in data
draft.readyA hosted agent writes a new draft for review.draft_id, product, skill, account_ref, created_at
reply.receivedA person replies to one of your sends. intent is one of interested, not-interested, referred, later, unclear.send_id, draft_id, account_id, intent, received_at
account.tier_changedSomeone accepts or overrides a proposed tier and the account's tier moves. A proposal on its own does not fire it.account_id, from_tier, to_tier, source, changed_at
send.approvedSomeone approves a draft and it is sent.draft_id, product, account_ref, channel, provider, approved_at
deal_terms.proposedA discount or a customer commitment is proposed on a deal, by an agent or a person, and waits for a person to approve or refuse it. kind is discount or commitment; routed is true when it waits in PromptCompute. The note and the words the customer would be told are never in it.proposal_id, deal_id (the deal as deal_ and a 26 character ULID; the CRM opportunity id is never sent), customer (only when your org granted the customer join and the seat belongs to the org the join speaks for: the company as cust:v1: and 64 hex, the same id CommitOps uses; never its domain), kind, discount_pct, payment_terms, capability, promise_by, proposed_by, routed, proposed_at
deal.stage_changedA deal leaves one stage for another, from a CRM sync or an edit here. A deal seen for the first time fires nothing. Offered once the operator turns on DEAL_STAGE_EVENTS; until then it is not in the list GET /api/v1/webhooks returns.deal_id (the deal as deal_ and a 26 character ULID; the CRM opportunity id is never sent), from_stage and to_stage (the stage names from your CRM, at most 100 characters each), direction (advanced, regressed, lateral, won or lost), changed_at

Events carry ids, short labels (the product, the skill, the account reference you gave the account), tiers, intents and timestamps. No email body, subject, recipient address or token is ever in a payload; fetch what you need with a key and the tools above. The body is one JSON object:

{"id":"evt_…","type":"draft.ready","created_at":"2026-10-13T09:00:00.000Z",
 "data":{"draft_id":"…","product":"salescron","skill":"first-touch","account_ref":"acc_…","created_at":"…"}}

Registering a webhook with a key

A system of yours can register its own receiver with one of your API keys, without a browser session. Call /api/v1/webhooks with Authorization: Bearer sak_…. The key needs the account.read scope, because every event names your accounts, deals or drafts, and your account needs a paid plan. A PromptReports ID agent token gets 403 key_required: an agent cannot add a place your events are sent to.

These are the same webhooks as the settings panel, with the same URL rules, the same limit of 10, and the same signing.

The CloudEvents form

A webhook can ask for each event as a CloudEvents 1.0 body with a Standard Webhooks signature, the form the PromptReports family contract uses. Send "envelope": "cloudevents" in the POST that creates it. The operator turns this on with WEBHOOK_FAMILY_ENVELOPE; until then the request answers 400 envelope_not_available. A webhook made without envelope gets the body shown above, and a webhook keeps the form it was made in.

{"specversion":"1.0","id":"evt_…","source":"https://salesascode.com",
 "type":"salesascode.deal.stage_changed","time":"2026-11-24T10:00:00.000Z",
 "datacontenttype":"application/json","subject":"deal_01JD8X4B2K6M8P0R2S4T6V8W0X",
 "data":{"deal_id":"deal_01JD8X4B2K6M8P0R2S4T6V8W0X","from_stage":"Discovery","to_stage":"Proposal","direction":"advanced","changed_at":"…"}}

id and data are the same as in the other form. type gains salesascode. in front, and subject is the deal id when the event names a deal. The secret is whsec_ and plain base64, which a Standard Webhooks library reads as it is. Webhook-Signature holds v1,<base64>, an HMAC-SHA256 over <Webhook-Id>.<Webhook-Timestamp>.<raw body> keyed with the bytes the secret holds after whsec_. After a space the same header also holds the v1=<hex> value described below, which a Standard Webhooks library skips.

Checking the signature

Each request carries Webhook-Id (the same on every retry of one event, so you can drop duplicates), Webhook-Timestamp (unix seconds) and Webhook-Signature: v1=<hex>, an HMAC-SHA256 with your secret over <timestamp>.<raw body>. Compute it over the raw bytes you received, compare in constant time, and refuse a timestamp more than five minutes old so a captured request cannot be replayed.

import { createHmac, timingSafeEqual } from 'node:crypto';

function verify(secret, rawBody, timestamp, signature) {
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const expected = createHmac('sha256', secret).update(timestamp + '.' + rawBody).digest('hex');
  const got = (signature || '').replace(/^v1=/, '');
  return got.length === expected.length
    && timingSafeEqual(Buffer.from(got, 'hex'), Buffer.from(expected, 'hex'));
}

Delivery, retries and switch-off

Which URLs we will send to

HTTPS only, on port 443 or 1024 to 65535, with no username or password in the URL. We refuse any address that is private, loopback, link-local, a cloud metadata address, or reserved, and we check again on every delivery at the moment we connect, so a hostname that later points somewhere private is refused rather than sent to. An account can hold 10 webhooks. Because a webhook URL often carries a token in its path, we store the path and query encrypted, and your data export lists only the scheme and host.

Versioning & deprecation

The API is versioned in the path: everything public lives under /api/v1. A change that would break a working client gets a new version prefix rather than being made in place.

Within v1 we treat these as additive and safe, so a client must tolerate them: a new tool, a new optional field in a request, a new field in a response, a new error code, a new optional header. Match on the fields you use and ignore the rest.

These are breaking, and get a new version: removing or renaming a tool, making an optional request field required, removing a response field, or changing the type of one.

When something is on the way out you will see it on the wire before it goes, not only in a changelog:

Nothing in v1 is deprecated today, so you will not see these headers yet. They are the contract for when it happens.

With SALESASCODE_AGENT_READABLE on, a route that is already retired keeps answering with Sunset, Deprecation and Link: <url>; rel="sunset", so a caller can tell a retired route from one that never existed. Outside v1, a retirement gets at least 90 days of notice. Today that is one route: POST /api/billing/upgrade-to-team, retired on 9 September 2026 when the platform moved to one price, which answers 410.

Audit & limits

Every call (MCP or REST) writes to your audit log, visible to the issuing user. Keys are rate-limited per key; a misbehaving client on one key can't 429 another. See the API Keys & MCP feature page for the issuing flow and the security model, and Concepts → the MCP contract for how the plugins use these tools.

A PromptReports workflow run sends its run id in an X-PromptReports-Run header on each call it makes (wr_ and 26 lowercase letters and digits). We keep that id on the call's audit event, so every product the run touched records the same run. A call without the header, or with a malformed id, is recorded with no run.

A write (any tool that is not a read, over MCP or REST, and the writes on /api/v1/webhooks) takes an Idempotency-Key header of 1 to 200 visible ASCII characters. Over MCP a PromptReports run can send it as _meta["promptreports/idempotency_key"] on the tools/call instead; the header wins when both are sent. Keys are kept for 24 hours under the key that called. The same key with the same tool and arguments answers the first result without running the write again. The same key with another tool or changed arguments answers 409 idempotency_conflict. A call that failed keeps nothing, so a retry runs, and so does an answer that refused before doing anything (requested: false with a refused code): once you fix the cause, the same key asks again. A resumed workflow run therefore sends a follow up or writes a CRM field once. Another caller's key with the same value is a separate entry. Sending a key is optional today; when the operator turns on SALESASCODE_IDEMPOTENCY_KEY_REQUIRED, a write with no key answers 400 idempotency_key_required and the connector manifest marks every write idempotency_key: true.