Golem add http endpoint scala

From golemcloud/golem · View interactive version

Golem add http endpoint scala is an AI agent skill from the GitHub repository golemcloud/golem. Exposing a Scala Golem agent over HTTP. Use when the user asks to add HTTP endpoints, mount an agent to a URL path, or expose agent methods as a REST API.

How to use this skill

Skill file

Adding HTTP Endpoints to a Scala Golem Agent

Overview

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

  1. Adding a mount parameter to @agentDefinition
  2. Annotating methods with @endpoint
  3. Adding an httpApi deployment section to golem.yaml (load the golem-configure-api-domain skill)

Related Skills

| Skill | When to Load |

|---|---|

| golem-http-params-scala | Path/query/header variable mapping, body mapping, supported types, response mapping |

| golem-make-http-request-scala | Making outgoing HTTP requests from agent code, especially when calling other Golem agent endpoints (required for correct JSON body formatting) |

| golem-add-http-auth-scala | Enabling authentication |

| golem-add-cors-scala | Configuring CORS allowed origins |

| golem-configure-api-domain | Setting up httpApi in golem.yaml, security schemes, domain deployments, and subdomain versus domain choices |

Steps

  1. Add mount = "/path/{param}" to @agentDefinition(...)
  2. Add @endpoint(method = "GET", path = "/...") to trait methods
  3. Add httpApi deployment to golem.yaml (see golem-configure-api-domain skill)
  4. Build and deploy

Mount Path

The mount parameter on @agentDefinition defines the base HTTP path. Path variables in {braces} map to constructor parameters defined in the class Id(...):

import golem.runtime.annotations.{agentDefinition, endpoint}
import golem.BaseAgent
import scala.concurrent.Future

@agentDefinition(mount = "/api/tasks/{name}")
trait TaskAgent extends BaseAgent {
  class Id(val name: String)

  // methods...
}

Constructor Parameter Naming in Scala

The path variable names must exactly match the class Id parameter names — do not use kebab-case in path variables. Use the same camelCase (or single-word) identifier that appears in the class Id:

// ✅ Correct — path variable matches parameter name exactly
@agentDefinition(mount = "/api/tasks/{taskName}")
trait TaskAgent extends BaseAgent {
  class Id(val taskName: String)
}

// ❌ Wrong — {task-name} does not match parameter name taskName
@agentDefinition(mount = "/api/tasks/{task-name}")
trait TaskAgent extends BaseAgent {
  class Id(val taskName: String)
}
// Named parameters with @id annotation
import golem.runtime.annotations.id

@agentDefinition(mount = "/api/catalog/{region}/{catalog}")
trait CatalogAgent extends BaseAgent {
  @id
  class CatalogParams(val region: String, val catalog: String)
}

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:

@agentDefinition(
  mount = "/tasks/{instance}",
  agentIdPath = "instance",
  createRoute = "/tasks/create"
)

For query addressing, use mount = "/tasks" and agentIdQuery = "instance" instead of agentIdPath. The ID is required; there is no optional binding or keyed fallback. ID mounts cannot bind constructor fields or combine with phantomAgent or ephemeral mode. The query ID name is reserved from explicit and implicit method query bindings and protocol controls. Keep fresh-per-request phantomAgent and ephemeral lifecycle policies on key mounts.

createRoute 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 @endpoint annotation marks a method as an HTTP endpoint. Specify the HTTP method and path:

@endpoint(method = "GET", path = "/items")
def listItems(): Future[List[Item]]

@endpoint(method = "POST", path = "/items")
def createItem(name: String, count: Int): Future[Item]

@endpoint(method = "PUT", path = "/items/{id}")
def updateItem(id: String, name: String): Future[Item]

@endpoint(method = "DELETE", path = "/items/{id}")
def deleteItem(id: String): Future[Unit]

Endpoint paths are relative to the mount path. Supported HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, CONNECT, TRACE, or any custom string.

For details on how path variables, query parameters, headers, and request bodies map to method parameters, load the golem-http-params-scala skill.

Durable Stream Route Customization

For a method with stream inputs or outputs, use @durableStreamSlot for each customized slot and @durableStreams for route policy:

@endpoint(method = "POST", path = "/events")
@durableStreamSlot(source = "input", slot = "input", name = "uploads")
@durableStreamSlot(
  source = "output",
  slot = "$result",
  name = "events",
  contentType = "application/vnd.example.events"
)
@durableStreams(
  maxConcurrentReadersPerStream = 8,
  maxAppendRequestsPerSecondPerStream = 25
)
def events(
  input: golem.schema.AgentStream[golem.UByte]
): Future[golem.schema.AgentStream[golem.UByte]]

Import durableStreamSlot and durableStreams from golem.runtime.annotations. If a method has multiple @endpoint annotations, identify the target in each durable-stream annotation with matching endpointMethod and endpointPath arguments.

