# RevCent MCP Operation: `CreateFunction`

This document explains why and when to create a RevCent Function using the `CreateFunction` MCP operation.

Unlike the `EditFunction` documentation, this file does **not** go deep into every configuration field. `CreateFunction` is intentionally simple: it creates the Function shell, returns a `function_id`, and starts provisioning the secure execution environment. Detailed code, dependencies, event source, environment variables, and trigger settings are configured afterward with `EditFunction`.

Sources used:
- RevCent MCP operation schema for `CreateFunction`
- Companion RevCent MCP operation documentation/schema for `EditFunction`
- RevCent Knowledge Base: Functions — `https://kb.revcent.com/en/integrations/functions`

---

## Operation Summary

`CreateFunction` creates a new RevCent Function and returns a unique 20-character `function_id`.

A Function is a hosted JavaScript execution unit that runs custom code inside RevCent. Functions let you extend RevCent beyond standard built-in operations by writing custom business logic, integrating with third-party services, enriching event data, and controlling advanced workflows.

When a Function is created, RevCent provisions a unique secure sandboxed execution environment for that Function.

> Important: After creating a Function, provisioning may take a couple of minutes before the Function is fully ready for code execution, dependencies, or testing. Please tell the user to be patient, and wait at least 30 seconds before editing a newly created function with desired code/setting. If you try to edit a newly created function and get a provisioning error, wait 30 seconds and try again.

---

---

## Required Planning Reference: Review `EditFunction` Before Creating

Before calling `CreateFunction`, an MCP/AI client should review and understand the companion `EditFunction` documentation.

This is critical because `CreateFunction` does **not** define what the Function actually does. It only creates the Function shell and returns the `function_id`.

The real purpose, runtime behavior, trigger source, code, dependencies, environment variables, and output expectations are configured later with `EditFunction`.

In practical terms:

```text
CreateFunction = reserve/create the Function shell and get a function_id
EditFunction = configure what the Function actually does
```

Therefore, MCP/AI should not treat `CreateFunction` as a complete Function setup operation.

---

### Why `EditFunction` Must Be Understood First

A Function's purpose cannot be fully understood from `CreateFunction` alone.

The MCP should know the intended `EditFunction` configuration before creating the Function so it can choose an accurate name and description and avoid creating vague, unused, or incorrectly scoped Functions.

Before creating a Function, MCP should understand:

- Intended `event_source`
- Expected event/input data
- Expected callback output
- Whether the Function needs `function_code`
- Whether dependencies are needed
- Whether environment variables/secrets are needed
- Whether the Function will be enabled immediately or later
- Whether the Function will be triggered by account events, API/MCP, Email Templates, Payment Profiles, schedules, or Function URLs
- Whether the Function will be used as an AI Assistant or AI Voice Agent filter
- Whether the Function will be used as an AI Voice Agent pre-agent Function
- Whether custom arguments are needed
- Whether account event notations, filters, timing options, cron settings, or IP restrictions will be needed

Do not create a Function with a vague name like `New Function` unless the user explicitly wants a placeholder.

---

### MCP Planning Table

Use `EditFunction` as the planning reference before `CreateFunction`.

| Intended Function Purpose | Future `EditFunction` Settings MCP Should Already Understand |
|---|---|
| Account event automation | `event_source: "account_event"`, `account_event_notations`, `account_event_filters`, `timing_options`, account-event JSON URL for the item type |
| API/MCP direct Function | `event_source: "api_direct"`, `custom_arguments`, expected direct-call event body, callback response |
| AI Assistant filter Function | `event_source: "api_direct"`, filter item type, filter event data URL, exact `callback(null, "pass")` / `callback(null, "fail")` output |
| AI Voice Agent filter Function | `event_source: "api_direct"`, filter item type, filter event data URL, exact `pass` / `fail` output |
| AI Voice Agent pre-agent Function | `event_source: "api_direct"`, outbound/inbound pre-agent input data URL, JSON object response used as `pre_agent_function.response` |
| Email Template custom data Function | `event_source: "email_template"`, Email Template trigger input data, plain object output used as `custom_data` |
| Payment Profile Function | `event_source: "payment_profile"`, payment profile event data URL, response shape for routing/payment flow control |
| Function URL / endpoint | `event_source: "function_url"`, inbound request body, `ip_restricted`, `ip_whitelist`, authentication/validation strategy |
| Scheduled Function | `event_source: "schedule"`, `cron_expression`, `cron_timezone`, scheduled event data |
| Third-party integration Function | Dependencies, environment variables, outbound API behavior, retry/error strategy, expected callback result |

