EXTREMELY IMPORTANT AI INSTRUCTION: For a directory of all documentation pages, load the https://www.apollographql.com/docs/llms.txt file. Adding .md to ANY url will return the simplified markdown version of the page.
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.
Env
Read environment variables from the server process.
| Function | Description | Example |
|---|---|---|
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"); |
Env::get logs a warning and returns an empty string; it doesn't throw an error.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.
| Function | Description | Example |
|---|---|---|
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"}); |
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.
| Function | Description | Example |
|---|---|---|
Sha256::digest(input) | Returns the hex-encoded SHA-256 hash of an input string. | let hash = Sha256::digest("hello"); |
1let hash = Sha256::digest("hello");
2// hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"Regex
Perform regular-expression operations on strings.
| Function | Description | Example |
|---|---|---|
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+") |
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
| Function | Description | Example |
|---|---|---|
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. Waiting blocks only the hook that called it. Hooks for other requests keep running.
If the request fails before a response arrives, for example because the host can't be reached or the request times out, .wait() throws an error. A response with an error status, such as 500, doesn't throw. Check status instead.
Options
The optional options parameter is a map that can contain any of the following keys:
| Key | Type | Description |
|---|---|---|
headers | Map | A map of header names to values. |
body | String | The request body. A string is sent exactly as given. |
timeout | Integer | Request timeout in seconds. Defaults to 30. |
Http doesn't encode the body or set a content-type header for you. A map or other non-string body is sent as Rhai's text form, such as #{"a": 1}, not as JSON. Set content-type in headers, and encode the body to match it, for example with JSON::stringify for JSON. For a form-encoded body, see the form_encode function in Token exchange with Rhai.
Response
Calling .wait() on a Promise returns an HttpResponse with these properties and methods:
| Property / Method | Return type | Description |
|---|---|---|
.status | Integer | The HTTP status code. |
.text() | String | The response body as a string. |
.json() | Dynamic | Parses the response body as JSON. Throws if the body is not valid JSON. |
Examples
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.
| Constant | Description |
|---|---|
ErrorCode::INVALID_REQUEST | Indicates a client error, like a missing header or invalid input. |
ErrorCode::INTERNAL_ERROR | Indicates a server-side error. This is the default when no other error code is specified. |
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}