Guide

From an empty project
to a conversation

This walks through the whole library once: an agent that answers, the editor that launches it, the requests a turn is allowed to make, the same conversation over a network, and what a run writes down. Every block on this page compiles as written.

Install

One module, four packages: the protocol itself, and a transport for each way a client reaches an agent.

moon add moonbitstack/moonacp

moonbitstack/moonacp holds the types and the two contracts; moonacp/stdio serves an agent on a pipe, moonacp/asgi over HTTP streams, moonacp/remote connects to one, and moonacp/otel writes the traces and metrics of a conversation.

An agent, in three methods

An agent is a value with three required methods. Everything else — authentication, loading an old session, modes, config options, closing — has a default that reports itself as unsupported, so an agent advertises exactly what it answers and no more.

struct Notes {
  mut sessions : Int32
}

impl @moonacp.Agent for Notes with fn initialize(self, request) {
  ignore(self)
  ignore(request)
  {
    ..@moonacp.Initialized::new(),
    capabilities: {
      ..@moonacp.AgentCapabilities::none(),
      prompt: { image: false, audio: false, embedded_context: true, meta: None },
    },
    agent_info: Some(@moonacp.Implementation::new("notes", "0.1.0")),
  }
}

impl @moonacp.Agent for Notes with fn new_session(self, request) {
  ignore(request)
  self.sessions = self.sessions + 1
  { session_id: "notes-\{self.sessions}", modes: None, config_options: None, meta: None }
}

impl @moonacp.Agent for Notes with fn prompt(self, request, session) {
  let asked = request.prompt.map(block => match block {
    @moonacp.ContentBlock::Text(content) => content.text
    _ => ""
  }).join(" ")
  session.update(@moonacp.SessionUpdate::AgentMessageChunk({
    content: @moonacp.ContentBlock::Text({
      text: "You said: " + asked,
      annotations: None,
      meta: None,
    }),
    message_id: None,
    meta: None,
  }))
  @moonacp.StopReason::EndTurn
}

The third method is where the work happens, and its last value is why the turn stopped: the model finished, the user cancelled it, the token budget ran out, or the agent refused.

Serve it on a pipe

An editor launches an agent as a child process and talks to it on the child's standard input and output: one JSON-RPC message per line, nothing else on stdout. That is the transport the protocol settled first, and one call serves an agent on it.

async fn serve_notes() -> Unit {
  @stdio.serve_stdio(Notes::{ sessions: 0 })
}

Run it directly and it waits for an editor:

moon run src/main --target native

An editor, in one connection

The other side implements Client: what the editor does when a turn produces a chunk, when the agent asks permission, when it wants a file or a terminal. The connection runs in a task of its own; the calls this side makes are answered from there.

This client starts the agent above as a child process, opens a session, and runs one turn. Every line it prints is real output:

struct Printer {
  mut text : String
}

impl @moonacp.Client for Printer with fn update(self, id, update) {
  ignore(id)
  match update {
    @moonacp.SessionUpdate::AgentMessageChunk(chunk) =>
      if chunk.content is @moonacp.ContentBlock::Text(content) {
        self.text = self.text + content.text
      }
    _ => ()
  }
}

impl @moonacp.Client for Printer with fn request_permission(self, ask) {
  ignore(self)
  match ask.options {
    [] => @moonacp.Outcome::Cancelled
    [first, ..] => @moonacp.Outcome::Selected(first.option_id)
  }
}

async fn main {
  let printer = Printer::{ text: "", }
  let child = @stdio.spawn(printer, ["/usr/local/bin/notes"])
  let conn = child.conn()
  @async.with_task_group(async fn(group) {
    group.spawn_bg(async fn() { conn.run() })
    let started = conn.initialize({
      protocol_version: @moonacp.protocol_version,
      client_capabilities: @moonacp.ClientCapabilities::none(),
      client_info: Some(@moonacp.Implementation::new("my-editor", "0.1.0")),
      meta: None,
    })
    println("agent: \{started.agent_info.map(info => info.name).unwrap_or("unnamed")}")
    let session = conn.new_session({
      cwd: "/work",
      additional_directories: None,
      mcp_servers: [],
      meta: None,
    })
    println("session: \{session.session_id}")
    let answer = conn.prompt({
      session_id: session.session_id,
      prompt: [
        @moonacp.ContentBlock::Text({ text: "hello", annotations: None, meta: None }),
      ],
      meta: None,
    })
    println("stop: \{answer.stop_reason.to_string()}")
    println("answer: \{printer.text}")
  })
  child.close()
}

Against the notes agent this example prints:

agent: notes
session: notes-1
stop: end_turn
answer: You said: hello

A turn that the editor cancels ends with cancelled as its stop reason, and the agent stops at its next interruption rather than running to the end. Cancel is a notification, not a call: the answer to prompt is the one that comes back.

