Golem add http endpoint moonbit

From golemcloud/golem · View interactive version

Golem add http endpoint moonbit is an AI agent skill from the GitHub repository golemcloud/golem. Exposing a MoonBit Golem agent over HTTP with mount paths and endpoint annotations. Use when the user asks to add HTTP endpoints, REST APIs, or web interfaces to an agent.

How to use this skill

Skill file

Adding HTTP Endpoints to a MoonBit Golem Agent

Overview

Golem agents can be exposed over HTTP using code-first route definitions. This involves:

  1. Adding #derive.mount("/path/{param}") to the agent struct
  2. Annotating methods with #derive.endpoint(get="/path") (or post, put, delete)
  3. Adding an httpApi deployment section to golem.yaml (load the golem-configure-api-domain skill)

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

  1. Add #derive.mount("/path/{param}") to the agent struct (below #derive.agent)
  2. Add #derive.endpoint(get="/...") (or post, put, delete) to public methods
  3. Optionally add #derive.mount_auth(false) to disable authentication
  4. Optionally add #derive.mount_cors("https://origin.com") to configure CORS
  5. Add httpApi deployment to golem.yaml (see golem-configure-api-domain skill)
  6. 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:

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] {
  // ...
}

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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.