Agents

Objeck is an agentic language and runtime. A function is a tool, a program is an MCP server, and an agent is a loop with limits. Each program below was compiled and run with v2026.11.4; the output shown is what it printed. None needs a key or a network.

Declare a tool

A doc comment with @tool is the whole declaration. The description is the comment, the JSON Schema comes from the parameter types, and @readonly becomes the MCP readOnlyHint. A call with a bad argument is refused before the function runs.

use API.MCP, Data.JSON;

class Tools {
  #~
  Greet a person.
  @tool
  @readonly
  @param name who to greet
  ~#
  function : Greet(name : String) ~ String {
    return "Hello, {$name}";
  }

  function : Main(args : String[]) ~ Nil {
    server := McpService->New("greeter", "1.0.0");
    Tools->McpTools(server);

    client := McpClient->InProcess(server);
    client->Initialize("demo", "1.0");
    each(tool in client->ListTools()) {
      "{$tool->GetName()}: {$tool->GetDescription()}"->PrintLine();
      tool->GetInputSchema()->ToString()->PrintLine();
    };
    client->CallTool("greet", "{\"name\":\"Ada\"}")->GetText()->PrintLine();
  }
}
$ obc -src tool.obs -lib gen_collect,json,net,net_server,cipher,misc,mcp
$ obr tool.obe
greet: Greet a person.
{"properties":{"name":{"description":"who to greet","type":"string"}},"required":["name"],"type":"object"}
Hello, Ada

Serve it

A program with @tool, @resource or @prompt functions needs no server code. obr --mcp starts it as an MCP server on standard input and output, which is what Claude Code and Claude Desktop launch; obr --mcp-http=8080 serves the same program over HTTP.

use API.MCP;

class Notes {
  #~
  Count the words in a text.
  @tool
  @readonly
  @param text the text to count
  ~#
  function : CountWords(text : String) ~ Int {
    return text->Split(" ")->Size();
  }

  #~
  A greeting for a name.
  @resource greeting://{name}
  ~#
  function : Greeting(name : String) ~ String {
    return "Hello, {$name}!";
  }

  function : Main(args : String[]) ~ Nil {
    "Serve me: obr --mcp serve.obe"->PrintLine();
  }
}
$ obc -src serve.obs -lib gen_collect,json,net,net_server,cipher,misc,mcp
$ obr serve.obe
Serve me: obr --mcp serve.obe

Here is a session with it. Each > is what a client sent and each < the reply, played against the real server by the same check that keeps this page honest:

