kennraDocs

GraphQL API

Kennra's API is one GraphQL endpoint. Queries follow the graph: a company, its people, their roles, deals and timeline. Mutations are semantic commands such as registerPerson or advanceDeal, never generic updates.

ResourceURL
EndpointPOST https://api.kennra.com/graphql
Schema (SDL)GET https://api.kennra.com/graphql/schema.graphql
OperationsGET https://api.kennra.com/graphql/operations
Event schemasGET https://api.kennra.com/schemas

The API has no version number. Until the API is locked, Kennra may still change it. After the lock, changes are additive only, and removed fields are first marked @deprecated with a replacement.

Persisted operations

In production, you don't send GraphQL text. You name an operation from Kennra's allowlist, by its name or its SHA-256 hash, plus variables. This keeps every query's cost, purpose and access known in advance.

Call an operation by name

Send operationName and variables, with no query and no hash. The API looks the name up among the operations with client: "api" and runs it exactly as by hash: the same allowlist, purposes, limits and audit. Names are case sensitive.

import { Kennra } from '@kennra/sdk';
 
const kennra = new Kennra(); // reads KENNRA_TOKEN
 
const person = await kennra.people.register(
  { givenName: 'Kari', familyName: 'Nordmann', title: 'CTO' },
  { idempotencyKey: 'crm-sync-4711' },
  { purpose: 'sales.b2b' },
);

Queries also run as GET /graphql?operationName=OrganizationList&variables={"first":10}, which caches can keep. An unknown name, or the name of an admin or mcp operation, returns PERSISTED_QUERY_NOT_FOUND with next. When a request has both a name and a hash, the hash wins.

Call an operation by hash

GET /graphql/operations lists the allowlist:

[
  {
    "name": "RegisterPerson",
    "client": "api",
    "area": "people",
    "purpose": "organization.management",
    "purposes": ["organization.management", "sales.b2b"],
    "sha256Hash": "<64 hex characters>"
  }
]
FieldMeaning
nameThe operation name
clientWhich set it belongs to. Use operations with client: "api". admin and mcp hold the admin UI's and the MCP server's own operations
areaThe area that groups it, such as organizations, deals or privacy. GET /graphql/areas lists the areas in order, with English and Norwegian labels and the root fields in each
purposesThe purposes the operation may run under. The first is the default
sha256HashHex SHA-256 of the operation file, byte for byte, without its # @area line. Areas never change a hash

Send the hash in extensions.persistedQuery:

POST /graphql HTTP/1.1
Host: api.kennra.com
authorization: Bearer <token>
content-type: application/json
kennra-purpose: sales.b2b
 
{
  "variables": { "input": { "givenName": "Kari", "familyName": "Nordmann", "title": "CTO" }, "idempotencyKey": "crm-sync-4711" },
  "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "<hash of RegisterPerson>" } }
}

For reference, this is the RegisterPerson operation the hash points to. The first line declares its purposes, the second its area:

# @purpose organization.management sales.b2b
# @area people
mutation RegisterPerson($input: RegisterPersonInput!, $idempotencyKey: String!, $provenance: ImportProvenanceInput) {
  registerPerson(input: $input, idempotencyKey: $idempotencyKey, provenance: $provenance) {
    __typename
    ... on RegisterPersonSuccess { partyId consistencyToken idempotentReplay }
    ... on ProposalCreated { proposalId approver command message consistencyToken }
    ... on DomainError { code message }
    ... on ValidationFailed { problems { path code message } }
    ... on IdentityConflict { identifierType candidatePartyId }
  }
}

Always take hashes from /graphql/operations. An unknown hash returns PERSISTED_QUERY_NOT_FOUND.

Ad hoc queries

Tokens with the graphql:adhoc scope may send { "query": "…" } and use introspection, for example while exploring. Ad hoc queries have a smaller budget: cost 400 and depth 6. Other tokens get PERSISTED_QUERY_ONLY.

Headers

HeaderRequiredMeaning
authorizationYesBearer <token>. See Authentication
kennra-workspaceWith sign-in tokens in several workspacesThe workspace identifier, for example fjellsport-demo
kennra-purposeNoThe purpose for this request. Must be in the operation's purposes and in your grant
kennra-consistency-tokenNoWait for your own earlier write before reading (see below)

Purpose

Without kennra-purpose, the API uses the first of the operation's purposes that you hold. Pick a purpose that matches why you read the data: the response holds only fields that purpose allows, and the audit records it.

CodeWhen
PURPOSE_LOCKEDThe purpose is not in the operation's list. extensions.allowed lists the ones that are
PURPOSE_NOT_GRANTEDYour grant doesn't hold the purpose. extensions.granted lists the ones it does
PURPOSE_REQUIREDAn ad hoc query without a purpose header

Response headers

