Prompts prompts
A campaign's or segment's AI prompts (qualification, personalization, ...): list with campaign_id, alone; it needs no campaign read.
Call it from an MCP client connected to https://mcp.ken.so/mcp: reads go through prompts_read and changes through prompts_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: prompt-templates-create, create, prompt-templates-delete, delete, prompt-templates-get, prompt-versions-get, get, prompt-templates-list, prompt-versions-list, list, restore, test, prompt-templates-update, update, ai_variables_save, save_new_version_from_prompts, save_new_version_from_variables
prompt-templates-create
Write. POST https://api.ken.so/v1/prompt-templates
Body (json): campaignId integer, description string, flow string, modelConfigurationId integer, name string, prompts array, scope string
Create a prompt template in the current workspace. scope=workspace is owned by the workspace header. Returns 201 and Location.
POST /api/v1/prompt-templates. Internal. Sends Ken-Version 1.1. Requires Campaigns edit. Qualification prompts keep the campaign AI workflow in sync. A campaign or model configuration outside the workspace is not_found before the write. flow is qualification, personalization, rewriting, segmentation, or scoring (tone_of_voice templates can be listed and read, but the API takes no new one). scope is user, workspace, or global. Each prompts item needs prompt and type (system, user, or assistant).
create
Write. POST https://api.ken.so/v1/prompts
Query: confirm boolean (required)
Body (json): audienceDescription string, campaignId integer, disqualificationCriteria string, fallbackIfEmpty string, flow string, isRequiredForSending boolean, name string, order integer, prompt string, promptTemplateId integer, qualificationCriteria string, scoringCriteria string, segmentId integer, toOutput boolean, toRewrite integer, type string
Create a prompt in the current workspace. campaign_id or segment_id is required. confirm=true when the write refreshes cached AI results. Returns 201 and Location.
POST /api/v1/prompts. Public. Sends Ken-Version 1.1. Requires Campaigns edit. prompt_type is system, user, or assistant. flow is qualification, personalization, rewriting, segmentation, or scoring. tone_of_voice prompts can be listed and read, but the API takes no new one: it is refused here. flow=personalization (an AI variable) takes prompt_type="system" only, and any other type is refused here: every personalization reader loads only system prompts, so the API would save the prompt and never generate it. PascalCase names and Flow integers are accepted and sent as those strings. Pass confirm=false when the write does not refresh cached results. prompt_template_id must be a Workspace-scope template of the current workspace. Another workspace's template, a User template or a Global template returns 404 not_found on field promptTemplateId; manage those templates' prompts through the prompt templates operations.
prompt-templates-delete
Write. DELETE https://api.ken.so/v1/prompt-templates/{templateId}
Path: templateId
Delete a prompt template. Returns 204. A template outside the workspace is not_found. Internal.
DELETE /api/v1/prompt-templates/{templateId}. Internal. Sends Ken-Version 1.1.
Requires Campaigns edit.
delete
Write. DELETE https://api.ken.so/v1/prompts/{promptId}
Path: promptId
Query: confirm boolean (required)
Delete a prompt. Returns 204. confirm=true when deletion would refresh cached AI results.
DELETE /api/v1/prompts/{promptId}. Public. Sends Ken-Version 1.1.
Requires Campaigns edit.
prompt-templates-get
Read. GET https://api.ken.so/v1/prompt-templates/{templateId}
Path: templateId
Return one prompt template visible in the current workspace. A missing or cross-workspace id is not_found. Internal.
GET /api/v1/prompt-templates/{templateId}. Internal. Sends Ken-Version 1.1.
Requires Campaigns view.
prompt-versions-get
Read. GET https://api.ken.so/v1/segments/{segmentId}/prompt-versions/{versionId}
Path: segmentId, versionId
Return one prompt version for a segment in the current workspace. A missing segment or version is not_found. Public.
GET /api/v1/segments/{segmentId}/prompt-versions/{versionId}. Public.
Sends Ken-Version 1.1. Requires Campaigns view. The detail includes the
saved prompts.
get
Read. GET https://api.ken.so/v1/prompts/{promptId}
Path: promptId
Return one prompt in the current workspace. A missing or cross-workspace id is not_found.
GET /api/v1/prompts/{promptId}. Public. Sends Ken-Version 1.1.
prompt-templates-list
Read. GET https://api.ken.so/v1/prompt-templates
Query: cursor string, flow string, limit integer, q string, scope string
List prompt templates visible in the current workspace. Filter by flow or scope. q matches the name. Internal.
GET /api/v1/prompt-templates. Internal. Sends Ken-Version 1.1. client_id is the workspace, sent as X-Ken-Workspace-Id. Workspace-scoped rows are limited to that workspace. q is at most 200 characters. flow is qualification, personalization, rewriting, segmentation, tone_of_voice, or scoring. scope is user, workspace, or global. Requires Campaigns view.
prompt-versions-list
Read. GET https://api.ken.so/v1/segments/{segmentId}/prompt-versions
Path: segmentId
Query: cursor string, limit integer
List prompt versions for a segment in the current workspace. A segment outside the workspace is not_found. Public.
GET /api/v1/segments/{segmentId}/prompt-versions. Public. Sends Ken-Version 1.1.
Requires Campaigns view. Ordered by id. limit is 1 to 200.
list
Read. GET https://api.ken.so/v1/prompts
Query: campaignId integer, cursor string, flow string, limit integer, q string, segmentId integer
List prompts in the current workspace. Filter by campaign, segment, or flow. q matches the name only.
GET /api/v1/prompts. Public. Sends Ken-Version 1.1. client_id is the workspace, sent as X-Ken-Workspace-Id. campaign_id and segment_id filter within that workspace. q is at most 200 characters. flow is qualification, personalization, rewriting, segmentation, tone_of_voice, or scoring.
restore
Write. POST https://api.ken.so/v1/segments/{segmentId}/prompt-versions/{versionId}/restore
Path: segmentId, versionId
Body (json): confirm boolean, dryRun boolean
Restore a prompt version for a segment in the current workspace. dry_run returns what the restore would clear and does not write. Public.
POST /api/v1/segments/{segmentId}/prompt-versions/{versionId}/restore.
Public. Sends Ken-Version 1.1. Requires Campaigns edit. Qualification sync stays
inside the existing revert command. A restore that would clear campaign AI
output returns 409 conflict with error.impact until confirm is true. dry_run
returns dryRun, hasImpact and impact without writing. An applied restore
returns versionNumber and versionWarning (set when version history or the
model configuration was not fully captured).
A segment outside the workspace is not_found before the write.
test
Write. POST https://api.ken.so/v1/prompts/test
Body (json): campaignId integer, excludeContactIds array, flow string, modelOverrides object, sampleSize integer, segmentId integer
Run a prompt test against live model calls. Samples contacts in the campaign and runs the requested flow. This spends model usage. Requires prompt test access.
POST /api/v1/prompts/test. Public. Sends Ken-Version 1.1. flow is qualification, personalization, rewriting, segmentation, or scoring (tone_of_voice is refused, as the API refuses it). model_overrides is keyed by flow, the same five. Each value needs model, and may set max_tokens, temperature, and reasoning_level (none, minimal, low, medium, high).
prompt-templates-update
Write. PATCH https://api.ken.so/v1/prompt-templates/{templateId}
Path: templateId
Update a prompt template. Absent fields stay unchanged. JSON null clears description or model_configuration_id. Internal.
PATCH /api/v1/prompt-templates/{templateId}. Internal. Sends Ken-Version 1.1.
Requires Campaigns edit. A template outside the workspace is not_found before
the write. Qualification prompt edits keep the campaign AI workflow in sync.
changes uses snake_case or camelCase field names. A flow change takes the
create flows; tone_of_voice is refused, and so is any change to a stored
tone_of_voice template (the API refuses that one).
update
Write. PATCH https://api.ken.so/v1/prompts/{promptId}
Path: promptId
Query: confirm boolean (required)
Update a prompt. Absent fields stay unchanged. JSON null clears a text field or prompt_template_id. segment_id cannot change on this route, and campaign_id cannot be cleared on a prompt without a segment. confirm=true when the write would refresh cached AI results.
PATCH /api/v1/prompts/{promptId}. Public. Sends Ken-Version 1.1.
Requires Campaigns edit. changes uses snake_case or camelCase field names.
Pass null to clear name, prompt text, criteria, fallback_if_empty, or
prompt_template_id. segment_id cannot change here. campaign_id null on a
prompt without a segment returns 400 (the prompt would belong to no
workspace). A new prompt_template_id
must be a Workspace-scope template of the current workspace; anything else
returns 404 not_found on field promptTemplateId. A flow change takes
qualification, personalization, rewriting, segmentation, or scoring;
tone_of_voice is refused here, as the API refuses it.
ai_variables_save
Write.
Bulk upsert AI variables (Personalization prompts). Supports per-variable fallbackIfEmpty and isRequiredForSending; omit those keys to preserve stored values. Wiping saves 409 unless confirm=true; print message+impact first.
Bulk upsert AI variables (Personalization prompts) for a campaign in one call.
SAVE SEMANTICS: this is a LIVE save - it mutates the working AI variable
set and does NOT create a prompt-bundle version row. To capture a
versioned snapshot of the segment's AI variables, call
prompts(operation="save_new_version_from_variables", ...).
CASCADE WIPE: deleting a variable or dropping rewriting that would clean
AI rows is a no-op without confirm=true. The API returns 409 with preview
message + impact. Print both to the human first, then re-call with
confirm=true. dry_run=true returns the preview and does not write.
Zero-impact saves succeed without confirm. confirm/dryRun are body fields
on SaveAiVariablesRequest, not query params.
Why use this over editing prompts one at a time:
------------------------------------------------
This tool wraps the Kenso backend's dedicated `SaveAiVariablesCommand` endpoint,
which does substantially more than individual prompt CRUD. Prefer this tool when
authoring or updating the full set of AI variables for a campaign segment.
Key behaviors the backend performs automatically:
- Bulk upsert with name-based reconciliation: each variable is matched by `name`
against existing Personalization prompts for the campaign/segment. Existing
variables with the same name are updated in place, new names are created, and
names not present in the payload are deleted. This replaces the variable set.
- Auto-syncs the Personalization (flow=2) AI workflow so the campaign runs
personalization with the new variable set.
- New/default variables are created with rewriting disabled (`toRewrite = 0`).
Saving variables does not auto-enable Rewriting (flow=3).
- If Rewriting was already enabled on the campaign, the backend preserves it only
when the save keeps at least one same-name surviving variable with
`toRewrite > 0`. Empty saves clear both Personalization and Rewriting.
- When `model` is provided, the backend creates or updates
`AiFlowModelConfiguration` for Personalization. Rewriting keeps its own
explicit config or runtime fallback behavior.
- Clears affected `AiPre*` / AI outreach statuses, including both
personalization and rewriting statuses, so the next cycle re-runs from the
updated variable state.
When to use a different tool instead:
-------------------------------------
- Qualification (flow=1), Rewriting (flow=3) and Segmentation (flow=4) prompts →
prompts(operation="list", campaign_id=..., flow=...) to find the campaign's prompt
of that flow, then prompts(operation="update", prompt_id=..., changes=..., confirm=...),
or prompts(operation="create", ...) when there is none
- ToneOfVoice (flow=5) or other ad-hoc prompt surgery → prompts(operation="create")
or prompts(operation="update")
- Editing a single Personalization prompt without disturbing the rest of the
variable set → prompts(operation="update")
Endpoint:
---------
PUT /api/v1/campaigns/{campaign_id}/ai-variables
Query: ?segmentId={int} (optional - scopes to a specific campaign segment)
Parameters:
-----------
client : KenAPIClient
API client instance
campaign_id : int
Campaign ID to save variables for
variables : list[dict]
Non-empty list of variable definitions. Each entry must be a dict with:
- name (str, required): variable name used for reconciliation (e.g. "First Line").
Names must stay non-empty and unique after variable-name normalization
to lowercase snake_case (for example, "Subject Line" collides with
"subject_line").
- prompt (str, required): prompt text template with {{placeholders}}
- order (int, optional): zero-based execution order within the flow
- fallbackIfEmpty (str, optional, nullable): static plain-text default
used when this variable's AI output is missing or whitespace-only,
after any inline ``{{Name|fallback}}`` override in the sequence body.
Does not apply to lead/custom single-brace tokens. Rejected by this
tool when it contains '|', '{', or '}' - those characters would make
an opaque backend 400; the MCP fails early with a clear message naming
the variable. Nested variables inside fallback text are not supported.
- isRequiredForSending (bool, optional, nullable): when true, a contact
with no non-whitespace AI output for this variable (and no effective
fallback) is not send-ready.
A set fallbackIfEmpty or an inline ``{{Name|fallback}}`` satisfies
the required-for-sending gate, so the lead still ships with the
fallback text. Must be a real JSON bool when present (not "true"/1).
Fallback precedence (ALWAYS, for AI variables):
1. Inline pipe in the sequence body (e.g.
``{{First Line|Hope you're well.}}``) overrides everything.
2. Otherwise ``fallbackIfEmpty`` on this entry (dialog default) is used.
3. Otherwise bare: blank AI output ships blank (or the lead is
excluded if isRequiredForSending is true and no fallback exists).
Preserve-on-omit / clear semantics (nullable fields):
- OMIT the key, or send null, to PRESERVE the stored value on an
existing variable. On a brand-new variable, omit/null means no
fallback and isRequiredForSending=false.
- Send ``fallbackIfEmpty: ""`` (empty string) to CLEAR a stored
dialog fallback.
- Send ``isRequiredForSending: false`` explicitly to clear a stored
required flag. Do not omit the key if you intend to turn it off.
segment_id : int, optional
Campaign segment ID. Omit to target the campaign-level variable set, or
provide it to scope the save to a single segment.
model : str, optional
Logical model name from `models(operation="ai_supported_models", flow="Personalization")`,
such as "kimi-k2.6" or "deepseek-v4-flash". Provider
routing is auto-selected by the backend provider-chain and batch failover
tables. Omit to leave the existing model config untouched. "grok-4.7"
works only when the workspace's own xAI or OpenRouter key unlocks it.
vendor : str, optional
Operator override for the backend AI provider enum. Leave omitted for
normal campaign setup so provider-chain failover decides the vendor.
Accepted values: "OpenAI", "Anthropic", "xAI", "Moonshot",
"Doubleword", "DeepSeek", "Meta", "ExperientialLabs",
"Hemmingway". OpenRouter, TogetherAi, and FireworksAi are
temporarily disabled for new selections.
The backend validates that the vendor supports the logical model for
Personalization before storing the provider-specific route.
Use `models(operation="ai_supported_models", flow="Personalization", include_vendors=True)`
only when you need to inspect provider groups before choosing an override.
reasoning_level : str, optional
Reasoning effort the model should apply. One of "None", "Minimal", "Low",
"Medium", "High". Only meaningful for reasoning-capable models; ignored
by providers that don't expose a reasoning knob. Omit to leave the
existing setting untouched. The backend defaults new configurations to
"None" when this is not supplied on first create.
DEFAULT TO "None" - reasoning costs significantly more tokens, latency,
and money per Personalization call (which fans out across every contact
in a campaign segment, so the multiplier compounds fast). Pick the lowest
level that demonstrably improves output quality:
- "None" - the right default for Personalization in almost every case
- "Minimal" / "Low" - try only if "None" produces clearly broken output
- "Medium" / "High" - reserve for narrow cases with measured wins;
never a first choice and never a "to be safe" pick
Returns:
--------
dict
API response with structure:
{
"success": bool,
"message": str,
"data": { ... }
}
Examples:
---------
Save the full variable set for a campaign segment using Kimi.
Entries below only set name/prompt/order - they do NOT send
fallbackIfEmpty or isRequiredForSending, so any previously stored
dialog fallback and required flag on same-name existing variables
are PRESERVED (new names get no fallback / required=false):
>>> await ai_variables_save(
... campaign_id=456,
... segment_id=78,
... model="kimi-k2.6",
... variables=[
... {"name": "Subject Line", "prompt": "Write a subject...", "order": 1},
... {"name": "First Line", "prompt": "Write an intro for {{firstName}}...", "order": 2},
... {"name": "PS Line", "prompt": "Write a PS line...", "order": 3},
... ],
... )
Save campaign-level variables without touching the model config.
Same preserve-on-omit: only name/prompt/order are sent, so stored
fallbackIfEmpty / isRequiredForSending on "First Line" are untouched:
>>> await ai_variables_save(
... campaign_id=456,
... variables=[
... {"name": "First Line", "prompt": "Write an intro...", "order": 1},
... ],
... )
Save with a dialog fallback and required-for-sending flag:
>>> await ai_variables_save(
... campaign_id=456,
... segment_id=78,
... variables=[
... {
... "name": "First Line",
... "prompt": "Write an intro for {{firstName}}...",
... "order": 1,
... "fallbackIfEmpty": "Hope you're well.",
... "isRequiredForSending": True,
... },
... ],
... )
# Sequence body {{First Line|Hope this finds you well.}} still overrides
# the dialog default above. With isRequiredForSending true, a blank AI
# output ships the fallback rather than excluding the lead.
Clear a stored dialog fallback (empty string) while leaving required alone
(omit isRequiredForSending so the stored flag is preserved):
>>> await ai_variables_save(
... campaign_id=456,
... variables=[
... {
... "name": "First Line",
... "prompt": "Write an intro...",
... "order": 1,
... "fallbackIfEmpty": "",
... },
... ],
... )
Save variables targeting a reasoning model with an operator vendor override.
Again only name/prompt/order - does not touch stored fallback/required:
>>> await ai_variables_save(
... campaign_id=456,
... segment_id=78,
... model="deepseek-v4-flash",
... vendor="DeepSeek",
... reasoning_level="Low", # only honored by reasoning-capable models
... variables=[
... {"name": "First Line", "prompt": "Write an intro...", "order": 1},
... ],
... )
save_new_version_from_prompts
Write.
Manage immutable prompt-bundle versions for a campaign segment. Ops: save_new_version_from_variables, save_new_version_from_prompts. Client-facing: campaign-scoped.
Manage immutable prompt-bundle versions for a campaign segment.
Client-facing sub-surface (task 15): all operations on this tool are already
campaign-scoped (campaign_id + segment_id required). save_new_version_*
need campaigns edit in the pinned workspace on the client-facing host.
client_id is the workspace selector that host binds; neither save
operation sends it.
A prompt bundle = all prompts + AI variables for a (campaign, segment).
The backend versions the bundle as one immutable row; you cannot version
individual prompts.
SAVE SEMANTICS
--------------
- Live edits via ai_variables_save and prompt_save mutate the
working bundle. They do NOT create a bundle-version row.
- save_new_version_from_variables / save_new_version_from_prompts:
create one immutable bundle-version row. That row alone is NOT
reachable from the dashboard version-history popover, which lists
segment versions. For any user-visible checkpoint that should appear
in the popover (and cascade on segment revert), use
email_sequences(operation="save_bundle_version") instead
(see docs/sequence-versioning-workflow.md). The two operations exist
because the backend save endpoint accepts either payload shape; pick
based on what part of the bundle you're capturing:
* variables -> use save_new_version_from_variables (AI variables
for the Personalization flow). Preferred when only
snapshotting variables: the variables branch
back-fills non-personalization prompts from live
state, producing a complete bundle snapshot.
* full bundle -> use save_new_version_from_prompts (sends the full
prompts array; snapshots only what you send, so
omitted prompt kinds are missing from the version)
Operations:
-----------
save_new_version_from_variables:
Capture a new bundle version from an AI-variables payload.
Params: campaign_id, segment_id, variables (list of {name, prompt,
order?}), model?, reasoning_level?, source_version_id?
When source_version_id is omitted, the supplied variables payload is
captured directly; the MCP wrapper does not inject the latest version
id. The wrapper response echoes the resolved source under
`data.sourceVersionId` and `data.sourceMode`.
save_new_version_from_prompts:
Capture a new bundle version from a full PromptLibraryDTO array.
Params: campaign_id, segment_id, prompts (list), model?,
reasoning_level?, source_version_id? When source_version_id is
omitted, the supplied prompts payload is captured directly.
Returns:
--------
dict
Backend envelope. For save_new_version_*, the response is wrapped:
{
"success": true,
"data": {
"newVersionId": int | None,
"sourceVersionId": int | None,
"sourceMode": "provided" | "latest" | "live",
"versionWarning": str | None,
"snapshot": <backend data field>
}
}
save_new_version_from_variables
Write.
Manage immutable prompt-bundle versions for a campaign segment. Ops: save_new_version_from_variables, save_new_version_from_prompts. Client-facing: campaign-scoped.
Manage immutable prompt-bundle versions for a campaign segment.
Client-facing sub-surface (task 15): all operations on this tool are already
campaign-scoped (campaign_id + segment_id required). save_new_version_*
need campaigns edit in the pinned workspace on the client-facing host.
client_id is the workspace selector that host binds; neither save
operation sends it.
A prompt bundle = all prompts + AI variables for a (campaign, segment).
The backend versions the bundle as one immutable row; you cannot version
individual prompts.
SAVE SEMANTICS
--------------
- Live edits via ai_variables_save and prompt_save mutate the
working bundle. They do NOT create a bundle-version row.
- save_new_version_from_variables / save_new_version_from_prompts:
create one immutable bundle-version row. That row alone is NOT
reachable from the dashboard version-history popover, which lists
segment versions. For any user-visible checkpoint that should appear
in the popover (and cascade on segment revert), use
email_sequences(operation="save_bundle_version") instead
(see docs/sequence-versioning-workflow.md). The two operations exist
because the backend save endpoint accepts either payload shape; pick
based on what part of the bundle you're capturing:
* variables -> use save_new_version_from_variables (AI variables
for the Personalization flow). Preferred when only
snapshotting variables: the variables branch
back-fills non-personalization prompts from live
state, producing a complete bundle snapshot.
* full bundle -> use save_new_version_from_prompts (sends the full
prompts array; snapshots only what you send, so
omitted prompt kinds are missing from the version)
Operations:
-----------
save_new_version_from_variables:
Capture a new bundle version from an AI-variables payload.
Params: campaign_id, segment_id, variables (list of {name, prompt,
order?}), model?, reasoning_level?, source_version_id?
When source_version_id is omitted, the supplied variables payload is
captured directly; the MCP wrapper does not inject the latest version
id. The wrapper response echoes the resolved source under
`data.sourceVersionId` and `data.sourceMode`.
save_new_version_from_prompts:
Capture a new bundle version from a full PromptLibraryDTO array.
Params: campaign_id, segment_id, prompts (list), model?,
reasoning_level?, source_version_id? When source_version_id is
omitted, the supplied prompts payload is captured directly.
Returns:
--------
dict
Backend envelope. For save_new_version_*, the response is wrapped:
{
"success": true,
"data": {
"newVersionId": int | None,
"sourceVersionId": int | None,
"sourceMode": "provided" | "latest" | "live",
"versionWarning": str | None,
"snapshot": <backend data field>
}
}