Kenso MCP tools

Campaign Ops campaign_ops

restart re-runs a campaign's processing from the beginning (after a config change or a stall); reset_processing_status only clears a stuck flag. status is lifetime totals, no date window. campaign_linkedin_url_mismatches lists leads whose LinkedIn URL does not match their name. Stopping a campaign's processing or AI is campaigns pause, not an operation here, and it needs no status read first.

Call it from an MCP client connected to https://mcp.ken.so/mcp: reads go through campaign_ops_read and changes through campaign_ops_write. Each takes operation plus that operation's parameters, and your workspace role decides which operations you see.

Each operation with a route calls the Kenso API at https://api.ken.so with Authorization: Bearer <Kenso API key>, Ken-Version: 1.1 and X-Ken-Workspace-Id: <workspace id>. You can call that route directly with the same headers.

Operations: campaign-batches-get, get-account-play-protection, campaign-batches-list, triggers-list-linkedin-engagements, restart, campaign-batches-restore-sample, campaign-batches-skip-sample, unarchive, campaign-batches-update-sample, campaign_linkedin_url_mismatches, pipeline, reset_processing_status, reset_status, status

campaign-batches-get

Read. GET https://api.ken.so/v1/campaign-batches/{campaignBatchId}

Path: campaignBatchId

Get one campaign batch with Ken's samples: the emails Ken picked to review first. Free: no AI and no credits.