HeaderMeaning
x-request-idThe request's ID. Quote it when you ask for help
kennra-consistency-tokenAfter a mutation: send it back to read your own write (see below)
server-timingHow long the API spent on the request, in milliseconds: auth;dur=1.2, exec;dur=8.4, total;dur=10.1

server-timing carries durations only. total is the whole request inside the API; auth is the token check and exec the validation and execution. The difference between total and the time your client measures is the network. Browsers on an allowed origin can read all three headers.

Response extensions

Every response carries extensions.kennra:

{
  "extensions": {
    "kennra": {
      "auditId": "…",
      "requestId": "…",
      "purpose": "sales.b2b",
      "withheld": [{ "path": "person.phone", "reason": "pii_level" }],
      "cost": { "requested": "…", "limit": 2000 }
    }
  }
}
  • auditId points to the audit entry for this request.
  • requestId is the request's ID, the same as the x-request-id header. Quote it when you ask for help. Every error carries it too, as extensions.requestId. If your roles let you see the request log, an error also has extensions.requestUrl, a link to the request in the admin.
  • withheld lists fields that came back null because of purpose, PII level or another rule, with a reason. See Concepts.
  • cost shows what the query cost and the limit it ran under.
  • degraded appears when a live lookup in another system timed out or failed and Kennra answered from its stored copy.

Mutations

Payload unions and typed errors

Most mutations return a union. Business outcomes are members of the union, so you handle them with __typename, not with exceptions. Every error member implements DomainError { code message }.

MemberMeaning
…Success (for example RegisterPersonSuccess)The command ran
ProposalCreatedYour agent may only suggest this write. A person approves it in the admin
ValidationFailedThe input is wrong. problems lists { path code message } per problem
IdentityConflictKennra found a likely existing record and created nothing. Use candidatePartyId
AlreadyExistsThe record exists. entityId names it
NotFoundAn id you passed doesn't exist or isn't visible to you
VersionConflictSomeone changed the record since the version you passed
InvalidStageTransition, InvalidTransitionThe move isn't allowed from the current state
DealAlreadyClosed, PartyArchived, PartyMerged, SubjectErased, MergeBlocked, HierarchyCycleThe record's state rules out the command. Restore an archived company or person before you change it
TraitValidationFailedA trait value doesn't match its definition

Some governance and app mutations, such as installApp and issueAgentToken, return a flat result instead: { ok code message problems … }.

Select __typename, ... on DomainError { code message } and ... on ValidationFailed { problems { path code message } } in every mutation you write.

Idempotency keys

Every mutation takes idempotencyKey: String!. Choose a key that is stable for the change you mean, for example crm-sync-<source id>-<source version>.

  • The same key with the same input returns the same response with idempotentReplay: true. Retrying after a timeout is safe.
  • The same key with different input returns the error IDEMPOTENCY_KEY_REUSED.

Read-your-writes

Kennra writes events first and updates its read models shortly after. A read sent right after a write, without the token, can miss that write. Every mutation returns its position twice: as consistencyToken in the success payload and as the Kennra-Consistency-Token response header. Send it as kennra-consistency-token on your next request, and the API waits until the read models have caught up, for at most 3 seconds. If they haven't, you get CONSISTENCY_TIMEOUT; retry the read.

The MCP server, the kennra CLI, @kennra/sdk and @kennra/app-sdk (InstallationClient.graphql) keep the newest token per session or client and send it on later calls for you.

const person = await kennra.people.register({ givenName: 'Kari', familyName: 'Nordmann' });
 
if (person.status === 'applied') {
  const card = await kennra.people.card(person.partyId); // sees the write above
}

Intents: one call for a whole task

A task like "register this company with its parent" or "move this deal and set its people" can take several mutations. @kennra/sdk/intents runs them as one intent, the same code the MCP write tools and the CLI run. An intent checks identity before it creates anything and returns candidates instead of a duplicate. Each step gets its own idempotency key from the intent's key, so a retry finishes a half-done intent and repeats nothing. Kennra still decides the write mode: a write that becomes a proposal returns status: "pending".

The intents are registerOrganization, registerPerson, registerProspect, updateOrganization, updatePerson, archiveParty, proposeMerge, setTraitValues, proposeTrait, proposeKind, createRecord, linkRecords, unlinkRecord, openDeal, advanceDeal, winDeal, loseDeal, updateDeal, linkDealQuote, linkDealCommerce, proposeRenewal, logInteraction and setReportingLine.

import { INTENTS, type IntentRunner, loadWorkspaceContext, runIntent } from '@kennra/sdk/intents';
 