$ obr --mcp serve.obe
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"claude","version":"1.0"}}}
< {"id":1,"jsonrpc":"2.0","result":{"capabilities":{"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}},"protocolVersion":"2025-11-25","serverInfo":{"name":"Notes","version":"1.0"}}}
> {"jsonrpc":"2.0","method":"notifications/initialized"}
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"count_words","arguments":{"text":"tools are plain functions"}}}
< {"id":2,"jsonrpc":"2.0","result":{"content":[{"text":"4","type":"text"}],"isError":false}}
> {"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"greeting://Ada"}}
< {"id":3,"jsonrpc":"2.0","result":{"contents":[{"mimeType":"text/plain","text":"Hello, Ada!","uri":"greeting://Ada"}]}}

To use it from Claude Code, give the client the command:

{"mcpServers":{"notes":{"command":"obr","args":["--mcp","/path/to/serve.obe"]}}}

Standard output carries the protocol, so a tool logs with ErrorLine(), which goes to standard error.

Call a server through a typed client

mcp_stubs asks a server for its tools and writes a class with one typed method per tool. A wrong argument is a compile error, and --check fails the build when the server's tools have changed since the client was generated. The generated class (about 100 lines) is in the sample's source; the page shows the part you write.

use API.MCP, Data.JSON;

class Shop {
  #~
  The price of an item.
  @tool
  @readonly
  @param item the item name
  ~#
  function : Price(item : String) ~ String {
    if(item->Equals("tea")) {
      return "4.50";
    };
    Runtime->Raise(Error->New("no such item: {$item}"));
    return Nil;
  }

  #~
  Order more of an item.
  @tool
  @param item the item name
  @param count how many
  @param rush rush delivery
  ~#
  function : Restock(item : String, count : Int, rush : Bool := false) ~ String {
    speed := "standard";
    if(rush) {
      speed := "rush";
    };
    return "{$count} x {$item}, {$speed} delivery";
  }
}

class Demo {
  function : Main(args : String[]) ~ Nil {
    server := McpService->New("shop", "1.0.0");
    Shop->McpTools(server);
    client := McpClient->InProcess(server);
    client->Initialize("demo", "1.0");

    # ShopClient was generated from the server's tools: one typed method per tool
    shop := ShopClient->New(client);
    shop->Price("tea")->PrintLine();
    shop->Restock("tea", 12, true)->PrintLine();
    if(shop->Price("coffee") = Nil) {
      shop->GetError()->PrintLine();
    };
    # shop->Price("tea", 3);   does not compile
  }
}
$ obc -src client.obs -lib gen_collect,json,net,net_server,cipher,misc,mcp
$ obr client.obe
4.50
12 x tea, rush delivery
Tool price failed: no such item: coffee

Run an agent

McpAgentTools hands a server's tools to an Agent. The effect hints decide who approves: the read-only add ran without a question, the destructive delete_file asked, and the approver said no, so its function never ran. A budget ends a run that would not stop. The model here is a ScriptedBackend, which replays fixed replies; swap in AnthropicBackend, OpenAIBackend, GeminiBackend or OllamaBackend and nothing else changes.

use API.MCP, API.Agent, Data.JSON, Collection;

class Tools {
  #~
  Add two integers.
  @tool
  @readonly
  ~#
  function : Add(a : Int, b : Int) ~ Int {
    return a + b;
  }

  #~
  Delete a file.
  @tool
  @destructive
  ~#
  function : DeleteFile(path : String) ~ String {
    return "deleted {$path}";
  }
}

class Cautious implements AgentApprover {
  New() {
  }

  method : public : Approve(call : AgentToolCall, tool : AgentTool) ~ Bool {
    "asked about {$call->GetName()}: no"->PrintLine();
    return false;
  }
}

class Demo {
  function : Main(args : String[]) ~ Nil {
    server := McpService->New("tools", "1.0.0");
    Tools->McpTools(server);
    client := McpClient->InProcess(server);
    client->Initialize("agent", "1.0");
    registry := ToolRegistry->New();
    McpAgentTools->AddAll(registry, client);

    # a scripted model: no key, no network
    calls := Vector->New()<AgentToolCall>;
    calls->AddBack(AgentToolCall->New("1", "add", JsonParser->TextToElement("{\"a\":17,\"b\":25}")));
    calls->AddBack(AgentToolCall->New("2", "delete_file", JsonParser->TextToElement("{\"path\":\"old.txt\"}")));
    script := Vector->New()<AgentReply>;
    script->AddBack(AgentReply->AskAll(calls));
    script->AddBack(AgentReply->Say("The sum is 42. I left old.txt alone."));

    agent := Agent->New(ScriptedBackend->New(script), registry);
    agent->SetApprover(Cautious->New())->SetApproveUnlessReadOnly(true);
    agent->SetBudget(AgentBudget->New()->SetMaxSteps(5)->SetMaxToolCalls(4));

    result := agent->Run("Add 17 and 25, then delete old.txt");
    each(step in result->GetSteps()) {
      each(r in step->GetResults()) {
        "{$r->GetToolName()}: {$r->GetStatus()} - {$r->GetContent()}"->PrintLine();
      };
    };
    "{$result->GetText()} ({$result->GetStopReason()})"->PrintLine();
  }
}
$ obc -src agent.obs -lib gen_collect,json,net,net_server,cipher,misc,mcp,agent,mcp_agent
$ obr agent.obe
asked about delete_file: no
add: ok - 42
delete_file: refused - Error: the user declined to run 'delete_file'
The sum is 42. I left old.txt alone. (completed)

Every run says why it ended in one word: completed, cancelled, deadline, budget_steps, budget_tool_calls, budget_tokens and so on. An AgentCancel token that any thread can trip stops a run between steps, and a tool in a bounded mode is abandoned at its time limit.

Limits for a block

AgentScope puts one set of limits, one cancel switch and one trace around every agent run inside a block, so a program does not hand a budget to each agent it makes. The limits are totals: the second question gets only what the first one left, and a run with nothing left is not started, so the model is not called at all.

use API.Agent, Data.JSON, Collection;

class Demo {
  @agent : static : Agent;

  function : Main(args : String[]) ~ Nil {
    script := Vector->New()<AgentReply>;
    script->AddBack(AgentReply->Ask("t1", "clock", "{}"));
    script->AddBack(AgentReply->Say("It is noon."));
    script->AddBack(AgentReply->Say("never asked"));

    registry := ToolRegistry->New();
    schema := JsonParser->TextToElement("{\"type\":\"object\",\"properties\":{}}");
    registry->Add(AgentTool->New("clock", "The time", schema,
      Func2Ref->New(Demo->Clock(JsonElement) ~ String)<JsonElement, String>));
    @agent := Agent->New(ScriptedBackend->New(script), registry);

    # two steps for everything inside the block, then no more model calls
    AgentScope->Run(AgentScope->New()->SetMaxSteps(2), Ask() ~ Nil);
  }

  function : Ask() ~ Nil {
    for(i := 1; i <= 3; i += 1;) {
      result := @agent->Run("question {$i}");
      "question {$i}: {$result->GetStopReason()}"->PrintLine();
    };
  }

  function : Clock(args : JsonElement) ~ String {
    return "12:00";
  }
}
$ obc -src scope.obs -lib agent,json,net,cipher,misc
$ obr scope.obe
question 1: completed
question 2: budget_steps
question 3: budget_steps

Local models, no key

OllamaBackend talks to a model on your own machine at localhost:11434. There is no key and nothing leaves the box. The program below runs the scripted model by default and a local one with obr local.obe ollama; the agent, the tool and the budget are the same code.

use API.Agent, Collection;

class Local {
  function : Main(args : String[]) ~ Nil {
    registry := ToolRegistry->New();
    registry->Add(AgentTools->Calculator());

    backend : ChatBackend;
    if(args->Size() > 0 & args[0]->Equals("ollama")) {
      # a local model: http://localhost:11434, no key, nothing leaves the machine
      backend := OllamaBackend->New("llama3.2");
    }
    else {
      script := Vector->New()<AgentReply>;
      script->AddBack(AgentReply->Ask("c1", "calculator", "{\"expression\":\"17 * 23\"}"));
      script->AddBack(AgentReply->Say("17 * 23 is 391."));
      backend := ScriptedBackend->New(script);
    };

    agent := Agent->New(backend, registry);
    agent->SetBudget(AgentBudget->New()->SetMaxSteps(4));
    result := agent->Run("What is 17 * 23?");
    "{$result->GetText()} ({$result->GetStopReason()}, {$result->GetToolCallCount()} tool call)"->PrintLine();
  }
}
$ obc -src local.obs -lib agent,json,net,cipher,misc
$ obr local.obe
17 * 23 is 391. (completed, 1 tool call)

The Ollama branch needs a running Ollama and a model that supports tools. The default run, shown above, needs neither.

Built to run agents

  • Collector-cooperative inference. An ONNX session running on a thread does not hold up the garbage collector, and a session can be shared by threads. Architecture and performance have the measurements.
  • Actors with supervision. System.Actor gives cooperating agents a mailbox each, links and monitors, and a Supervisor that restarts the ones that fail.
  • Telemetry. System.Telemetry records inference latency and predicts it from past runs, so a run can be accounted for.
  • Generational collector and a JIT. The runtime under the agents is the same one that runs the benchmarks.

Reference