Phantom Agents

Set phantomAgent = true to create a new agent instance for each HTTP request, enabling fully parallel processing:

@agentDefinition(
  mount = "/webhook/{agent-type}/{value}",
  phantomAgent = true
)
trait WebhookHandler extends BaseAgent {
  class Id(val value: String)
  // Each HTTP request gets its own agent instance
}

Custom Types

All types used in endpoint parameters and return values must have a zio.blocks.schema.Schema instance:

import zio.blocks.schema.Schema

final case class Task(id: String, title: String, done: Boolean) derives Schema

For collections, use List[T] instead of Array[T]. Array does not have automatic Schema derivation support.

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.

Scala Either[E, T] is mapped to the WIT result<T, E> type, with Right treated as Ok and Left as Err.

| Return Type | HTTP Status | Response Body |

|---|---|---|

| Future[Unit] | 204 No Content | empty |

| Future[T] | 200 OK | JSON-serialized T |

| Future[Option[T]] | 200 OK if Some, 404 Not Found if None | JSON T or empty |

| Future[Either[E, T]] | 200 OK if Right, 500 Internal Server Error if Left | JSON T or JSON E |

| Future[Either[E, Unit]] | 204 No Content if Right, 500 if Left | empty or JSON E |

| Future[Either[Unit, T]] | 200 OK if Right, 500 if Left | JSON T or empty |

| Future[Either[E, Option[T]]] | 200 OK if Right(Some), 404 Not Found if Right(None), 500 if Left | JSON T, empty, or JSON E |

| Future[golem.schema.UnstructuredBinary[M]] | 200 OK (Url → 307 redirect) | Raw binary with Content-Type |

| Future[golem.schema.UnstructuredText[L]] | 200 OK (Url → 307 redirect) | text/plain; charset=utf-8 (+ optional Content-Language) |

Raw Text and Binary Responses

Return golem.schema.UnstructuredText[L] or golem.schema.UnstructuredBinary[M] for a raw body

instead of JSON (L / M is String for no restriction, or a string-literal union allow-list

such as "image/png" | "image/jpeg"). The value inside Some / Right follows the same rules as a

top-level value, so an unstructured value nested in Option, Either[E, _], or

Either[E, Option[_]] is still sent raw. A guarded raw download (raw bytes / 404 / JSON error 500):

@endpoint(method = "GET", path = "/files/{name}")
def download(name: String): Future[Either[String, Option[golem.schema.UnstructuredBinary[String]]]]
import golem.schema.UnstructuredBinary

override def download(name: String): Future[Either[String, Option[UnstructuredBinary[String]]]] =
  Future.successful(name match {
    case "missing" => Right(None)                       // 404
    case "pending" => Left("pending")                   // 500, JSON body
    case _         => Right(Some(UnstructuredBinary.fromInline(Array[Byte](1, 2, 3), "image/png"))) // 200, raw bytes
  })

Generated RPC clients copy method signatures but not the imports of the agent trait's file, so use

the fully qualified golem.schema.UnstructuredBinary / golem.schema.UnstructuredText names in the

agent trait. Load golem-http-params-scala for unstructured request bodies.

Complete Example

import golem.runtime.annotations.{agentDefinition, agentImplementation, endpoint, header}
import golem.BaseAgent
import zio.blocks.schema.Schema
import scala.concurrent.Future

final case class Task(id: String, title: String, done: Boolean) derives Schema

@agentDefinition(mount = "/task-agents/{name}")
trait TaskAgent extends BaseAgent {
  class Id(val name: String)

  @endpoint(method = "GET", path = "/tasks")
  def getTasks(): Future[List[Task]]

  @endpoint(method = "POST", path = "/tasks")
  def createTask(title: String): Future[Task]

  @endpoint(method = "GET", path = "/tasks/{id}")
  def getTask(id: String): Future[Option[Task]]

  @endpoint(method = "POST", path = "/report")
  def submitReport(@header("X-Tenant") tenantId: String, data: String): Future[String]
}
import golem.runtime.annotations.agentImplementation
import scala.concurrent.Future

@agentImplementation()
final class TaskAgentImpl(private val name: String) extends TaskAgent {
  private var tasks: List[Task] = Nil

  override def getTasks(): Future[List[Task]] =
    Future.successful(tasks)

  override def createTask(title: String): Future[Task] = Future.successful {
    val task = Task(id = (tasks.length + 1).toString, title = title, done = false)
    tasks = tasks :+ task
    task
  }

  override def getTask(id: String): Future[Option[Task]] =
    Future.successful(tasks.find(_.id == id))

  override def submitReport(tenantId: String, data: String): Future[String] =
    Future.successful(s"Report from $tenantId: $data")
}
# 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.