Adding HTTP Endpoints to a MoonBit Golem Agent
Overview
Golem agents can be exposed over HTTP using code-first route definitions. This involves:
- Adding
#derive.mount("/path/{param}")to the agent struct - Annotating methods with
#derive.endpoint(get="/path")(orpost,put,delete) - Adding an
httpApideployment section togolem.yaml(load thegolem-configure-api-domainskill)
Related Skills
| Skill | When to Load |
|---|---|
| golem-add-agent-moonbit | Creating a new agent from scratch before adding HTTP endpoints |
| golem-http-params-moonbit | Path/query/header variable mapping, body mapping, supported types, response mapping |
| golem-configure-api-domain | Setting up httpApi in golem.yaml, security schemes, domain deployments, and subdomain versus domain choices |
Steps
- Add
#derive.mount("/path/{param}")to the agent struct (below#derive.agent) - Add
#derive.endpoint(get="/...")(orpost,put,delete) to public methods - Optionally add
#derive.mount_auth(false)to disable authentication - Optionally add
#derive.mount_cors("https://origin.com")to configure CORS - Add
httpApideployment togolem.yaml(seegolem-configure-api-domainskill) - Build and deploy
Mount Path
The #derive.mount("/path") annotation on the agent struct defines the base HTTP path. Path variables in {braces} map to constructor parameters:
#derive.agent
#derive.mount("/api/tasks/{task_name}")
struct TaskAgent {
task_name : String
mut tasks : Array[TaskInfo]
}
fn TaskAgent::new(task_name : String) -> TaskAgent {
{ task_name, tasks: [] }
}
Rules:
- Path must start with
/ - On a key mount, every user-supplied identity parameter must appear as a
{variable}in the mount path (using the parameter name) - On a key mount, every ordinary
{variable}must match a user-supplied identity parameter. Host-injectedPrincipaland@config.Config[T]parameters are excluded; do not bind them in the mount path. - Catch-all
{*rest}variables are not allowed in mount paths
Required Agent ID Mounts and Creation
Use an ID mount to address an existing durable, non-router agent without constructor inputs in the URL:
#derive.mount("/tasks/{instance}")
#derive.mount_agent_id(path = "instance")
#derive.mount_create("/tasks/create")
For query addressing, use #derive.mount("/tasks") and #derive.mount_agent_id(query = "instance"). The ID is required; there is no optional binding or keyed fallback. ID mounts cannot bind constructor fields or combine with #derive.mount_phantom(true) or ephemeral mode. The query ID name is reserved from explicit and implicit method query bindings and protocol controls. Keep fresh-per-request phantom and ephemeral lifecycle policies on key mounts.
#derive.mount_create declares a full exact POST path, not a mount suffix, and requires an ID mount. Only literals and system variables are allowed in this path. Send a JSON object with one field per user-supplied constructor parameter, as an endpoint body has one field per method parameter, for example {"name": "first"}; an optional parameter may be left out. Other fields, such as env, config or keyed, are rejected with 400. The new agent has no key. Route authentication does not grant configuration authority. Use authorized operator REST creation or SDK creation for overrides. Creation inherits mount authentication/CORS, waits for the constructor, and returns 201 Created with agentId/agentFingerprint JSON and an ID-mounted Location. Current HTTP callers have no caller scope, even with authentication, so Idempotency-Key is ignored; retries create new unkeyed agents.
ID selection never creates an agent. File serving supports both key and ID mounts but is lookup-only: missing keys and unknown, deleted, wrong-type or wrong-environment IDs return terminal 404, without creation or handler fallback. Missing files on an existing target retain normal mapping fallback.
Endpoint Annotation
The #derive.endpoint(...) attribute marks a public method as an HTTP endpoint. Specify one HTTP method with its path:
#derive.endpoint(get="/items")
pub fn TaskAgent::list_items(self : Self) -> Array[Item] {
self.items
}
#derive.endpoint(post="/items")
pub fn TaskAgent::create_item(self : Self, name : String, count : UInt64) -> Item {
let item = { id: self.items.length().to_string(), name, count }
self.items.push(item)
item
}
#derive.endpoint(put="/items/{id}")
pub fn TaskAgent::update_item(self : Self, id : String, name : String) -> Item {
// ...
}
#derive.endpoint(delete="/items/{id}")
pub fn TaskAgent::delete_item(self : Self, id : String) -> Unit {
// ...
}
Endpoint paths are relative to the mount path.
Durable Stream Route Customization
For a method with stream inputs or outputs, add one #derive.durable_stream_slot per customized slot and one optional #derive.durable_streams route policy:
#derive.endpoint(post = "/events")
#derive.durable_stream_slot(input = "input", name = "uploads")
#derive.durable_stream_slot(
output = "$result",
name = "events",
content_type = "application/vnd.example.events",
)
#derive.durable_streams(
max_concurrent_readers_per_stream = 8,
max_append_requests_per_second_per_stream = 25,
)
pub fn MyAgent::events(
self : Self,
input : @schema.AgentStream[Byte],
) -> @schema.AgentStream[Byte] {
// ...
}
inputoroutputselects a canonical top-level stream slot.$resultis the only implicit result selector.namechanges the public URL and OpenAPI name; the canonical name is no longer accepted in the public URL.content_typeis allowed only for a direct@schema.AgentStream[Byte]slot and must be a concrete non-text, non-JSON MIME type without parameters or wildcards. JSON-shaped streams stayapplication/json; do not usetext/plainfor@schema.AgentStream[String]. SSE still usestext/event-streamand base64 data.- Reader and append limits must be positive and no greater than the installation maximums. Omitted values use the registry installation defaults.
- Limits are maintained per route and worker-service node, not as a cluster-wide quota.
Query Parameters
Specified in the endpoint path using ?key={var} syntax:
#derive.endpoint(get="/search?q={query}&limit={max_results}")
pub fn MyAgent::search(self : Self, query : String, max_results : UInt64) -> Array[SearchResult] {
// query and max_results are extracted from the URL query string
}
Header Variables
Map HTTP headers to method parameters using #derive.endpoint_header("Header-Name", "param_name"):
#derive.endpoint(post="/data")
#derive.endpoint_header("X-Request-Id", "request_id")
pub fn MyAgent::submit_data(self : Self, request_id : String, payload : String) -> String {
// request_id comes from the X-Request-Id header, payload from the JSON body
}
Authentication
Disable authentication on a mount with #derive.mount_auth(false):
#derive.agent
#derive.mount("/public/{name}")
#derive.mount_auth(false)
struct PublicAgent {
name : String
}
CORS
Configure allowed CORS origins with #derive.mount_cors(...):
#derive.agent
#derive.mount("/api/{name}")
#derive.mount_cors("https://app.example.com", "https://other.example.com")
struct ApiAgent {
name : String
}
Multiple origins can be specified as separate string arguments.
POST Request Body Mapping
User-supplied method parameters not bound to path variables, query parameters, or headers are body parameters. Ordinary structured parameters are populated from a JSON object with body parameter names as top-level fields:
#derive.endpoint(post="/items/{id}")
pub fn MyAgent::update_item(self : Self, id : String, name : String, count : UInt64) -> Item {
// id from path, name and count from JSON body: { "name": "Widget", "count": 5 }
}
A single object parameter named payload still needs wrapping: {"payload": {"name": "Widget", "count": 5}}. Do not include path/query/header parameters in the body. Unstructured text and binary parameters instead consume the raw body. Load golem-http-params-moonbit for those restrictions and the separate CLI positional/native-literal rules.
Custom Types
All types used in endpoint parameters and return values must be annotated with #derive.golem_schema:
#derive.golem_schema
pub(all) struct Task {
id : String
title : String
done : Bool
} derive(ToJson, @json.FromJson)
#derive.golem_schema
pub(all) enum Priority {
Low
Medium
High
} derive(Eq, ToJson, @json.FromJson)
Return Type to HTTP Response Mapping
Golem maps method return types to HTTP status codes and response bodies according to the table below. This mapping is currently not configurable.
| Return Type | HTTP Status | Response Body |
|---|---|---|
| Unit (no return) | 204 No Content | empty |
| T (any type) | 200 OK | JSON-serialized T |
| T? (Option[T]) | 200 OK if Some, 404 Not Found if None | JSON T or empty |
| Result[T, E] | 200 OK if Ok, 500 Internal Server Error if Err | JSON T or JSON E |
| Result[Unit, E] | 204 No Content if Ok, 500 if Err | empty or JSON E |
| Result[T?, E] | 200 OK if Ok(Some), 404 Not Found if Ok(None), 500 if Err | JSON T, empty, or JSON E |
| @schema.UnstructuredBinary[M] | 200 OK (Url → 307 redirect) | Raw binary with Content-Type |
| @schema.UnstructuredText[L] | 200 OK (Url → 307 redirect) | text/plain; charset=utf-8 (+ optional Content-Language) |
Raw Text and Binary Responses
Return @schema.UnstructuredText[L] or @schema.UnstructuredBinary[M] for a raw body instead of
JSON. The type argument implements @schema.AllowedLanguages / @schema.AllowedMimeTypes; use
@schema.AnyLanguage / @schema.AnyMimeType for no restriction. The value inside Some / Ok
follows the same rules as a top-level value, so an unstructured value nested in T?,
Result[T, E], or Result[T?, E] is still sent raw. A guarded raw download (raw bytes / 404 /
JSON error 500):
///|
pub(all) struct ReportMimeTypes {}
///|
impl @schema.AllowedMimeTypes for ReportMimeTypes with fn mime_types() {
["text/csv"]
}
///|
/// Download a CSV report (`ReportAgent` has a `reports : Map[String, String]` field)
#derive.endpoint(get="/report/{name}")
pub fn ReportAgent::report(
self : Self,
name : String,
) -> Result[@schema.UnstructuredBinary[ReportMimeTypes]?, String] {
match self.reports.get(name) {
None => Ok(None) // 404
Some(csv) if csv.is_empty() => Err("report \{name} is pending") // 500, JSON body
Some(csv) =>
Ok(Some(@schema.UnstructuredBinary::inline(@utf8.encode(csv), mime_type="text/csv"))) // 200, raw bytes
}
}
Load golem-http-params-moonbit for unstructured request bodies.
Complete Example
///|
/// Priority level for tasks
#derive.golem_schema
pub(all) enum Priority {
Low
Medium
High
} derive(Eq, ToJson, @json.FromJson)
///|
/// A task record
#derive.golem_schema
pub(all) struct Task {
id : String
title : String
priority : Priority
mut done : Bool
} derive(ToJson, @json.FromJson)
///|
/// A task management agent exposed over HTTP
#derive.agent
#derive.mount("/task-agents/{name}")
#derive.mount_auth(false)
struct TaskAgent {
name : String
mut tasks : Array[Task]
}
///|
fn TaskAgent::new(name : String) -> TaskAgent {
{ name, tasks: [] }
}
///|
/// List all tasks
#derive.endpoint(get="/tasks")
pub fn TaskAgent::get_tasks(self : Self) -> Array[Task] {
self.tasks
}
///|
/// Create a new task
#derive.endpoint(post="/tasks")
pub fn TaskAgent::create_task(self : Self, title : String, priority : Priority) -> Task {
let task = {
id: self.tasks.length().to_string(),
title,
priority,
done: false,
}
self.tasks.push(task)
task
}
///|
/// Get a task by ID
#derive.endpoint(get="/tasks/{id}")
pub fn TaskAgent::get_task(self : Self, id : String) -> Task? {
self.tasks.iter().find_first(fn(t) { t.id == id })
}
///|
/// Mark a task as complete
#derive.endpoint(post="/tasks/{id}/complete")
pub fn TaskAgent::complete_task(self : Self, id : String) -> Task? {
for t in self.tasks {
if t.id == id {
t.done = true
return Some(t)
}
}
None
}
# golem.yaml (add to existing file)
httpApi:
deployments:
local:
- subdomain: my-app # resolves to my-app.localhost:9006 by default
agents:
TaskAgent: {}
Key Constraints
#derive.mount("/path")is required on the agent struct before any#derive.endpoint(...)annotations can be used- Key mounts bind all user-supplied identity parameters via mount path variables; ID mounts bind only the agent ID. Host-injected Principal and Config parameters must not be bound
- Path/query/header variable names must exactly match method parameter names
- The endpoint path must start with
/ - Exactly one HTTP method must be specified per
#derive.endpoint(...)annotation - All custom types used in parameters or return values must have
#derive.golem_schema - Method names use
snake_case - Only
pub fnmethods can be exposed as HTTP endpoints - Never edit generated files —
golem_reexports.mbt,golem_agents.mbt, andgolem_derive.mbtare auto-generated bygolem build