Functions Reference

Built-in functions available in Rhai scripts


Apollo MCP Server provides several built-in function namespaces in the Rhai scripting environment. These functions are available in all Rhai scripts without any imports.

caution
Rhai scripts run as trusted server-side code. Restrict and review script changes, especially when using environment variables or outbound HTTP. For details, see the Rhai security guidance.

Env

Read environment variables from the server process.

FunctionDescriptionExample
Env::get(name)Returns the value of an environment variable or an empty string if the variable isn't set.let key = Env::get("API_KEY");
note
When an environment variable isn't set, Env::get logs a warning and returns an empty string; it doesn't throw an error.
Rhai
1let api_key = Env::get("API_KEY");
2let region = Env::get("AWS_REGION");
3
4fn on_execute_graphql_operation(ctx) {
5    ctx.headers["x-api-key"] = api_key;
6}

JSON

Parse and serialize JSON data.

FunctionDescriptionExample
JSON::parse(input)Parses a JSON string into a Rhai value (for example, a map, array, string, or number). Throws on invalid JSON.let obj = JSON::parse("{\"key\": \"value\"}");
JSON::stringify(value)Converts a Rhai value into a JSON string.let s = JSON::stringify(#{name: "apollo"});
Rhai
1// Parse a JSON string into an object
2let data = JSON::parse("{\"name\": \"Apollo\", \"version\": 1}");
3print(data.name);    // "Apollo"
4print(data.version); // 1
5
6// Convert a Rhai map to a JSON string
7let obj = #{status: "ok", count: 42};
8let json_string = JSON::stringify(obj);
9print(json_string);  // {"count":42,"status":"ok"}

Sha256

Compute SHA-256 cryptographic hashes.

FunctionDescriptionExample
Sha256::digest(input)Returns the hex-encoded SHA-256 hash of an input string.let hash = Sha256::digest("hello");
Rhai
1let hash = Sha256::digest("hello");
2// hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

Regex

Perform regular-expression operations on strings.

FunctionDescriptionExample
Regex::is_match(string, pattern)Returns true if the pattern matches anywhere in the string. Throws on invalid pattern.Regex::is_match("hello123", "\\d+")
Regex::replace(string, pattern, replacement)Replaces all matching patterns with the replacement string. Supports numbered ($1) and named ($name) capture groups. Throws on invalid pattern.Regex::replace("foo bar", "foo", "baz")
Regex::matches(string, pattern)Returns an array of all matching substrings or an empty array if there are no matches. Throws on invalid pattern.Regex::matches("abc 123 def 456", "\\d+")
Rhai
1// Check if a string contains digits
2let has_numbers = Regex::is_match("order-123", "\\d+");
3// has_numbers = true
4
5// Replace all matches
6let result = Regex::replace("foo bar foo", "foo", "baz");
7// result = "baz bar baz"
8
9// Use capture groups to reformat a date
10let reformatted = Regex::replace("2025-01-15", "(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
11// reformatted = "01/15/2025"
12
13// Use named capture groups
14let swapped = Regex::replace("John Smith", "(?P<first>\\w+) (?P<last>\\w+)", "$last, $first");
15// swapped = "Smith, John"
16
17// Find all matches
18let numbers = Regex::matches("abc 123 def 456", "\\d+");
19// numbers = ["123", "456"]

Http

Make HTTP requests from Rhai scripts.

Functions

FunctionDescriptionExample
Http::get(url)Sends a GET request to the given URL. Returns a Promise.Http::get("https://api.example.com/data")
Http::get(url, options)Sends a GET request with the provided options. Returns a Promise.Http::get(url, #{ headers: #{ "x-api-key": key } })
Http::post(url)Sends a POST request to the given URL. Returns a Promise.Http::post("https://api.example.com/data")
Http::post(url, options)Sends a POST request with the provided options. Returns a Promise.Http::post(url, #{ body: payload })

All Http functions return a Promise. Call .wait() on the promise to block until the response is available.

Options

The optional options parameter is a map that can contain any of the following keys:

KeyTypeDescription
headersMapA map of header names to values.
bodyStringThe request body.
timeoutIntegerRequest timeout in seconds. Defaults to 30.

Response

Calling .wait() on a Promise returns an HttpResponse with these properties and methods:

Property / MethodReturn typeDescription
.statusIntegerThe HTTP status code.
.text()StringThe response body as a string.
.json()DynamicParses the response body as JSON. Throws if the body is not valid JSON.

Examples

Rhai
1// Simple GET request
2let response = Http::get("https://api.example.com/health").wait();
3print(response.status); // 200
4print(response.text()); // "OK"
5
6// GET with custom headers
7let response = Http::get("https://api.example.com/data", #{
8    headers: #{
9        "authorization": "Bearer " + token,
10        "accept": "application/json"
11    },
12    timeout: 30
13}).wait();
14
15// Parse a JSON response
16let data = response.json();
17print(data.name); // access fields directly
18
19// POST with a JSON body
20let response = Http::post("https://api.example.com/items", #{
21    headers: #{
22        "content-type": "application/json"
23    },
24    body: JSON::stringify(#{ name: "new item", count: 1 })
25}).wait();
26
27if response.status != 201 {
28    throw #{
29        message: "Failed to create item: " + response.text(),
30        code: ErrorCode::INTERNAL_ERROR
31    };
32}

ErrorCode

These are the constants for structured error responses when using throw in lifecycle hooks. Go to Lifecycle Hooks for details about error handling.

ConstantDescription
ErrorCode::INVALID_REQUESTIndicates a client error, like a missing header or invalid input.
ErrorCode::INTERNAL_ERRORIndicates a server-side error. This is the default when no other error code is specified.
Rhai
1fn on_execute_graphql_operation(ctx) {
2    if ctx.incoming_request.headers["authorization"] == "" {
3        throw #{
4            message: "Authorization required",
5            code: ErrorCode::INVALID_REQUEST
6        };
7    }
8}