GET /api/v1/campaign-batches/{campaignBatchId}. Internal, behind the
campaign_batches flag. Sends Ken-Version 1.1, X-Ken-Workspace-Id and X-Ken-Actor:
agent. Read only. Needs campaigns view. A missing or other-workspace id is
404 not_found.
Returns the batch (see campaign-batches-list) plus samples and moreCount. samples
has up to sampleCount leads (5, 10 or every lead, the step's samples setting), one
per segment and A/B variant before a second from any. Each: contactId, name,
title, company, segment (id, name; omitted for the default segment), variant
(omitted when the step has one version), email (to, subject, body as plain text:
step 1 of the lead's sequence filled for that lead), note (why Ken picked it and
what it wrote the opening line from), skipped (true when a person skipped the lead:
it stays in the list but not in count, and skippedCount counts them) and updatedAt
(send it back to campaign-batches-update-sample). moreCount is count minus the samples
that are not skipped.
A lead routed to another language shows step 1 as dispatch sends it, the approved
localization: its email then also carries language (fr-FR), mirrorSubject and
mirrorBody (the English mirror, filled with the same variables), qaScore (0-100)
and editedByHuman (true when a person edited the localization after Ken wrote
it, so the mirror may not match it). An email in the source text has none of them,
except editedByHuman, which is also set when the email was edited in this batch
(campaign-batches-update-sample): true when a person wrote it, false when an agent or an
API key did. The email then shows that text.
email.editableBody is the body as text to edit, each link, image and video a numbered
marker ([link 1: text], [booking link 2: text], [asset link 3: text], [unsubscribe link 4],
[image 5], [video 6]); send it to campaign-batches-update-sample with
email.editableBodyVersion. A Studio email has none.

get-account-play-protection

Read. Early access: needs accounts on for the workspace. GET https://api.ken.so/v1/campaigns/{campaignId}/account-play-protection

Path: campaignId

Report how account-play protection affects a campaign. Mode, people skipped now, people stopped, and the accounts behind them.

GET /api/v1/campaigns/{campaignId}/account-play-protection. Staff. Sends
Ken-Version 1.1. client_id is sent as X-Ken-Workspace-Id. Needs the accounts
feature for the workspace (404 when it is off). A cross-workspace id is not_found.

People in an active account play (an account in stage warming, engaged,
meeting_booked or in_deal, matched by email domain, company domain, or a stakeholder's
email or LinkedIn profile) are skipped by campaigns that protect account plays.

Returns data {protectAccountPlays, mode, skippedCount, stoppedCount, isPartial,
accounts[{accountId, name, stage, contactCount}]}. mode is enforced (people not
contacted yet are held; people who got a step are stopped at their next send),
shadow (counted only, sending unchanged) or off (protectAccountPlays is false or
account plays are not on for the workspace). skippedCount counts live contacts
not stopped yet that match now (0 when off). stoppedCount counts contacts whose
sequence in this campaign was stopped for an account play, in any mode. isPartial
is true when the campaign has more than 100,000 unstopped contacts: the skip
counts cover the first 100,000. Turn protection on or off with
campaigns(operation="update", protect_account_plays=...).

campaign-batches-list

Read. GET https://api.ken.so/v1/campaign-batches

Query: campaignId integer, cursor string, limit integer, status string

List campaign batches waiting for approval (default) or of any status, newest first. Each batch is the first emails of one campaign held until a person approves them.

GET /api/v1/campaign-batches. Internal, behind the campaign_batches flag. Sends
Ken-Version 1.1, X-Ken-Workspace-Id and X-Ken-Actor: agent. Read only. Needs
campaigns view.
status (comma = OR): pending (waiting for a decision; it takes new leads until it
reaches batchSize or is approved), rewriting (sent back to Ken; still held),
approved. Default pending,rewriting. campaign_id keeps one campaign's batches.
limit 1 to 200 (default 50); pass pagination.nextCursor back unchanged as cursor.
Each batch: id, campaignId, campaignName, number (1, 2, 3 per campaign), status,
count (leads in it), batchSize (25, 50 or 100), segmentCount, sampleCount,
senders (inboxCount, linkedInAccountCount), round, clientApproval, waitingOn
(team or client), approval (canDecide, note), workflowId, decidedAt, decidedBy
(kind user or client, userId, name), sentBackAt, sentBackBy, sentBackNote (the last
send back to Ken, and what it asked to change), createdAt, updatedAt.
approval.canDecide says whether the caller may approve the batch (campaigns edit plus
approve, and a batch the team decides), with a note when not.

triggers-list-linkedin-engagements

Read. GET https://api.ken.so/v1/triggers/{triggerId}/linkedin-engagements

Path: triggerId

Query: cursor string, limit integer, status string

List the LinkedIn engagements a LinkedIn signal trigger stored, newest first. Public. status is new, imported, offered, or skipped.

GET /api/v1/triggers/{triggerId}/linkedin-engagements. Sends Ken-Version 1.1 and
X-Ken-Workspace-Id. Requires Campaigns view. 404 while the workspace's linkedin_signals flag is off.
Each item: id, kind (post_reaction, post_comment, post_reply, post_author, profile_view), postUrl, actor {name,
headline, profileUrl}, commentText, reactionType, commentId, parentCommentId (set on a reply),
postText, intent, intentReason (Ken's label of a comment or reply), ownPost (false for a pasted
third-party post and for a topic's or watched profile's post), sourceKind (seat, page, post, topic or
person; absent on a profile view), topic (the keyword of a topic source, the watched person's name of a
person source; absent otherwise), occurredAt, firstSeenAt, status (offered: a workflow run took it; no
contact), skipReason (own_seat, kind_filtered, reaction_type_filtered, keyword_mismatch, intent_filtered,
headline_filtered, not_imported: the import created no contact, e.g. do not contact), contactId.
A trigger of another signal type returns an empty list.

restart

Write. POST https://api.ken.so/v1/campaigns/{campaignId}/restart

Path: campaignId

Restart a campaign's processing from the beginning. Recovers a stalled or errored campaign, or reprocesses after a config change.

POST /api/v1/campaigns/{campaignId}/restart. Public. Sends Ken-Version 1.1. No body.

Re-runs the processing pipeline from the beginning, to recover a campaign that
stalled or errored, or to reprocess after a configuration change. On a draft
campaign it starts processing behind the same readiness checks as
campaigns(operation="resume"), and a draft trigger campaign is 400
validation_failed (start it with resume). An archived campaign is 400
validation_failed. A campaign with autoLaunchWhenReady launches once processing
reaches ready. Returns the campaign.

Requires Campaigns edit and the `launch` permission. A campaign of
another workspace is 404 not_found. While the workspace's data is scheduled for
deletion or being deleted, returns 409 invalid_state. Replaces the legacy
campaign_ops restart and restart_processing verbs.

campaign-batches-restore-sample

Write. POST https://api.ken.so/v1/campaign-batches/{campaignBatchId}/samples/{contactId}/restore

Path: campaignBatchId, contactId

Undo a skip: the lead goes out with this campaign batch again when it is approved.

POST /api/v1/campaign-batches/{campaignBatchId}/samples/{contactId}/restore. Internal, behind the
campaign_batches flag. Sends Ken-Version 1.1, X-Ken-Workspace-Id and X-Ken-Actor: agent. Needs
campaigns edit. Honors Idempotency-Key.
Works while the batch is pending: the lead counts in the batch again. A lead that is not skipped
stays as it is. A batch that is not pending or waits on the client is 409 invalid_state; a lead
that is not in the batch is 404 not_found. Returns the batch with its samples (see
campaign-batches-get).

campaign-batches-skip-sample

Write. POST https://api.ken.so/v1/campaign-batches/{campaignBatchId}/samples/{contactId}/skip

Path: campaignBatchId, contactId

Body (json): reason string

Skip one lead of a pending campaign batch: it does not go out with this batch and waits for a later one. Sends nothing and removes nothing. Undo with campaign-batches-restore-sample.

POST /api/v1/campaign-batches/{campaignBatchId}/samples/{contactId}/skip. Internal, behind the
campaign_batches flag. Sends Ken-Version 1.1, X-Ken-Workspace-Id and X-Ken-Actor: agent. Needs
campaigns edit. Honors Idempotency-Key.
- contact_id: the sample's contactId.
- reason: optional, up to 500 characters, kept with the lead until the batch is approved.
The lead stays in the campaign, held and unsent. The batch's count drops by one, so approve it
with the new count; approving moves the skipped lead into the campaign's next batch, where it is
reviewed again. The sample stays in samples with skipped: true. Skipping a skipped lead changes
nothing. A batch that is not pending or waits on the client is 409 invalid_state, and so is the
batch's last email (last_email). A lead that is not in the batch is 404 not_found. Returns the
batch with its samples (see campaign-batches-get).

unarchive

Write. POST https://api.ken.so/v1/campaigns/{campaignId}/unarchive

Path: campaignId

Unarchive a campaign. It never starts sending: a finished one comes back completed, one that launched comes back paused, one that never launched comes back a draft. Idempotent when the campaign is not archived.

POST /api/v1/campaigns/{campaignId}/unarchive. Public. Sends Ken-Version 1.1.
Requires Campaigns edit and the `launch` permission. To send again, call
campaigns(operation="resume", campaign_id=...): resume plans the sends that
archiving cancelled.

campaign-batches-update-sample

Write. PATCH https://api.ken.so/v1/campaign-batches/{campaignBatchId}/samples/{contactId}

Path: campaignBatchId, contactId

Body (json): body string, editableBody string, editableBodyVersion string, subject string, updatedAt date-time

Put the person's own subject and body in place of Ken's first email for one lead of a pending batch. Only text the person wrote or approved. Nothing is sent here; the send uses it once the batch is approved.

PATCH /api/v1/campaign-batches/{campaignBatchId}/samples/{contactId}. Internal, behind the
campaign_batches flag. Sends Ken-Version 1.1, X-Ken-Workspace-Id and X-Ken-Actor: agent. Needs
campaigns edit. Honors Idempotency-Key.
- updated_at: the sample's updatedAt from campaign-batches-get. When the lead changed since (an
  edit, a skip, an undo), nothing is stored: 409 sample_changed.