// Runs one persisted operation by name with your token.
const runner: IntentRunner = {
  async run(name, variables, opts) {
    const res = await fetch('https://api.kennra.com/graphql', {
      method: 'POST',
      headers: {
        authorization: `Bearer ${process.env.KENNRA_TOKEN}`,
        'content-type': 'application/json',
        ...(opts?.purpose ? { 'kennra-purpose': opts.purpose } : {}),
      },
      body: JSON.stringify({ operationName: name, variables }),
    });
    const body = await res.json();
    const errors = (body.errors ?? []).map((e: { message: string; extensions?: { code?: string } }) => ({
      message: e.message,
      code: e.extensions?.code ?? null,
    }));
    const k = body.extensions?.kennra ?? {};
    return {
      data: body.data ?? null,
      errors,
      kennra: { auditId: k.auditId ?? null, purpose: k.purpose ?? null, withheld: k.withheld ?? [] },
    };
  },
};
 
const ctx = await loadWorkspaceContext(runner); // pipelines, types and your write modes
const result = await runIntent(
  INTENTS.registerOrganization,
  runner,
  ctx,
  { name: 'Fjellsport AS', orgNumber: '923609016', orgNumberCountry: 'NO' },
  { dryRun: true },
);
console.log(result.status, result.summary); // dry_run, then applied, pending, conflict or rejected

Pagination

Lists are cursor connections. Pass first (1 to 100, default 20) and after, and read pageInfo:

organizations(first: $first, after: $after) {
  nodes { id legalName }
  pageInfo { hasNextPage endCursor }
}

To get the next page, send endCursor as after while hasNextPage is true. A first outside 1–100 returns BAD_USER_INPUT. Large pages of rich operations can exceed the cost limit, so prefer smaller pages for operations like OrganizationList.

Limits

LimitValueError
Query cost, persisted operations2,000 per queryCOST_LIMIT_EXCEEDED
Query cost, ad hoc400 per queryCOST_LIMIT_EXCEEDED
Cost budget per token100,000 points per minute (default)RATE_LIMITED, with extensions.retryAfter
Depth10 (ad hoc: 6)MAX_DEPTH_EXCEEDED
Aliases20 per operationMAX_ALIASES_EXCEEDED
Query time5 seconds (mutations are not cut off)TIMEOUT
Identity lookups30 per token per minute (default)RATE_LIMITED
Request body2 MBHTTP 413, PAYLOAD_TOO_LARGE

Agents also have their own budgets, set on the agent. Crossing one pauses the agent for the rest of the period and tells its owner and the DPO.

Error codes

Authorization, limits and system errors come back as GraphQL errors with extensions.code:

CodeMeaning
UNAUTHENTICATEDMissing, expired or invalid token. See Authentication for the reasons
FORBIDDENYour grant or the policy doesn't allow this operation or record. See Denials below
PERSISTED_QUERY_NOT_FOUNDUnknown name or hash. /graphql/operations lists the operations with client: "api"
PERSISTED_QUERY_ONLYYour token can't send ad hoc queries
PURPOSE_LOCKED, PURPOSE_NOT_GRANTED, PURPOSE_REQUIREDSee Purpose above
COST_LIMIT_EXCEEDED, RATE_LIMITED, MAX_DEPTH_EXCEEDED, MAX_ALIASES_EXCEEDED, TIMEOUTSee Limits above
IDEMPOTENCY_KEY_REUSEDThe key was used before with different input. Use a new key
CONSISTENCY_TIMEOUTThe read models didn't catch up within 3 seconds. Retry the read
BAD_USER_INPUTAn argument is out of range, for example first
VALIDATION_FAILEDA variable is not a valid value of its type, for example a Date of 2027-02-30. problems names the field (input.dueAt), expected the format
INTERNALSomething failed on Kennra's side. Retry, and quote the requestId if it persists

Denials

A FORBIDDEN error says what is missing and what to do, never the policy itself:

{
  "message": "An agent can run openDeal only when it acts for a person, and this agent acts on its own.",
  "extensions": {
    "code": "FORBIDDEN",
    "reason": "agent_needs_person",
    "missing": { "actor": "a person the agent acts for" },
    "next": "Connect the agent on behalf of a person (sign in through Kennra), or ask a person to do it.",
    "docs": "https://kennra.com/docs/graphql#denials",
    "decisionId": "01jd3k9q7xw2m8c4v6t5hpa1rz"
  }
}
reasonMeaning
missing_scopemissing.scopes lists the scopes that would allow it; any one is enough
purpose_required, purpose_not_grantedThe request named no purpose, or one the token does not hold
agent_needs_personAgents change deals only when they act for a person
agent_suggest_only, agent_write_deniedThe agent's write mode for this command is suggest or deny (Settings → Agents)
user_not_allowedThe person the agent acts for may not do this themselves
needs_human_decision, needs_human_approval, people_onlyA person makes this decision or change
not_for_apps, support_read_only, outside_visibility, other_workspaceThe actor or record rules it out

Dates must exist in the calendar: Date is YYYY-MM-DD and DateTime is ISO 8601 (2027-02-28T09:30:00Z; without an offset it is read as UTC). 2027-02-30 is refused with VALIDATION_FAILED, never moved to 2 March.