MCP MCP — Java examples backed by real provider calls. java examples examples/mcp src/examples/java/mcp example MCP

These Java examples are real runnable files. Edit the source file first; this page is rebuilt from the checked-in example and its metadata header.

Java Native MCP Tools

Attaches a live MCP client directly to AxGen without a lossy function adapter.

Java
import dev.axllm.ax.*;
import java.util.*;

public final class NativeMCPToolsExample {
  public static void main(String[] args) {
    String key = Optional.ofNullable(System.getenv("OPENAI_API_KEY")).orElse(System.getenv("OPENAI_APIKEY"));
    String endpoint = System.getenv("MCP_URL");
    if (key == null || endpoint == null) throw new IllegalStateException("Set OPENAI_API_KEY and MCP_URL.");
    AxMCPClient mcp = new AxMCPClient(new AxMCPStreamableHTTPTransport(endpoint), Map.of("namespace", "inventory"));
    AxGen program = new AxGen(Ax.s("request:string -> answer:string"), Map.of("mcp", mcp));
    OpenAICompatibleClient llm = new OpenAICompatibleClient(Map.of("api_key", key, "model", "gpt-5.4-mini"));
    try {
      AxMCPClient.CatalogSnapshot catalog = mcp.inspectCatalog();
      System.out.println(Json.stringify(Map.of(
          "tools", catalog.tools().stream().map(tool -> tool.get("name")).toList(),
          "resources", catalog.resources(),
          "resourceTemplates", catalog.resourceTemplates())));
      System.out.println(Json.stringify(program.forward(llm, Map.of("request", "Reindex inventory."))));
    } finally {
      mcp.close();
    }
  }
}

Java MCP Resource Wake

Subscribes over real Streamable HTTP and lets AxEventRuntime wake an authenticated Agent automatically.

Java
import dev.axllm.ax.*;
import dev.axllm.ax.runtime.quickjs.*;
import java.util.*;
import java.util.concurrent.*;

public final class ResourceWakeAgentExample {
  public static void main(String[] args) throws Exception {
    String key=Optional.ofNullable(System.getenv("OPENAI_API_KEY")).orElse(System.getenv("OPENAI_APIKEY"));String endpoint=System.getenv("AX_MCP_ENDPOINT");if(key==null||endpoint==null)throw new IllegalStateException("Set OPENAI_API_KEY and AX_MCP_ENDPOINT.");boolean local=endpoint.startsWith("http://127.0.0.1");
    AxMCPStreamableHTTPTransport transport=new AxMCPStreamableHTTPTransport(endpoint,Map.of("ssrfProtection",Map.of("requireHttps",!local,"allowLocalhost",local,"allowPrivateNetworks",local)));AxMCPClient client=new AxMCPClient(transport,Map.of("namespace","inventory"));AxMCPEventSource source=new AxMCPEventSource(client,"inventory","tenant:demo","authenticated",AxMCPEventSource.all());AxAgent agent=Ax.agent("uri:string -> summary:string",Map.of("runtime",Map.of("language","JavaScript")));OpenAICompatibleClient llm=new OpenAICompatibleClient(Map.of("api_key",key,"model","gpt-5.4-mini"));CountDownLatch completed=new CountDownLatch(1);
    AxEventRuntime runtime=new AxEventRuntime(List.of(new AxEventRoute("resource-wake","wake",Map.of("types",List.of("mcp.resource.updated")),"inventory-agent",true,"strict",0))).registerTarget(new AxEventRuntime.Target("inventory-agent",(input,context)->{try(AxQuickJsCodeRuntime js=new AxQuickJsCodeRuntime()){Object output=agent.forward(llm,castMap(input),Map.of("runtime",js));System.out.println(Json.stringify(output));completed.countDown();return output;}}).mapInput((event,continuation)->Map.of("uri",castMap(event.data()).get("uri"))).retrySafety("idempotent")).addSource(source);runtime.start();if(!completed.await(60,TimeUnit.SECONDS))throw new IllegalStateException("Timed out waiting for an MCP resource notification");runtime.close();client.close();
  }
  @SuppressWarnings("unchecked")private static Map<String,Object> castMap(Object value){return(Map<String,Object>)value;}
}

Java MCP Task Continuation

Creates an owned continuation and resumes an AxFlow from real MCP progress and terminal task notifications.

Java
import dev.axllm.ax.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public final class TaskResumeFlowExample {
  public static void main(String[] args)throws Exception{
    String key=Optional.ofNullable(System.getenv("OPENAI_API_KEY")).orElse(System.getenv("OPENAI_APIKEY"));String endpoint=System.getenv("AX_MCP_ENDPOINT");if(key==null||endpoint==null)throw new IllegalStateException("Set OPENAI_API_KEY and AX_MCP_ENDPOINT.");boolean local=endpoint.startsWith("http://127.0.0.1");AxMCPStreamableHTTPTransport transport=new AxMCPStreamableHTTPTransport(endpoint,Map.of("ssrfProtection",Map.of("requireHttps",!local,"allowLocalhost",local,"allowPrivateNetworks",local)));AxMCPClient client=new AxMCPClient(transport,Map.of("namespace","inventory"));client.addNotificationListener(message->{if("notifications/progress".equals(message.get("method")))System.out.println("MCP task progress");});client.init();String taskId=String.valueOf(castMap(client.callTool("start_reindex",Map.of("scope","all")).get("task")).get("taskId"));
    AxFlow flow=Ax.flow(Map.of("id","reindex-flow")).execute("status",Ax.ax("taskId:string -> status:string")).returns(Map.of("status","status"));OpenAICompatibleClient llm=new OpenAICompatibleClient(Map.of("api_key",key,"model","gpt-5.4-mini"));AtomicInteger calls=new AtomicInteger();CountDownLatch completed=new CountDownLatch(1);AxEventRuntime.Target target=new AxEventRuntime.Target("reindex-flow",(input,context)->{Object output=flow.forward(llm,castMap(input));System.out.println(Json.stringify(output));if(calls.incrementAndGet()>=2)completed.countDown();return output;}).mapInput((event,continuation)->Map.of("taskId",continuation==null?castMap(event.data()).get("taskId"):continuation.metadata.get("taskId"))).waitFor("mcp.task","taskKey",Map.of("taskId",taskId)).retrySafety("idempotent");
    AxEventRuntime runtime=new AxEventRuntime(List.of(new AxEventRoute("task-start","wake",Map.of("types",List.of("app.task.started")),"reindex-flow",false,"strict",0),new AxEventRoute("task-progress","observe",Map.of("types",List.of("mcp.progress")),null,false,"strict",0),new AxEventRoute("task-resume","resume",Map.of("types",List.of("mcp.task.status")),"reindex-flow",false,"strict",0))).registerTarget(target);runtime.start();runtime.publish(new AxEventEnvelope("task-start","app://tasks","app.task.started",Map.of("taskId",taskId,"taskKey","inventory:"+taskId)),"tenant:demo","authenticated");AxMCPEventSource source=new AxMCPEventSource(client,"inventory","tenant:demo","authenticated",List.of());source.start(event->runtime.publish(event,source.identityScope(),source.trust()));System.out.println("Waiting for terminal MCP task notification "+taskId);if(!completed.await(60,TimeUnit.SECONDS))throw new IllegalStateException("Timed out waiting for the MCP task continuation");source.close();runtime.close();client.close();
  }
  @SuppressWarnings("unchecked")private static Map<String,Object> castMap(Object value){return(Map<String,Object>)value;}
}
Docs