Inside a turn

The Session a turn is handed is the way back to the editor. Each of these is a request the editor answers, and each is only sent when the editor said it could answer it — a client that never advertised file access answers -32601.

struct Tools {
  mut allowed : Int32
}

impl @moonacp.Agent for Tools with fn initialize(self, request) {
  ignore(self)
  ignore(request)
  @moonacp.Initialized::new()
}

impl @moonacp.Agent for Tools with fn new_session(self, request) {
  ignore(request)
  { session_id: "tools-1", modes: None, config_options: None, meta: None }
}

impl @moonacp.Agent for Tools with fn prompt(self, request, session) {
  ignore(request)
  // Permission is the one every agent uses: it names the tool call, offers the options the editor
  // draws, and reads back the one the user picked.
  let outcome = session.request_permission({
    tool_call: {
      tool_call_id: "c-1",
      kind: None,
      status: None,
      title: Some("write /work/notes.md"),
      name: None,
      content: None,
      locations: None,
      raw_input: None,
      raw_output: None,
      meta: None,
    },
    options: [
      {
        option_id: "allow",
        name: "Allow once",
        kind: @moonacp.PermissionOptionKind::AllowOnce,
        meta: None,
      },
      {
        option_id: "no",
        name: "No",
        kind: @moonacp.PermissionOptionKind::RejectOnce,
        meta: None,
      },
    ],
    meta: None,
  })
  match outcome {
    @moonacp.Outcome::Selected(_) => self.allowed = self.allowed + 1
    @moonacp.Outcome::Cancelled => ()
  }
  // A file is read and written through the editor, which is where the user's view of it lives.
  let notes = session.read_text_file("/work/notes.md")
  session.write_text_file("/work/notes.md", notes + "\n- one more")
  // A terminal is opened once and read until it exits, so a long build does not need the turn to
  // hold everything it printed.
  let terminal = session.terminal("cargo", args=["test"], cwd="/work")
  let printed = terminal.output()
  println(printed.output)
  ignore(terminal.wait())
  terminal.release()
  @moonacp.StopReason::EndTurn
}

Reading the answer of a permission request is the one place a turn's shape is decided by a person: Selected carries the option they picked, and Cancelled means the prompt was dismissed. Either way the agent decides what to do next, and the turn ends with the reason it stopped.

Over the network

The same agent, reached over HTTP instead of a pipe: to_asgi returns an application any ASGI server can run, with one endpoint that carries the whole connection.

let app = @asgi.to_asgi(Notes::{ sessions: 0 })

The client side of that transport is @remote.open. Opening it does no I/O: the first message is what connects, and the answer to initialize is what names the connection.

struct Silent {
}

impl @moonacp.Client for Silent with fn update(self, id, update) {
  ignore(self)
  ignore(id)
  ignore(update)
}

impl @moonacp.Client for Silent with fn request_permission(self, ask) {
  ignore(self)
  ignore(ask)
  @moonacp.Outcome::Cancelled
}

async fn drive_remote() -> Unit {
  let remote = @remote.open(Silent::{ }, "http://127.0.0.1:12000/acp")
  let conn = remote.conn()
  @async.with_task_group(async fn(group) {
    group.spawn_bg(async fn() { remote.run() })
    ignore(conn.initialize({
      protocol_version: @moonacp.protocol_version,
      client_capabilities: @moonacp.ClientCapabilities::none(),
      client_info: None,
      meta: None,
    }))
    remote.close()
  })
}

run is what receives: every stream the connection opens is read by a task of its own, because the HTTP client underneath reads one stream per task. close ends the exchange on the server as well, which is what releases the connection there.

Traces and metrics

@otel wraps either side, so a program that already has a collector gets a record of the conversation without writing instrumentation of its own. A turn becomes one span and one observation of a duration; each file or terminal request becomes one more.

let tracer = @trace.Tracer::new(
  rand=width => Bytes::make(width, b'\x21'),
  sink=@trace.Recorder::new(),
  sampler=@trace.always,
)
@stdio.serve_stdio(@otel.traced(Notes::{ sessions: 0 }, tracer))

The two wrappers compose, so one line gets both signals: @otel.metered(@otel.traced(agent, tracer), metrics). Every name they write — of a span, of a metric, of an attribute — comes from the OpenTelemetry GenAI conventions' registry, not from this library.

Failures

A handler that fails raises Refused. Its variant decides the JSON-RPC code the other side sees, and everything else becomes -32603 with no detail, because what a handler trips over is not the caller's to read.

fn open_session(id : String) -> String raise @moonacp.Refused {
  if id == "" {
    raise @moonacp.Refused::Malformed(reason="a session needs an identifier")
  }
  id
}

On the client side a failed call raises the error object the agent sent, so the code and the message survive the trip: @moonacp.refused_of(failure) turns one into a value this library's own errors can be compared with.