serve
Starts an HTTP server on the engine-allocated port, registers methods with the engine, and handles graceful shutdown.
Signature
rpc.serve(options: RpcServeOptions): Promise<RpcServer>
Parameters
| Parameter | Type | Description |
|---|---|---|
options.methods | Record<string, RpcMethodEntry> | Map of method names to definitions or handler functions |
Returns
Behavior
- Reads
HMCS_RPC_PORT,HMCS_MOD_NAME, andHMCS_PORTfrom environment variables (set by the engine when spawning the MOD service). - Creates an HTTP server listening on
127.0.0.1:{HMCS_RPC_PORT}. - Registers methods with the engine via
POST /rpc/registerwith exponential backoff (up to 10 retries, 100 ms → 5 s). - Installs a
SIGTERMhandler for graceful shutdown.
Error Responses
When a request arrives at the MOD's RPC server, it may return:
| Status | Condition |
|---|---|
| 400 | Invalid JSON or Zod validation failure |
| 404 | Unknown method name |
| 405 | Non-POST request |
| 500 | Handler threw an error |
Example
import { rpc } from "@hmcs/sdk/rpc";
import { z } from "zod";
const server = await rpc.serve({
methods: {
greet: rpc.method({
input: z.object({ name: z.string() }),
handler: async ({ name }) => ({ message: `Hello, ${name}!` }),
}),
ping: async () => ({ pong: true }),
},
});