- subject: plain text, one line, up to 500 characters. Omit to keep it; an empty string goes
  back to Ken's subject.
- editable_body: the sample's email.editableBody as edited, up to 20,000 characters. A link
  marker's text becomes the link's text (same URL); a deleted marker drops its element, except
  the unsubscribe link. Empty goes back to Ken's body. A bad marker is 400 on editableBody
  (marker_*, unsubscribe_link_required); a Studio email is 409 system_link.
- editable_body_version: the sample's email.editableBodyVersion, required with editable_body.
  409 sample_changed when Ken's links, images or videos changed since: read the batch again.
- body: plain text, only for an email with no link, image or video (else 409 system_link);
  not with editable_body.
The text is the person's: a {token} or {{token}} in it goes out as written. This tool's edits
read email.editedByHuman: false (an agent's). The edit does not reach an inbox whose provider builds the message
itself. A batch that is not pending or waits on the client is 409 invalid_state; a lead that is
not in the batch is 404 not_found. Returns the batch with its samples (see campaign-batches-get).

campaign_linkedin_url_mismatches

Read.

List campaign leads whose LinkedIn slug does not match first+last name.

Cheap heuristic for campaign QA (wrong-person InMail targets). Does not
reject or rewrite URLs. The same flag is ``linkedInUrlNameMismatch`` on
``ContactDTO`` and export column ``linkedin_url_name_mismatch``.

Parameters
----------
campaign_id : int
    Campaign to scan (required).
client_id : int, optional
    Owning client id; omit to resolve from the auth token.
page_index : int
    1-based page (default 1).
page_size : int
    Page size, 1..200 (default 100).

Returns
-------
dict
    Envelope with a page of ``{contactId, firstName, lastName, profileUrl}``.

Examples
--------
    >>> await campaign_linkedin_url_mismatches(campaign_id=8233, client_id=24)

pipeline

Read.

Campaign processing pipeline: snapshot funnel counts or recent events.

Inspect a campaign's processing pipeline (Import through Sending).

### view=snapshot (default)
Get the processing pipeline snapshot for a campaign.

Returns the backend BaseResponse envelope from GET
/v1/campaigns/{campaign_id}/pipeline without additional unwrapping. The
pipeline stages are reported in this order: Import, Qualification,
Enrichment, Verification, Segmentation, Personalization, Export,
Sending.

Each stage includes funnel counts: total, processed, failedCount, and
stuckCount. Status values describe the stage state and include Stalled;
stalled stages include stalledSince so callers can show when progress
stopped. The top-level asOf field indicates when the snapshot was computed
so agents can reason about staleness. A details field appears only for
admin callers. Verification, Segmentation, and Qualification stages also
carry a user-facing breakdown map of distribution counts (zero buckets
omitted): Verification uses email validity buckets Safe, Verified,
CatchAll, Risky, Invalid, Unknown, NoEmail; Segmentation uses contacts per
segment name plus Unsegmented; Qualification uses Qualified, Unqualified,
Unprocessed.

Response field reference:
stages: [{stage, status, total, processed, failedCount, stuckCount, lastProgressAt, stalledSince, breakdown?, details?}]

### view=events
Get recent processing pipeline events for a campaign.

Returns the backend BaseResponse envelope from GET
/v1/campaigns/{campaign_id}/pipeline/events without additional unwrapping.
Use this with view=snapshot when investigating how a campaign moved through
the 8 pipeline stages.

Parameters:
-----------
campaign_id : int
    Campaign ID to inspect.
view : str
    "snapshot" (default) for the stage funnel, or "events" for the feed.
page_index : int
    Zero-based page index for view=events. Defaults to 0.
page_size : int
    Page size for view=events. Defaults to 50.
client_id : int, optional
    Workspace the campaign must belong to. Defaults to the selected
    workspace; staff may omit it. A campaign from another workspace is
    reported as not found.

reset_processing_status

Write.

Reset a campaign's stuck ProcessingStatus flag (reset_processing_status). Not for CampaignStatus changes.

Reset the ProcessingStatus bookkeeping flag of a campaign.

This tool does NOT change CampaignStatus - that is
campaigns(operation='launch'|'pause'|'resume').

Tool Selection (campaign domain):
---------------------------------
- "restart" the campaign because processing stalled ->
  campaign_ops(operation="restart").
- "reset processing status" / clear the stuck ProcessingStatus flag ->
  use this tool with operation="reset_processing_status".
- "reset" a specific AI workflow (qualification / personalization /
  rewriting / segmentation) so contacts can be re-processed ->
  models(operation="reset").
- Import contacts into a campaign (CSV, search results, another campaign) ->
  contacts(operation="contact-imports-create").
- Edit campaign name, contact limit, schedule, mode or auto-launch ->
  campaigns(operation="update"); AI workflows ->
  campaign_flow(operation="replace-ai-workflows").

See docs/campaign-tool-selection.md for the full verb -> tool map.

Operations:
-----------
reset_processing_status:
    Reset the campaign's ProcessingStatus flag (the bookkeeping flag that
    tracks whether processing is mid-flight). Use this when the flag is
    stuck after a crash or a cancelled run, before re-kicking processing
    with campaign_ops(operation="restart"). This is NOT a CampaignStatus
    reset and NOT an AI-flow reset.
    Example: operation="reset_processing_status", campaign_id=123, client_id=42