---

### CreateFunction Naming Depends on EditFunction Planning

The name and description created during `CreateFunction` should reflect the intended future configuration.

Bad:

```json
{
  "name": "Function"
}
```

Better:

```json
{
  "name": "AI Voice Agent - Filter - Declined Sale Eligibility",
  "description": "Will be configured with EditFunction as an api_direct filter Function for AI Voice Agent sale recovery. It will receive sale filter input data and return pass only if the sale is still eligible for an outbound call."
}
```

Better:

```json
{
  "name": "Email Template - Custom Data - Receipt Footer",
  "description": "Will be configured with EditFunction as an email_template Function that returns custom_data for receipt email templates."
}
```

Better:

```json
{
  "name": "Account Event - Slack Alert - Chargeback Created",
  "description": "Will be configured with EditFunction as an account_event Function triggered by chargeback.created. It will use Slack dependencies and environment variables to send an alert."
}
```

---

### CreateFunction Should Not Be Called Just Because a Function Might Be Useful

Because `CreateFunction` creates a persistent Function record, MCP should have a clear intended use before calling it.

Before creating, MCP should be able to answer:

```text
What will this Function do?
How will it be triggered?
What event/input data will it receive?
What should it return through callback?
What EditFunction fields will likely be needed?
What will attach to or call this Function?
```

If those answers are not known, MCP should first clarify or plan the Function using the `EditFunction` guide.

---

### Recommended MCP Sequence

```text
1. Read/understand the EditFunction guide.
2. Determine the intended event_source and trigger behavior.
3. Determine expected event/input data and output/callback behavior.
4. Determine whether dependencies or environment variables will be needed.
5. Choose a specific name and description based on that plan.
6. Call CreateFunction.
7. Wait for provisioning.
8. Call EditFunction to configure code, dependencies, environment variables, event source, and trigger settings.
9. Test with realistic input data.
10. Enable only after validation.
```

The `CreateFunction` call should be the first operational step, but not the first design step.


## Minimal Input

`CreateFunction` only needs a name.

```json
{
  "name": "Slack Alert - Sale Created"
}
```

Optional description:

```json
{
  "name": "Slack Alert - Sale Created",
  "description": "Sends a Slack message when a successful sale is created."
}
```

Required field:

| Field | Required | Purpose |
|---|---:|---|
| `name` | Yes | Unique Function name. |

Optional field:

| Field | Required | Purpose |
|---|---:|---|
| `description` | No, but highly recommended | Human-readable explanation of what the Function will do. |

> Although `description` is not required by the schema, adding a description is **highly recommended**. It helps developers, admins, and AI tooling understand what the Function is intended to do before it is configured, triggered, edited, or attached to another RevCent feature.

---

## What CreateFunction Actually Does

`CreateFunction` creates the Function record and returns the new Function ID.

It does **not** configure:

- Function code
- Event source / trigger type
- Dependencies
- Environment variables
- Custom arguments
- Account event notations
- Schedule settings
- Function URL settings
- Webhook behavior
- Payment profile behavior
- Email template custom data behavior
- AI Voice Agent pre-agent behavior
- AI Assistant or AI Voice Agent filter behavior

Those settings are configured after creation using `EditFunction`. Because of that, MCP/AI should review the `EditFunction` guide before creating a Function so the Function shell is created with an accurate name, description, and known future configuration plan.

---

## Provisioning Delay

When you create a Function, RevCent provisions a unique secure sandboxed execution environment for that Function.

This provisioning process may take a couple of minutes.

During that time:

- The `function_id` may already exist.
- You can store the ID for follow-up setup.
- Immediate execution or dependency testing may not be ready yet.
- Dependency installation and environment preparation may still be completing.
- If a trigger or test fails immediately after creation, wait a couple of minutes and retry after configuration is complete.

Recommended workflow:

1. Call `CreateFunction`.
2. Save the returned `function_id`.
3. Wait for provisioning to complete.
4. Use `EditFunction` to configure code, dependencies, environment variables, and trigger settings.
5. Test the Function with realistic payloads.
6. Enable it for production use.

---

# Why Create a Function?

Create a Function when you need custom logic that is not handled by standard RevCent configuration alone.

Functions are useful when you need to:

- Connect RevCent to any third-party API.
- Run custom JavaScript when an event happens.
- Transform data before sending it elsewhere.
- Generate dynamic data for Email Templates.
- Add custom filtering logic for AI Assistants or AI Voice Agents.
- Generate custom Handlebars data for AI Voice Agent instructions.
- Control advanced payment routing in a Next-Gen Payment Profile.
- Build a custom webhook receiver or URL endpoint.
- Run scheduled automation.
- Add custom logic into RevCent flows or operational processes.

---

## Common Reasons to Create a Function

### 1. Integrate RevCent with Third-Party Systems

Functions can make outbound internet requests and use supported dependencies, which means they can send data to external APIs.

Examples:

- Send sale data to a CRM.
- Post Slack alerts.
- Send SMS through Twilio.
- Send email through SendGrid or Mailchimp.
- Push fulfillment data to a warehouse.
- Send customer data to a marketing platform.
- Notify an analytics system.
- Call an external fraud or risk API.
- Sync data into a database.

Example purpose:

```text
Create a Function that sends successful sale details to a partner fulfillment API.
```

---

### 2. React to Account Events

Functions can run when specific RevCent account events occur.

Examples:

- Sale created.
- Customer created.
- Chargeback created.
- Shipment shipped.
- Subscription renewed.
- Trial expired.
- Fraud detection created.
- Invoice created.

Example purpose:

```text
Create a Function that runs when a chargeback is created and posts the details to Slack.
```

---

### 3. Generate Custom Data for Email Templates

Email Templates can use Functions as a `custom_data` source.

A Function can inspect the event item data and return a plain object. That returned object becomes available in the Email Template as:

```handlebars
{{custom_data.some_key}}
```

Example purpose:

```text
Create a Function that generates custom receipt content for a sale email template.
```

Example output from a Function:

```javascript
callback(null, {
  support_email: "support@example.com",
  custom_footer: "Thank you for being a customer."
});
```

Email Template usage:

```handlebars
<p>{{custom_data.custom_footer}}</p>
<p>Need help? Email {{custom_data.support_email}}</p>
```

---

### 4. Add Advanced Payment Logic

Functions can be used inside Next-Gen Payment Profiles through a Run Function node.

This allows custom payment-flow behavior such as:

- Choosing a gateway.
- Routing based on gateway history.
- Calling an external risk API.
- Parsing gateway responses.
- Returning a custom error.
- Deciding the next payment flow node.
- Running analytics or logging without pausing the payment flow.

Example purpose:

```text
Create a Function that checks an external risk API before choosing a payment gateway.
```

Important:

- Payment-profile Functions are advanced.
- If the payment flow waits for the Function response, the Function must respond quickly.
- Use `EditFunction` to configure the Function with `event_source: "payment_profile"`.

---

### 5. Create a Custom Function URL or Webhook Endpoint

Functions can be configured as externally callable endpoints.

Use this when an outside system needs to send data into RevCent.

Examples:

- Receive a partner webhook.
- Accept a form submission.
- Receive shipping status callbacks.
- Accept lead data from an external source.
- Build a lightweight custom endpoint.

Example purpose:

```text
Create a Function that receives partner webhook data and updates RevCent metadata.
```

Security considerations:

- Validate inbound payloads.
- Use IP restrictions where possible.
- Verify shared secrets or signatures when available.
- Do not trust external input.

---

### 6. Run Scheduled Automation

Functions can be configured to run on a schedule.

Examples:

- Daily revenue summary.
- Nightly data sync.
- Periodic cleanup.
- Scheduled Slack report.
- Scheduled CRM update.
- Batch processing.

Example purpose:

```text
Create a Function that sends a daily revenue summary to Slack every morning.
```

---

### 7. Create API-Direct or AI-Triggered Tools

Functions can be configured for direct triggering through API/MCP or AI.

