Overview
Apps can define AI capabilities that live inside the workspace — reusable skill instructions and agents with custom system prompts.defineSkill
Define AI agent skills
defineSkill
Define AI agent skills
Skills define reusable instructions and capabilities that AI agents can use within your workspace. Use Key points:
defineSkill() to define skills with built-in validation:src/skills/example-skill.ts
nameis a unique identifier string for the skill (kebab-case recommended).labelis the human-readable display name shown in the UI.contentcontains the skill instructions — this is the text the AI agent uses.icon(optional) sets the icon displayed in the UI.description(optional) provides additional context about the skill’s purpose.
defineAgent
Define AI agents with custom prompts
defineAgent
Define AI agents with custom prompts
Agents are AI assistants that live inside your workspace. Use Key points:Schema notes:
defineAgent() to create agents with a custom system prompt:src/agents/example-agent.ts
nameis the unique identifier string for the agent (kebab-case recommended).labelis the display name shown in the UI.promptis the system prompt that defines the agent’s behavior.description(optional) provides context about what the agent does.icon(optional) sets the icon displayed in the UI.modelId(optional) overrides the default AI model used by the agent.responseFormat(optional) sets the agent’s default output shape. Defaults to{ type: 'text' }for free-form text. Use{ type: 'json', schema }to force structured JSON output. ArunAgent()call or a workflow AI step can ask for a different shape, which takes precedence.roleUniversalIdentifier(optional) binds the agent to a role your app defines. That role must not grant more than the application role, or the build fails; see Agent roles.modelConfiguration(optional) turns on the model’s native tools, as the agent settings page does:{ webSearch: { enabled: true }, twitterSearch: { enabled: true } }. Each tool only works on models that support it. Leave it out to keep them off.isSystem(optional, defaults tofalse) hides the agent from agent lists, like the agents Twenty creates for workflow AI steps. It only changes what is displayed: an app’s agents can only be changed through the app, whatever this flag says.
responseFormat to { type: 'json' } and provide a schema:src/agents/structured-agent.ts
- The schema is a flat object: each property’s
typemust be a primitive (string,number, orboolean). Nested objects and arrays are not supported. description(optional) on each property guides the model on what to put there.required(optional) lists the properties the model must always return.additionalProperties: false(optional) forbids any property not declared inproperties.
defineMcpServer
Expose an external MCP server to the workspace's AI (beta)
defineMcpServer
Expose an external MCP server to the workspace's AI (beta)
Use Key points:
defineMcpServer() to ship a remote MCP server (Streamable HTTP) with your app, so the workspace’s AI can use its tools without syncing that data into Twenty:src/mcp-servers/github.ts
nameis snake_case (lowercase letters, digits and underscores, starting with a letter, at most 32 characters) and unique in the workspace. It prefixes the server’s tool names.urlmust be an HTTP or HTTPS URL.connectionProvider(optional) references a connection provider declared by the same app. Calls send that connection’s access token as a Bearer token. Omit it for a public server.- The URL cannot change in a later version while a connection provider is linked, so tokens are never sent to another host.
- Workspaces can deactivate the server; a later app version keeps that choice.
- Requires
"engines": { "twenty": ">=2.53.0" }.
runAgent
Run an agent from a logic function
runAgent
Run an agent from a logic function
runAgent() lets a logic function run one of your app’s agents (with its
skills and tools). Identify the agent by the universalIdentifier you passed
to defineAgent(), and pass what you want it to work on as input:src/logic-functions/run-enricher.ts
inputis a string, or a list of 1 to 100 messages ({ role: 'user' | 'assistant', content: string }). Ausermessage can also carry file attachments (see below). To hold a conversation, pass athreadrather than replaying earlier turns yourself.- By default the call waits for the agent, which can read/update records
itself via its own tools —
runAgent()resolves once the run completes. PasswaitForCompletion: falseto resolve as soon as the run starts:statusis thenRUNNINGandresult: null, and the reply lands in thethreadIdconversation. A run that outlasts 15 minutes also resolves asRUNNING. - The agent can also pause until a record changes or some time has passed.
runAgent()then resolves withsuccess: true,status: 'SUSPENDED'andresult: null; the agent goes on by itself later, and its reply lands in thethreadIdconversation. A call to athreadwhose agent is still waiting fails until it finishes. - Every call is stored with its input and status, plus its reply and usage
when it completes, so it shows up in the agent’s runs. Without a
thread, a call gets a conversation of its own:threadIdnames it, and a later call never sees it. - An app can only run its own agents.
- The app’s default role must grant the
AIpermission flag — addSystemPermissionFlag.AIto itspermissionFlagUniversalIdentifiers(or setcanAccessAllTools: true). Without it,runAgent()fails with a permission error. - Set a generous
timeoutSecondson the logic function — agent runs can take several seconds. statusisCOMPLETEDwith a non-nullresultwhen the run completes without waiting;SUSPENDEDwithsuccess: trueandresult: nullwhile it waits;RUNNINGwithsuccess: trueandresult: nullwhen the call did not wait for the run;FAILEDwithsuccess: falseanderrorholding the reason (for example, when the workspace ran out of AI credits mid-run).
src/roles/default-role.ts
Sending files with a message
Auser message can carry attachments, so the agent sees a screenshot or a
PDF instead of only its name. Each entry references a file your app has already
uploaded into the agent-chat folder:src/logic-functions/describe-screenshot.ts
UPLOAD_FILE permission flag on the app’s default role,
alongside AI. filename is optional and only labels the file for the model.- Only
usermessages may carry attachments. They cannot be represented on an assistant turn, sorunAgent()rejects them there rather than dropping them. - At most 10 attachments per message.
- The
fileIdmust name a fully uploaded file in the same workspace, under theagent-chatfolder. Anything else fails the call instead of quietly answering without the file.
Asking for a structured result
PassresponseFormat to get a shape for this call only. It takes precedence over
the agent’s own responseFormat, so one agent can serve callers that need
different outputs. It uses the same schema as defineAgent():src/logic-functions/score-lead.ts
Continuing a conversation
Pass athread and Twenty keeps the conversation for you: each call sends only
the new input, and the agent sees the earlier turns, including what its tools
returned. Use any stable identifier from your side as the key, such as a Slack
channel and thread timestamp:src/logic-functions/reply-in-thread.ts
- Keys are scoped to your app and agent, so two apps never share a
conversation. Only app access tokens can pass a
thread. inputmay only holdusermessages: the conversation already holds the agent’s replies.additionalInstructionsare given to the model for this call only and are not stored, which suits per-request guidance such as formatting rules or a deadline. They work without athreadtoo.- Every run is stored as a turn with its status, failed ones included. Its usage is stored when the agent returns, even if it ran out of credits. A failed run is not part of the conversation, so the next call does not see it.
- Calls on the same thread run one at a time: a second call waits for the first to finish, so each one sees the turns before it.
- When turns run as different members (see below), each one only sees the text of the others’ turns, never their tool results, since those were read with someone else’s permissions.
Running on behalf of a workspace member
PassrunAsWorkspaceMemberId when the run is triggered by a person — a chat
bot answering a message, for instance — so the agent acts as that member
instead of as the app:src/logic-functions/answer-question.ts
- A token with no user attached may name any member. A logic function runs
with one, and so do tokens minted through
client_credentialsor from an API key. - A token issued on behalf of a user, as a front component receives, may only name that user’s own member.
Following a conversation
An app reads the conversations it holds with its agents through the same API as the chat:listConversationMessages() returns its history, and
streamConversation() yields its live events, token by token. Name the
conversation by the agent and the thread key you pass to runAgent(); you
can start following it before the first run reaches it.src/logic-functions/follow-conversation.ts
- Events are the chat’s own:
stream-chunkcarries an AI SDKUIMessageChunkand aseq, and notifications such asmessage-persisted(a message was saved: a member’s, or the reply, which carries its run’sturnId),credits-exhausted(the reply stopped when the workspace ran out of credits),queue-updatedorstream-errorsay when to read the history again. Akeepalivecomes once connected, then every few seconds: read the history on the first one, since what happened before it is there. - To turn chunks into messages as the chat does, pipe them into
readUIMessageStream()from theaipackage. listConversationMessages()returns{ messages, streamCatchup }: the saved messages as AI SDKUIMessages, as the chat builds them, and the chunks of a reply still streaming. Show those chunks, then skip live chunks whoseseqis at moststreamCatchup.maxSeq, since they repeat them.runAgent()returnsrunId, the turn the call opens: messages of that run carry it asmetadata.turnId. A run that waits goes on in later turns of the conversation.- The stream stays open until you abort its
signalorbreak, and throws if the connection drops: stream again to resume. - An app reads only its own conversations. Turns a member opened elsewhere,
such as in the chat, show only their text, in the history, live and in the
agent’s next run: live, their other chunks arrive as empty
message-metadatachunks, soseqstays gapless. Turns your app ran as a member (see above) stay whole when it reads on its own. - Requires
"engines": { "twenty": ">=2.56.0" }.
ai.generate
Call a model from a logic function, without an agent
ai.generate
Call a model from a logic function, without an agent
ai.generate() calls a model from a logic function. Unlike
runAgent(), it needs no defineAgent(): the call carries its own
instructions, and opens no conversation. Use it for one-shot work such as
classifying, summarizing or extracting.inputis a string, or a list of{ role: 'user' | 'assistant', content }messages.instructions(optional) adds the caller’s system instructions.modelId(optional) picks the model. Without it, the call uses the workspace’s default model.responseFormat(optional) works as inrunAgent(). With{ type: 'json', schema }, the schema goes on the model request itself, so a JSON answer takes one request (plus tool steps when ascopegrants tools).scope(optional) lets the call use the database, as described below.
{ success, text, object, error, runId, usage }:textis the reply of a text response, andnullfor a JSON one.objectis the result of a JSON response, andnullotherwise.errorexplains a failed run, whensuccessisfalse. A run that fails resolves this way rather than throwing; a call that cannot start a run, such as one with invalid input, throws.runIdidentifies the recorded run, with its model, usage and credits.usageis{ inputTokens, outputTokens }: what the run spent, including the steps that finished before a failure.
scope, the call reads and writes no records. To let it use the
database, pass a scope, written like a role’s permissions:onChunk. The call still resolves
to the same result, once the last chunk was handed to onChunk. If the
stream’s end never arrives, it stops waiting once the result is in and 5 s
pass without a new chunk, and still hands over every chunk received by then:- The call follows the run through the same subscription as
streamConversation(): it subscribes first, waits until the subscription is live, then starts the run, so it misses no chunk. - Chunks are the chat’s own: pipe them into
readUIMessageStream()from theaipackage to build the message. signalaborts the call: it rejects with the abort error and closes the stream. The run itself goes on, and is recorded as usual.- Once the stream is live, a failure of it only stops the chunks: the call
still resolves with the run’s result, which is billed either way. The call
rejects when the subscription fails before it goes live, so the run never
starts, or when
onChunkthrows. - An app follows only its own runs, so
onChunkneeds an app token. - Requires
"engines": { "twenty": ">=2.56.0" }.
ai.generate() requires the AI permission flag on the app’s default role,
like runAgent().sendInboxMessage
Start or continue a conversation in members' chats
sendInboxMessage
Start or continue a conversation in members' chats
sendInboxMessage() posts a message from your app in the chats of one or more
workspace members. It can end on a tool call the member answers from the chat,
after which the conversation continues with Twenty’s assistant. See
Inbox for its options, the mention
helpers, and how to post from a front component.