"reset_status" is a deprecated alias for "reset_processing_status".

client_id is optional. The backend endpoint does not require it in the URL,
but downstream auth checks need it for cross-workspace access; pass
client_id for the campaign's workspace. It is also used to enrich HTTP 400
errors with the campaign's current status.

Error shape on bad-state rejection:
    On HTTP 400 this tool raises KenValidationError with a `details` dict:
        {
          "attempted_operation": "reset_processing_status",
          "campaign_id": int,
          "current_status": Optional[int],
          "current_status_name": Optional[str],   # e.g. "Sending"
          "allowed_next_operations": list[str],
          "fix_hint": str,
          "raw_message": str,
        }
    Inspect `details` to recover without parsing the message string.

Returns:
--------
dict
    An API response wrapping the updated CampaignDTO, trimmed to the
    lifecycle fields. Read `campaignStatuses` (CampaignStatus values
    0=Draft, 1=Building, 2=Ready, 3=Sending, 4=Paused, 5=Completed,
    6=Error) as the canonical public state. The legacy `status` int is
    the unrelated `Status` enum, not the public lifecycle. Only the
    processingStatus flags are reset; sendingStatus is left untouched.

reset_status

Write.

Reset a campaign's stuck ProcessingStatus flag (reset_processing_status). Not for CampaignStatus changes.