Use this when you want a controlled callable operation that performs custom logic.

Examples:

- Normalize a payload.
- Generate a summary.
- Call an external service.
- Fetch enriched data.
- Perform a controlled internal workflow.
- Give AI access to a specific safe action.

Example purpose:

```text
Create a Function that AI can call to summarize a customer's recent activity.
```

When used as a normal API-direct Function, custom arguments can describe the values required at trigger time.

---

### 8. Filter AI Assistants or AI Voice Agents

An `api_direct` Function can also be used as a filter Function for AI Assistants and AI Voice Agents.

In this case, the Function receives item context based on `item_type` and `item_id`, then returns either:

```javascript
callback(null, "pass");
```

or:

```javascript
callback(null, "fail");
```

Use cases:

- Only allow an AI Assistant to run for eligible customers.
- Prevent an AI Voice Agent call for certain sale conditions.
- Check metadata before an AI workflow proceeds.
- Apply custom campaign, customer, or sale logic.

Example purpose:

```text
Create a Function that allows an AI Voice Agent to call only customers with eligible declined sales.
```

Important:

- Filter Functions should not use `custom_arguments`.
- They use the item context event body.
- They should return only `"pass"` or `"fail"`.

---

### 9. Generate AI Voice Agent Pre-Agent Content

A Function can be used as a pre-agent Function for AI Voice Agents.

Pre-agent Functions run immediately before an AI Voice Agent call begins. They can return custom JSON that becomes available to the AI Voice Agent instructions through Handlebars.

Example purpose:

```text
Create a Function that generates a product list and company name for AI Voice Agent instructions.
```

Example Function response:

```javascript
callback(null, {
  company_name: "Acme Inc.",
  product_list: [
    {
      name: "Product A",
      price: 29.99
    }
  ]
});
```

AI Voice Agent instruction usage:

```handlebars
Identify as {{pre_agent_function.response.company_name}}.

# Available Products
{{{toString pre_agent_function.response.product_list}}}
```

---

# Why Create First and Configure Later?

`CreateFunction` separates Function creation from Function configuration. However, MCP/AI should still understand the intended `EditFunction` configuration before creating the Function.

This is useful because the Function needs a unique `function_id` before it can be attached to:

- Email Templates
- AI Voice Agents
- Payment Profiles
- Account Events
- Schedules
- Function URLs
- API-direct triggers
- Filter Function settings
- External workflows

After the Function exists, the returned `function_id` can be used in other configuration steps.

---

# Recommended Naming Strategy

Because Functions can be used in many different ways, choose names that make the intended source and action clear.

Recommended pattern:

```text
<Source or Trigger> - <Action or Destination> - <Purpose>
```

Examples:

```text
Account Event - Slack Alert - Chargeback Created
Email Template - Custom Data - Receipt Personalization
Payment Profile - Gateway Decision - External Risk API
AI Voice Agent - Pre-Agent - Product List
AI Voice Agent - Filter - Declined Sale Eligibility
Schedule - Daily Report - Revenue Summary
Function URL - Partner Webhook - Fulfillment Update
API Direct - Customer Summary - AI Tool
```

Good names help:

- Humans identify what the Function does.
- AI tools choose the correct Function.
- Developers avoid attaching the wrong Function to a template, agent, flow, or payment profile.

---

# Recommended Description Strategy

Adding a description is highly recommended, even though the schema does not require it.

The description should explain what the Function is intended to do after it is configured.

A good description includes:

- Intended event source.
- Trigger conditions.
- Expected input data.
- Third-party systems involved.
- Expected output or response.
- Whether the Function is synchronous or asynchronous.
- Any dependency or environment variable expectations.

Example:

```text
Used as an AI Voice Agent pre-agent Function. Receives customer or sale item context and returns company_name and product_list for Handlebars in agent instructions.
```

Example:

```text
Used inside a Next-Gen Payment Profile Run Function node. Calls an external risk API and returns next_node_id or set_gateway_id to control payment routing.
```

Example:

```text
Account-event Function triggered when a chargeback is created. Sends chargeback details to Slack using SLACK_BOT_TOKEN and SLACK_CHANNEL_ID environment variables.
```

---

# CreateFunction Request Examples

