Custom actions

Let the AI agent do anything your systems allow, with one HTTP request or your own Python code.

A custom action is an operation the AI agent calls during a conversation. An API action makes one HTTP request. A Python action runs your own general-purpose code, so anything your systems allow can become an action:

  • Refund an order and restock its items in a retailer's ERP.
  • Open a claim in an insurer's policy system and return the claim number.
  • Check a telecom customer's line for faults and book a technician visit.
  • Check stock across a B2B supplier's warehouses and quote a delivery date.

Your workflow instructions tell the AI agent when to call each action.

There is no fixed catalog of operations. Anything with an API can be called, and anything with a website can be reached through browser automation. Where a platform requires an installed app or a sign-in, such as Shopify, its connector gives your code the platform's API. Call it with shopify_graphql or with the stored credentials from get_integration_credentials. See integration patterns for how the building blocks fit together.

Actions only run inside workflows

An action is not available to the AI agent until a workflow enables it. The workflow's instructions tell the AI agent when to call it.

When to use an action

Use an action when the AI agent should decide, mid-conversation, to fetch or change something. Other building blocks cover the other moments:

You needUse
The AI agent fetches or changes data when it decides toA custom action (this page)
Data fetched before the AI agent replies, to pick a workflow pathA condition provider
Context in the system prompt on every replyA prompt section
Code that runs when something happens (close, handoff, rating)An event handler
Code that runs on a scheduleA recurring job
A URL another system or a web page can callA custom HTTP endpoint
A human decision before the AI agent continuesHuman-in-the-loop decisions

How actions work

  1. You create an action: a name, a description and the request or code it runs.
  2. You enable it in a workflow.
  3. In the workflow's instructions, you tell the AI agent when to call it, for example "Step 3: call getOrderDetails".
  4. The AI agent calls the action with the arguments it collected.
  5. The action runs and returns data.
  6. The AI agent uses the returned data in its reply.

Choose a type

API actionPython action
Best forOne HTTP request, no logicMulti-step logic, data transformation, several API calls
SetupConfigure URL, method, headers and bodyWrite a Python function
Dynamic inputs$variableName in the path, query, headers or bodycontext["args"]["variableName"]
CredentialsStored in the action's configurationRead at runtime from secrets with get_secret
ExamplesFetch a record's status, check availabilityValidate before a write, combine data from several systems, tag conversations

Ask Copilot or any MCP client to build either type, or create them in the dashboard under Settings -> Automation -> Custom Actions. See Create and manage with Copilot or MCP.

Name and description

Both action types need a name and a description. The AI agent reads them to decide when to call the action.

Name

Use camelCase and be descriptive. The AI agent uses the name to understand the action. Names start with a letter or underscore and contain only letters, digits and underscores. The AI agent calls an action by its camelCase tool name, so an action saved as lookup_order is called lookupOrder. list_actions and get_action_details return it as toolName; use that name in workflow instructions.

  • getOrderDetails
  • checkServiceStatus
  • getStoreLocations

Description

A one-sentence explanation of what the action does. Write it so the AI agent understands when to call it.

Retrieves the customer's order status, items, and tracking link given an order ID.

API actions

An API action makes one HTTP request and returns the response to the AI agent. No code is required.

Request configuration