Reset the ProcessingStatus bookkeeping flag of a campaign.

This tool does NOT change CampaignStatus - that is
campaigns(operation='launch'|'pause'|'resume').

Tool Selection (campaign domain):
---------------------------------
- "restart" the campaign because processing stalled ->
  campaign_ops(operation="restart").
- "reset processing status" / clear the stuck ProcessingStatus flag ->
  use this tool with operation="reset_processing_status".
- "reset" a specific AI workflow (qualification / personalization /
  rewriting / segmentation) so contacts can be re-processed ->
  models(operation="reset").
- Import contacts into a campaign (CSV, search results, another campaign) ->
  contacts(operation="contact-imports-create").
- Edit campaign name, contact limit, schedule, mode or auto-launch ->
  campaigns(operation="update"); AI workflows ->
  campaign_flow(operation="replace-ai-workflows").

See docs/campaign-tool-selection.md for the full verb -> tool map.

Operations:
-----------
reset_processing_status:
    Reset the campaign's ProcessingStatus flag (the bookkeeping flag that
    tracks whether processing is mid-flight). Use this when the flag is
    stuck after a crash or a cancelled run, before re-kicking processing
    with campaign_ops(operation="restart"). This is NOT a CampaignStatus
    reset and NOT an AI-flow reset.
    Example: operation="reset_processing_status", campaign_id=123, client_id=42

"reset_status" is a deprecated alias for "reset_processing_status".

client_id is optional. The backend endpoint does not require it in the URL,
but downstream auth checks need it for cross-workspace access; pass
client_id for the campaign's workspace. It is also used to enrich HTTP 400
errors with the campaign's current status.

Error shape on bad-state rejection:
    On HTTP 400 this tool raises KenValidationError with a `details` dict:
        {
          "attempted_operation": "reset_processing_status",
          "campaign_id": int,
          "current_status": Optional[int],
          "current_status_name": Optional[str],   # e.g. "Sending"
          "allowed_next_operations": list[str],
          "fix_hint": str,
          "raw_message": str,
        }
    Inspect `details` to recover without parsing the message string.

Returns:
--------
dict
    An API response wrapping the updated CampaignDTO, trimmed to the
    lifecycle fields. Read `campaignStatuses` (CampaignStatus values
    0=Draft, 1=Building, 2=Ready, 3=Sending, 4=Paused, 5=Completed,
    6=Error) as the canonical public state. The legacy `status` int is
    the unrelated `Status` enum, not the public lifecycle. Only the
    processingStatus flags are reset; sendingStatus is left untouched.

status

Read.

Lifetime campaign snapshot: campaign, segments, overall stats, pipeline. No date window - not for last week/month. Use api_dashboard view=summary or chart.

Typed replacement for the ken-ai-plugin ``/ken-ai:campaign-status`` command.