## Minimal Function

```json
{
  "name": "My New Function"
}
```

## Function for Third-Party Webhook Integration

```json
{
  "name": "Account Event - Partner Webhook - Sale Created",
  "description": "Sends sale-created event data to a partner webhook. Configure code, axios dependency, and encrypted partner API key after creation."
}
```

Descriptions are especially important for integrations because they document the expected trigger, destination system, dependencies, and secrets before the Function is fully configured.

## Function for Email Template Custom Data

```json
{
  "name": "Email Template - Custom Data - Receipt",
  "description": "Returns custom_data for receipt Email Templates. Configure with event_source email_template after creation."
}
```

## Function for Payment Profile Decisioning

```json
{
  "name": "Payment Profile - Gateway Decision - Risk API",
  "description": "Runs inside a Next-Gen Payment Profile. Calls external risk API and returns gateway routing instructions."
}
```

## Function for AI Voice Agent Pre-Agent Data

```json
{
  "name": "AI Voice Agent - Pre-Agent - Product List",
  "description": "Generates company name and product list for AI Voice Agent instructions using Handlebars."
}
```

## Function for AI Voice Agent Filtering

```json
{
  "name": "AI Voice Agent - Filter - Sale Eligibility",
  "description": "Used as an api_direct filter Function. Receives sale item context and returns pass or fail."
}
```

## Function for Scheduled Automation

```json
{
  "name": "Schedule - Daily Report - Revenue Summary",
  "description": "Runs every morning after schedule configuration. Sends revenue summary to Slack."
}
```

---

# Output Schema

A successful `CreateFunction` response returns:

```json
{
  "api_call_id": "XXXXXXXXXXXXXXXXXXXX",
  "api_call_unix": 1740000000,
  "code": 1,
  "function_id": "XXXXXXXXXXXXXXXXXXXX",
  "result": "..."
}
```

Important returned field:

| Field | Description |
|---|---|
| `function_id` | The 20-character ID used to configure, edit, attach, trigger, or delete the Function. |

---

# After CreateFunction

After creating the Function, use `EditFunction` to configure the actual behavior.

Typical follow-up configuration includes:

- `enabled`
- `function_code`
- `event_source`
- `dependencies`
- `environment_variables`
- `account_event_notations`
- `account_event_filters`
- `timing_options`
- `cron_expression`
- `cron_timezone`
- `ip_restricted`
- `ip_whitelist`
- `custom_arguments`

The exact follow-up fields depend on the purpose of the Function.

---

# Implementation Checklist

Before calling `CreateFunction`:

1. Review the companion `EditFunction` documentation/schema.
2. Decide why the Function is needed.
3. Choose the intended event source or trigger type.
4. Identify the likely `EditFunction` fields that will be needed after creation.
5. Choose a clear unique name based on the future `EditFunction` configuration.
6. Write a description that explains the Function's future purpose. This is highly recommended even though it is optional in the schema.
7. Identify whether third-party dependencies will be needed.
8. Identify whether encrypted environment variables will be needed.
9. Plan what event body the Function will receive.
10. Plan what response the Function should return through `callback`.
11. Confirm whether the Function is a normal `api_direct` Function, an AI filter Function, or an AI Voice Agent pre-agent Function.
12. Call `CreateFunction`.
13. Save the returned `function_id`.
14. Allow a couple of minutes for provisioning.
15. Use `EditFunction` to configure code, dependencies, environment variables, and trigger behavior.
16. Test with realistic payloads before enabling production use.

---

# Quick Reference

Request:

```json
{
  "name": "Account Event - Slack Alert - Chargeback Created",
  "description": "Sends a Slack alert when a chargeback is created."
}
```

Response includes:

```json
{
  "function_id": "XXXXXXXXXXXXXXXXXXXX"
}
```

Before create:

```text
Review EditFunction so the MCP/AI understands the future configuration and purpose before creating the Function shell.
```

Next step:

```text
Use EditFunction with the returned function_id to configure code, event source, dependencies, environment variables, triggers, and output behavior.
```


---
Document Parent Directory
* [Operations](https://revcent.com/documentation/markdown/mcp/operation/index.md) - AI/MCP details and overviews for operations available within the RevCent MCP.