FieldDescription
Base URLThe root URL of your API (for example https://api.example.com)
PathThe endpoint path (for example /orders/$orderId)
MethodGET, POST, PUT, PATCH or DELETE
HeadersJSON headers, often for authentication
Query ParametersURL parameters (for example ?lang=en)
Request BodyJSON body for requests that send one
Request TimeoutHow long to wait before failing: 1 to 60 seconds, 30 by default

Every request also carries Content-Type: application/json and an x-octocom-conversation-id header with the current conversation's ID. Headers you configure override these.

Dynamic arguments

Use $variableName syntax to create dynamic inputs. Each variable becomes a required argument the AI agent must provide when calling the action.

GET /orders/$orderId
POST /stock
Body: { "productId": "$productId", "storeId": "$storeId" }

Use camelCase for variable names and choose names that convey meaning, such as orderId, customerEmail or accountNumber.

  • In the path, each value is URL-encoded into its own segment. An argument cannot add /, ? or #, cannot be . or .., and cannot change the request's host. A request whose arguments would change the host is not sent.
  • In headers and query parameters, a variable must be the whole value, for example {"X-Customer": "$customerId"}.
  • In the body, variables are always sent as text. If a body field needs a JSON value (an object, array, number, boolean or null), write it as $json:variableName:
POST /orders/search
Body: { "filters": "$json:filters", "limit": 10 }

The AI agent then provides JSON text and the action sends it parsed. Keys starting with $ and the keys __proto__, constructor and prototype are refused, so a customer cannot inject query operators through the chat. Only use $json: when your API needs structured input.

Network rules

  • Public endpoints only. API actions and their tests can call public HTTP and HTTPS endpoints. Private, loopback, link-local and internal-network destinations are blocked, including hostnames that resolve to those addresses. Expose an authenticated public API for the integration. If your API only accepts known IP addresses, use a Python action with proxy_request, which sends requests from a stable IP you can allowlist.
  • No redirects. API actions never follow redirects, so your headers and keys can never be carried to another host. A redirect response fails the call: configure the final URL.
  • Timeouts. The request timeout is 1 to 60 seconds, 30 by default.

These rules also apply to tests from the dashboard and MCP.

Credentials

Headers and query values are saved in the action's configuration, where anyone who can edit actions can read them. To keep an API key out of the configuration, use a Python action that reads it with get_secret.

Example: check service status

GET https://api.example.com/accounts/$accountId/service-status
Headers: { "x-api-key": "your-api-key" }

The AI agent provides the account ID and the action returns the account's current service status. The same shape works for stock levels, an appointment's state or a shipment's position: one GET, one response, no code.

Python actions

A Python action runs your function when the AI agent calls it, with whatever checks and steps your process needs. Use it when you need to:

  • Call several APIs and combine the results
  • Transform or validate data before or after an API call
  • Add safety checks, such as verifying a refund was offered before processing it
  • Handle complex input formats
  • Tag conversations or set metadata as side effects
  • Keep credentials in secrets instead of the action's configuration

Structure

Every Python action implements an execute_action function that receives a context object and returns data for the AI agent:

import requests

def execute_action(context):
    order_id = context["args"]["orderId"]

    response = requests.get(
        "https://api.example.com/orders",
        params={"id": order_id},
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()

The context object contains conversation data, the customer profile, business information and the arguments passed by the AI agent. See Python context for the full reference.

Return value. Whatever you return is sent back to the AI agent as context for its reply. Return structured data, such as dicts and lists, or clear error messages.

What your code can do

CapabilityHow
Call any HTTP APIUse requests with any method, headers and body, and stream large responses with stream=True. urllib.request.urlopen works too.
Send requests in parallelconcurrent.futures.ThreadPoolExecutor runs HTTP requests concurrently, up to max_workers at a time, or 8 when you don't set it.
Call from a fixed IPproxy_request and proxy_session send requests from Octocom's stable outbound IP, for APIs that only accept allowlisted addresses.
Use stored credentialsget_secret reads your API keys. get_integration_credentials returns the credentials of connected platforms.
Use connected platformsshopify_graphql runs any Shopify Admin GraphQL query or mutation. Order and subscription helpers cover other store and subscription platforms.
Use databases and sheetssql_server_query runs read-only SQL Server queries. The Google Sheets helpers read and write connected spreadsheets.
Work through a websiteopen_browser runs guarded, recorded browser steps from a saved action. See Browser automation.
Change the conversationBuilt-in helpers tag conversations, add notes, set metadata and hand off to your team. Return chat UI to show cards and confirmations in web chat.
Call Octocom itselfCall the REST API for your organization with the injected OCTOCOM_API_BASE_URL and OCTOCOM_ORG_API_KEY globals. The key is valid for this run only. See Python context.
Use AI, PDFs and messagingHelpers classify and summarize text with an LLM, render and read PDFs, and send emails and Slack notifications.
Share code and stateFunctions from Python modules are available without imports. The organization store shares state between runs and conversations.

Helpers need no import. See Python helpers for the full list.

Runtime and limits

RuntimeDetails
PythonPython 3.14 with the standard library, such as json, re, csv, hashlib, hmac and zoneinfo
Packagesrequests, beautifulsoup4, markdownify, openpyxl, python-dateutil and pytz. Other packages, such as pandas and numpy, are not available. Put shared code in Python modules.
Elapsed time120 seconds per run, including HTTP requests and browser waits
CPU time30 seconds of computation per run. Time spent waiting for the network does not count.
Outbound requestsUp to 10,000 per run, including the requests helpers make
MemoryLimited per run. Stream large downloads instead of loading them whole.
NetworkHTTP and HTTPS. Raw sockets and database drivers are not available: use sql_server_query for SQL Server, or put an HTTP API in front of other databases.
ThreadsCode runs on one thread. Use ThreadPoolExecutor to run HTTP requests in parallel.
FilesCode can write temporary files, for example under /mnt/data. Don't rely on them after the run.
StateEvery run starts with fresh globals. Keep lasting state in the organization store or in conversation metadata.
ArgumentsEvery argument arrives as a string. Convert numbers and parse JSON in your code.
Return valueMust be JSON-serializable: dicts, lists, strings, numbers, booleans or None.

The same limits apply when you test an action through Copilot, MCP, REST or the dashboard. Give each HTTP request a shorter timeout than the 120 seconds, so the action can handle a slow system itself. See Python context for how time is measured.

If the code raises an exception, the AI agent receives the error instead of a result. Outside test conversations, the Automation Execution Failed event also fires, so you can alert your team. A run that exceeds a resource limit fails and is not retried.

Optional arguments

Every argument is required by default: the AI agent must provide a value before it can call the action. Turn off Required next to an argument to make it optional. This is useful when the action can work with or without it, such as looking up orders by email with an optional order ID to narrow the result. Through MCP, list such arguments in optionalArguments.

When the AI agent leaves an optional argument out, its key is missing from context["args"] entirely, so read it with .get() instead of square brackets:

def execute_action(context):
    email = context["args"]["email"]           # required
    order_id = context["args"].get("orderId")  # optional: None when left out

    if order_id:
        return find_order(email, order_id)
    return list_orders(email)

context["args"]["orderId"] would raise a KeyError whenever the AI agent skips the argument. Say in the action's description when the optional argument should be provided, so the AI agent knows when to include it.

Showing UI in the chat

An action can also return cards, confirmations, order tracking, products and quick replies for the customer to see in web chat, under an octocom_ui key. See Chat UI from actions.

Asking a person before continuing

When the AI agent needs a human decision before it proceeds, an action can create an approval card for your team and let the AI agent continue once someone answers. See Human-in-the-loop decisions. If the person deciding works outside Octocom, follow the external decisions playbook.

Create and manage with Copilot or MCP

Describe the action and the system it calls. The agent writes the code, tests it and adds it to the workflow:

Ask Copilot or your AI agent

Create a Python action called getClaimStatus that looks up a claim by claim number and policyholder email in our claims API at https://claims.example.com, using the API key in the secret CLAIMS_API_KEY. Test it with claim CLM-48213 and jane@example.com, then enable it in our claims workflow.

Copilot and MCP clients manage actions with these tools:

ToolPurpose
list_actions, get_action_detailsFind actions and read their configuration or code
create_api_action, update_api_actionCreate or change an API action
create_python_action, update_python_actionCreate or change a Python action
test_api_action, test_python_actionRun an action with test arguments
list_action_versions, restore_action_versionRead the change history and restore an earlier version
archive_actionArchive an action so the AI agent can no longer use it
run_pythonRun Python once without saving it as an action

Two settings control where an action applies:

  • Businesses. By default an action is available to every business in the organization. Set allowedBusinessIds to limit it to specific businesses.
  • Tags. Up to eight free-form labels that help your team tell similar actions apart in the dashboard. They never affect which action the AI agent uses.

Testing

Every action can be tested before you use it in a live workflow. Tests run for real: API calls and helper writes take effect.

Testing API actions

  1. Open your API action in the dashboard.
  2. The test panel detects all $variables in your path, headers, query parameters and body.
  3. Fill in test values for each variable.
  4. Click Run Test.
  5. The dashboard makes the actual HTTP request and shows the response.

Testing Python actions

  1. Open your Python action in the dashboard.
  2. Fill in test values for each argument. Leave an optional argument blank to test the call without it. It is then missing from context["args"], just as when the AI agent leaves it out.
  3. Optionally enter a Conversation ID. This populates context["conversation"] with real conversation data (messages, metadata and so on). You can use any conversation from your dashboard: copy the ID or public ID from the conversation detail view.
  4. Click Run Test.
  5. The dashboard runs your code and shows the returned result.

Without a conversation ID, context["conversation"] is None. This is fine for actions that only use context["args"], but if your action reads conversation messages, metadata or tags, provide a conversation ID to test with real data.

Tip: To test iteratively, keep a test conversation open in another tab. Send messages to it to set up the conversation state you want, then use its ID in the test panel.

Running code without saving an action

Copilot and MCP clients can run Python once with the run_python tool, without creating an action. The code uses the same format as a Python action (execute_action(context)) and runs in the same runtime: built-in helpers, active Python modules, secrets and integrations such as shopify_graphql are all available. Pass a business ID, optional args and an optional conversation ID, exactly like a test. Browser automation helpers need a saved action.

Use it to try code before saving it as an action, to debug a helper, or to read data such as a store's orders for a date range. It is not a dry run: helper calls and API writes take effect. Each run gets its own API token, which is revoked when the run returns, and REST calls made with it are attributed to the user who ran the code.

Security and privacy

Your action's result is visible to the AI agent and may be surfaced to the customer. Only return data that is appropriate for the customer to see.

Reducing sensitive exposure

If exact values are confidential, return abstracted indicators instead:

# Instead of this:
return {"stock": 123}

# Return this:
return {"inStock": True}

Customer authentication

Consider requiring several matching identifiers when an action returns protected data:

  • Arguments: email + orderId
  • Your API filters with both values to verify ownership

Single-factor lookup (for example, only an order ID) is more convenient for the customer but easier to misuse if someone tries to manipulate the AI agent. Choose based on your security requirements. See Review your AI agent's security.

Best practices

  • Name clearly. getOrderDetails, not getData. The AI agent uses the name to understand the action.
  • Describe for the AI agent. Write descriptions as if briefing a teammate: "Retrieves order status and tracking info given an order ID."
  • Return only what's needed. Don't expose raw database records. Return what the customer should see.
  • Handle errors gracefully. Return clear error messages the AI agent can relay: {"error": "Order not found"}.
  • Use Python when logic is needed. If you need if/else, several API calls, data transformation or stored credentials, use a Python action.
  • Use API actions for simple lookups. One endpoint, one response and no transformation: an API action is simpler to maintain.
  • Set timeouts. Always pass a timeout to HTTP requests so a slow API cannot use up the action's budget.
  • Make writes safe to retry. A timed-out request does not prove the other system did nothing. Use the target system's idempotency support, or check its state before writing.

Examples

Combine data from two systems

This action calls an ERP for order data and a courier API for tracking events, then combines the results:

import requests

def execute_action(context):
    order_id = context["args"]["orderId"]
    email = context["args"]["email"]

    # Fetch order from ERP
    order_resp = requests.get(
        "https://erp.example.com/orders",
        params={"id": order_id, "email": email},
        headers={"Authorization": "Bearer ERP_KEY"},
        timeout=30,
    )

    if order_resp.status_code != 200:
        return {"error": "Order not found. Please check the order ID."}

    order = order_resp.json()

    # Fetch tracking from courier
    tracking = requests.get(
        "https://tracking.example.com/shipments",
        params={"tracking_number": order["trackingNumber"]},
        timeout=30,
    ).json()

    return {
        "orderId": order_id,
        "status": order["status"],
        "trackingNumber": order["trackingNumber"],
        "trackingEvents": tracking.get("events", []),
        "estimatedDelivery": order.get("estimatedDelivery"),
    }

Validate before a write

This action checks the record's state before processing a refund, and tags the conversation for analytics:

import requests

def execute_action(context):
    order_id = context["args"]["orderId"]
    reason = context["args"]["reason"]

    # Validate order state
    order = requests.get(
        "https://api.example.com/orders",
        params={"id": order_id},
        timeout=30,
    ).json()

    if order.get("isRefunded"):
        return {"error": "This order has already been refunded."}

    if not order.get("isCancellable"):
        return {"error": "This order cannot be refunded in its current state."}

    # Process the refund
    result = requests.post(
        "https://api.example.com/refund",
        json={"orderId": order_id, "reason": reason, "fullRefund": True},
        timeout=30,
    ).json()

    # Tag for analytics
    add_conversation_tag(context, "refunded")
    set_conversation_metadata(context, "refund_amount", str(result["amount"]))

    return {"success": True, "refundedAmount": result["amount"]}

Book an appointment with a stored key

This action reserves a slot in a booking system. The API key lives in a secret, and the conversation records the booking reference:

import requests

def execute_action(context):
    slot_id = context["args"]["slotId"]
    email = context["args"]["email"]
    notes = context["args"].get("notes", "")

    response = requests.post(
        "https://booking.example.com/api/appointments",
        json={"slotId": slot_id, "email": email, "notes": notes},
        headers={"Authorization": f"Bearer {get_secret('BOOKING_API_KEY')}"},
        timeout=20,
    )

    if response.status_code == 409:
        return {"error": "That time is no longer available. Offer the customer another slot."}
    response.raise_for_status()
    booking = response.json()

    set_conversation_metadata(context, "booking_reference", booking["reference"])
    return {
        "booked": True,
        "reference": booking["reference"],
        "startsAt": booking["startsAt"],
    }

On this page