Lifetime snapshot only (no start_date / end_date / period). Do not use this
for "last week", "this month", or any date-windowed analytics - those are
``analytics_campaign(operation="dashboard")`` with ``view="summary"`` or
``view="chart"`` (workspace) or
``analytics(operation="get-campaign-performance")`` (per-campaign, with a window).

Composes existing backend REST endpoints only (no MySQL query tools),
so client-facing principals can use it: the campaign read, the campaign
list, the campaign's lifetime statistics and its segment list.

Parameters
----------
campaign_id : int, optional
    Campaign id. Exactly one of ``campaign_id`` / ``campaign_name`` required.
campaign_name : str, optional
    Case-insensitive name resolution against campaign names via
    ``GET /api/v1/campaigns`` (query params from api-surface:
    ``campaignStatus``, ``clientId``, ``pageIndex``, ``pageSize``,
    ``status``, ``tagId``, ``tagIds``, ``tagMatch`` - there is no dedicated
    name/search parameter). Pages client-side up to 5 pages of 100 items.
    Exact name matches take precedence over substring matches. Unique match
    proceeds only when the scan did not hit the page cap; zero matches,
    multiple matches, or a single match after a capped scan return
    ``{"success": false, "error": {"message": ..., "candidates": [{id, name}]}}``.
client_id : int, optional
    Workspace to look the campaign up in, sent as ``clientId``. Defaults to
    the selected workspace; required when none is selected (staff). A
    ``campaign_id`` from another workspace is reported as not found
    before any other read.
include_events : bool
    When true, also fetches the first page of pipeline events
    (``GET /v1/campaigns/{id}/pipeline/events``, pageIndex=0, pageSize=50).

Returns
-------
dict
    ``{"success": true, "data": {"campaign": ..., "segments": ...,
    "statistics": ..., "pipeline": ..., "events": ...?}}``.

    Each sub-object is the backend ``data`` payload after unwrapping the
    ``{success, data}`` envelope once (base+data endpoints).

Endpoints composed
------------------
- ``GET /api/v1/campaigns/{id}`` - campaign row
- ``GET /api/v1/campaigns`` - name resolution (list)
- ``GET /api/v1/campaigns/{campaignId}/segments`` - segment list
- ``GET /api/v1/campaigns/{id}/statistics/overall`` - lifetime totals (no date window)
- ``GET /v1/campaigns/{campaign_id}/pipeline`` - funnel + breakdowns
- optional ``GET /v1/campaigns/{campaign_id}/pipeline/events``

Pipeline stages (order)
-----------------------
Import, Qualification, Enrichment, Verification, Segmentation,
Personalization, Export, Sending.

Each stage: ``total``, ``processed``, ``failedCount``, ``stuckCount``,
``status``, ``lastProgressAt``, ``stalledSince``, optional ``breakdown`` /
``details``.

Breakdown vocabulary (zero buckets omitted)
-------------------------------------------
- **Verification** (email validity buckets): Safe, Verified, CatchAll,
  Risky, Invalid, Unknown, NoEmail.
  Legacy numeric codes for agent reference only (not returned as ints here):
  0=Unknown, 1=Invalid, 2=Risky, 3=Verified, 4=Safe, 5=CatchAll.
- **Segmentation**: contacts per segment name plus Unsegmented.
- **Qualification**: Qualified, Unqualified, Unprocessed - this is the
  authoritative ``contacts.qualified``-derived split.

**Never** describe the Qualification stage completion marker / outreach id
11 (AiQualification completed) as "qualified". The Qualification
breakdown's Qualified/Unqualified/Unprocessed counts are authoritative.

Known gaps vs the old plugin command (no REST equivalent - not faked)
--------------------------------------------------------------------
- Per-segment per-validity cross-tabulation
- Website-enrichment page counts
- Personalization / rewriting per-segment counts

Enrichment and Personalization stages still expose campaign-level funnel
counts (total/processed/failed/stuck), which is the supported granularity.

Examples
--------
By id::

    campaign_ops(operation="status", campaign_id=123)

By name::

    campaign_ops(operation="status", campaign_name="Fashion Q3")

With pipeline events::

    campaign_ops(operation="status", campaign_id=123, include_events=True)