### Hello World Agent with Static Content
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of running the 'hello-world' agent with a specified path and static content.
```bash
jbang agents@springai hello-world path=myfile.txt content="Hello World!"
```
--------------------------------
### Coverage Agent Example
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of invoking the 'coverage' agent to analyze target coverage for a specific module.
```bash
jbang agents@springai coverage target_coverage=90 module=core
```
--------------------------------
### AI-powered Hello World Agent with Claude
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of running the AI-powered 'hello-world-agent-ai' with Claude, specifying path and content.
```bash
jbang agents@springai hello-world-agent-ai path=greeting.txt content="a creative message" provider=claude
```
--------------------------------
### Install Artifacts for CI/Multi-Module Builds
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Use this command for CI or multi-module builds to install artifacts to the local repository, ensuring dependencies are available for subsequent modules.
```bash
./mvnw clean install -Pfailsafe
```
--------------------------------
### AI-powered Hello World Agent with Gemini
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of running the AI-powered 'hello-world-agent-ai' with Gemini, specifying path and content.
```bash
jbang agents@springai hello-world-agent-ai path=ai-info.txt content="information about AI agents" provider=gemini
```
--------------------------------
### Java Agent Client Example
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Example of using the AgentClient in a Spring Boot application to execute an agent goal. Requires Spring Boot and the agent client dependency.
```java
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.AgentClientResponse;
import java.nio.file.Path;
@Component
public class MyAgent implements CommandLineRunner {
private final AgentClient.Builder agentClientBuilder;
public MyAgent(AgentClient.Builder agentClientBuilder) {
this.agentClientBuilder = agentClientBuilder;
}
@Override
public void run(String... args) {
AgentClient client = agentClientBuilder.build();
AgentClientResponse response = client
.goal("Fix all failing tests in the project")
.workingDirectory(Path.of(System.getProperty("user.dir")))
.run();
System.out.println(response.isSuccessful() ? "Done!" : "Failed: " + response.getResult());
}
}
```
--------------------------------
### Example Snapshot Verification URL
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Specific example URL for verifying the maven-metadata.xml of the spring-ai-agent-model SNAPSHOT artifact.
```plaintext
https://central.sonatype.com/repository/maven-snapshots/org/springaicommunity/agents/spring-ai-agent-model/0.1.0-SNAPSHOT/maven-metadata.xml
```
--------------------------------
### Run Hello World Agent via JBang Catalog
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of running the 'hello-world' agent using the 'springai' catalog alias, specifying output path and content.
```bash
jbang agents@springai hello-world path=test.txt content="Hello World!"
```
--------------------------------
### AssertJ Assertion Example
Source: https://github.com/spring-ai-community/agent-client/blob/main/agents/code-coverage-agent/src/main/resources/META-INF/prompts/coverage-agent-prompt.txt
Use AssertJ for fluent and readable assertions. Static import `org.assertj.core.api.Assertions.assertThat` is recommended.
```java
assertThat(greeting.id()).isEqualTo(1)
```
--------------------------------
### Create and Run Agent Client (No Spring Boot)
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Instantiate an Agent model and client to run a command without Spring Boot. This example uses Claude and demonstrates basic agent interaction.
```java
ClaudeAgentModel model = ClaudeAgentModel.builder()
.defaultOptions(ClaudeAgentOptions.builder()
.model("claude-sonnet-4-5")
.yolo(true)
.build())
.build();
AgentClient client = AgentClient.create(model);
AgentClientResponse response = client.run("Create hello.txt with 'Hello from Agent Client!'");
```
--------------------------------
### Install Spring AI Agents Modules Locally
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Command to build and install Spring AI Agents modules locally using Maven, required for local development.
```bash
./mvnw clean install
```
--------------------------------
### Add JBang Catalog for Spring AI Agents
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
One-time setup command to add the Spring AI JBang catalog for easy access to agents.
```bash
jbang catalog add --name=springai \
https://raw.githubusercontent.com/spring-ai-community/agent-client/main/jbang-catalog.json
```
--------------------------------
### Verify JBang Catalog Installation
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Commands to verify that the Spring AI JBang catalog has been successfully added and to list available aliases.
```bash
jbang catalog list | grep springai
```
```bash
jbang alias list springai
```
--------------------------------
### Run AI-powered Agent with Claude via JBang Catalog
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of running an AI-powered agent ('hello-world-agent-ai') with Claude, requiring an API key and specifying output path and content.
```bash
export ANTHROPIC_API_KEY="your-key"
jbang agents@springai hello-world-agent-ai \
path=ai-test.txt \
content="a creative message" \
provider=claude
```
--------------------------------
### Mock AgentApi Implementation and AgentClient Usage
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Demonstrates how to create a lambda mock for the AgentApi interface for unit testing. It shows the setup of a mock API, instantiation of an AgentClient with this mock, and subsequent usage of the client to run a task and access its results and metadata.
```java
import org.springaicommunity.agents.model.AgentApi;
import org.springaicommunity.agents.model.AgentTaskRequest;
import org.springaicommunity.agents.model.AgentResponse;
import org.springaicommunity.agents.model.AgentGeneration;
import org.springaicommunity.agents.model.AgentGenerationMetadata;
import org.springaicommunity.agents.model.AgentResponseMetadata;
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.AgentClientResponse;
import java.util.List;
import java.util.Map;
// Lambda mock for unit tests
AgentApi mockApi = request -> {
String output = "Mock result for: " + request.goal();
AgentGenerationMetadata genMeta = new AgentGenerationMetadata("SUCCESS", Map.of());
AgentResponseMetadata meta = AgentResponseMetadata.builder()
.model("mock-model")
.sessionId("test-session-001")
.build();
return new AgentResponse(List.of(new AgentGeneration(output, genMeta)), meta);
};
AgentClient client = AgentClient.create(mockApi);
AgentClientResponse response = client.run("Test goal");
System.out.println(response.getResult()); // "Mock result for: Test goal"
System.out.println(response.isSuccessful()); // true
System.out.println(response.getMetadata().getModel()); // "mock-model"
```
--------------------------------
### Implement VendirContextAdvisor for External Context Injection
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
This advisor uses Vendir to declaratively fetch external documentation, API specs, or examples into the agent's working directory before execution. It implements the 'select context' strategy.
```java
import org.springaicommunity.agents.client.advisor.context.VendirContextAdvisor;
import org.springaicommunity.agents.client.AgentClient;
import java.nio.file.Path;
VendirContextAdvisor contextAdvisor = VendirContextAdvisor.builder()
.vendirConfigPath(Path.of("vendir.yml"))
.contextDirectory(".agent-context/vendir")
.autoCleanup(false)
.timeout(120) // seconds
.build();
AgentClient client = AgentClient.builder(model)
.defaultAdvisor(contextAdvisor)
.build();
// vendir.yml example:
// apiVersion: vendir.k14s.io/v1alpha1
// kind: Config
// directories:
// - path: docs
// contents:
// - path: spring-ai
// git:
// url: https://github.com/spring-projects/spring-ai
// ref: main
// subPath: docs
AgentClientResponse response = client
.goal("Implement a ChatClient wrapper following the official Spring AI patterns")
.workingDirectory(Path.of("/my/project"))
.run();
// Advisor populates context with sync metadata
Object synced = response.context().get("vendir.context.gathered"); // true/false
```
--------------------------------
### Run Launcher Directly via URL
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of executing the JBang launcher script directly from its URL, providing agent ID, output path, and content.
```bash
jbang https://raw.githubusercontent.com/spring-ai-community/agent-client/main/jbang/launcher.java \
hello-world \
path=greeting.txt \
content="Hello from Direct URL!"
```
--------------------------------
### Run Local JBang Launcher
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Command to run the JBang launcher script from the local file system after installing modules, useful for development.
```bash
jbang jbang/launcher.java hello-world path=test.txt
```
--------------------------------
### Use JBang Alias for Spring AI Agents
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Example of invoking the 'hello-world' agent using the 'springai@agents' alias, specifying output path and content.
```bash
jbang springai@agents hello-world path=test.txt content="Hello World!"
```
--------------------------------
### Handle Fragment Events and Storage Synchronization
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Listens for 'fragment' events and synchronizes slide changes via local storage. Uses `setTimeout` to defer event listener setup.
```javascript
let r=!0;setTimeout(()=>{e.on("fragment",e=>{r&&a(()=>({index:e.index,fragmentIndex:e.fragmentIndex}))})},0),window.addEventListener("storage",t=>{if(t.key===n&&t.oldValue&&t.newValue){const n=JSON.parse(t.oldValue),o=JSON.parse(t.newValue);if(n.index!==o.index||n.fragmentIndex!==o.fragmentIndex)try{r=!1,e.slide(o.index,{fragment:o.fragmentIndex,forSync:!0})}finally{r=!0}}});const i=()=>{const{reference:e}=o();void 0===e||e<=1?w(n):a(()=>({reference:e-1}))};window.addEventListener("pagehide",e=>{e.persisted&&window.addEventListener("pageshow",s),i()}),e.on("destroy",i)}
```
--------------------------------
### Add Agent Client Starter Dependency (Claude)
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Use this Maven dependency for Spring Boot auto-configuration with the Claude Code provider. The version should align with your project's Spring Boot setup.
```xml
org.springaicommunity.agents
agent-starter-claude
0.15.0
```
--------------------------------
### JBang Agent Client Usage
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Run agents using JBang without a build step. Add the catalog alias and invoke agents with specified parameters. Requires JBang to be installed.
```bash
# One-time: add the Spring AI catalog
jbang catalog add --name=springai \
https://raw.githubusercontent.com/spring-ai-community/agent-client/main/jbang-catalog.json
# Run a static hello-world agent
jbang agents@springai hello-world path=output.txt content="Hello from JBang!"
# Run an AI-powered agent with Claude (requires ANTHROPIC_API_KEY)
export ANTHROPIC_API_KEY="your-key"
jbang agents@springai hello-world-agent-ai \
path=greeting.txt \
content="a creative greeting about Spring AI" \
provider=claude
# Run with Gemini (requires GEMINI_API_KEY)
export GEMINI_API_KEY="your-key"
jbang agents@springai hello-world-agent-ai \
path=greeting.txt \
content="information about AI agents" \
provider=gemini
# Direct URL invocation (no catalog needed)
jbang https://raw.githubusercontent.com/spring-ai-community/agent-client/main/jbang/launcher.java \
hello-world path=test.txt content="Direct invocation!"
```
--------------------------------
### AgentClient Multi-step Refactoring
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Execute complex, multi-step refactoring tasks with AgentClient. This example modernizes code to newer Java features, specifying options like 'yolo(true)' and a longer timeout.
```java
// Multi-step refactoring
agentClient.goal("Modernize codebase to Java 25. " +
"Use records, switch expressions, text blocks")
.yolo(true)
.timeout(Duration.ofMinutes(20))
.run();
```
--------------------------------
### Run Hello World Sample Application
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Navigate to the hello-world sample directory and run the application using Maven.
```bash
cd samples/hello-world && mvn spring-boot:run
```
--------------------------------
### Build MCP Server Catalog and Initialize AgentClient
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Demonstrates how to build an McpServerCatalog from a JSON file or programmatically and then use it to configure an AgentClient. Shows default MCP server configuration and per-request server selection.
```java
McpServerCatalog catalog = McpServerCatalog.fromJson(Path.of("mcp-servers.json"));
AgentClient client = AgentClient.builder(claudeModel)
.mcpServerCatalog(catalog)
.defaultMcpServers("weather")
.build();
// Per-request MCP server selection
client.goal("Research topic").mcpServers("brave-search").run();
```
--------------------------------
### Run Sample Applications with Maven
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Use this command to run sample applications from their respective directories.
```bash
./mvnw spring-boot:run
```
--------------------------------
### Create and Run AgentClient Tasks
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Demonstrates building a provider model, creating an AgentClient, and running tasks using both one-liner and fluent goal() chain methods. Also shows how to configure default options via a builder.
```java
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.AgentClientResponse;
import org.springaicommunity.agents.claude.ClaudeAgentModel;
import org.springaicommunity.agents.claude.ClaudeAgentOptions;
import java.nio.file.Path;
import java.time.Duration;
// 1. Build the provider model
ClaudeAgentModel model = ClaudeAgentModel.builder()
.defaultOptions(ClaudeAgentOptions.builder()
.model("claude-sonnet-4-5")
.yolo(true)
.timeout(Duration.ofMinutes(5))
.build())
.build();
// 2a. Simplest form — one-liner convenience method
AgentClient client = AgentClient.create(model);
AgentClientResponse response = client.run("Create hello.txt with 'Hello from Agent Client!'");
System.out.println(response.getResult()); // task output text
System.out.println(response.isSuccessful()); // true / false
// 2b. Fluent goal() chain — like ChatClient.prompt()
AgentClientResponse response2 = client
.goal("Implement a Calculator class with add, subtract, multiply, divide")
.workingDirectory(Path.of("/my/project"))
.run();
System.out.println(response2.getResult());
// 2c. Builder with defaults applied to all requests
AgentClient configuredClient = AgentClient.builder(model)
.defaultWorkingDirectory(Path.of("/workspace"))
.defaultTimeout(Duration.ofMinutes(10))
.build();
AgentClientResponse response3 = configuredClient
.goal("Fix the failing JUnit tests")
.run();
// 2d. Mutate an existing client for a specialized use case
AgentClient quickClient = configuredClient.mutate()
.defaultTimeout(Duration.ofSeconds(30))
.build();
```
--------------------------------
### Run Context Engineering Sample Application
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Navigate to the context-engineering sample directory and run the application using Maven.
```bash
cd samples/context-engineering && mvn spring-boot:run
```
--------------------------------
### Hello World Agent with Default Content
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Demonstrates running the 'hello-world' agent when content is not explicitly provided, allowing the agent to use defaults.
```bash
jbang agents@springai hello-world path=myfile.txt
```
--------------------------------
### Basic Process Execution with zt-exec
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Demonstrates basic execution of a command with a timeout and output capture. Ensure zt-exec is available transitively.
```java
import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.ProcessResult;
// Execute a command with timeout
ProcessResult result = new ProcessExecutor()
.command("vendir", "--version")
.timeout(5, TimeUnit.SECONDS)
.readOutput(true)
.execute();
String output = result.outputUTF8();
int exitCode = result.getExitValue();
boolean success = exitCode == 0;
```
--------------------------------
### Run Full Build with Maven
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Standard Maven command to execute the full build, including compilation and tests.
```bash
./mvnw clean verify
```
--------------------------------
### Initialize and Use ClaudeAgentModel
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Demonstrates initializing ClaudeAgentModel with custom options, performing blocking and streaming calls, and registering tool use hooks. Ensure the working directory and timeout are set appropriately.
```java
import org.springaicommunity.agents.claude.ClaudeAgentModel;
import org.springaicommunity.agents.claude.ClaudeAgentOptions;
import org.springaicommunity.agents.model.AgentTaskRequest;
import org.springaicommunity.agents.model.AgentResponse;
import reactor.core.publisher.Flux;
import java.nio.file.Path;
import java.time.Duration;
ClaudeAgentModel model = ClaudeAgentModel.builder()
.workingDirectory(Path.of("/my/project"))
.timeout(Duration.ofMinutes(10))
.defaultOptions(ClaudeAgentOptions.builder()
.model("claude-sonnet-4-5")
.yolo(true)
.maxTurns(20)
.maxBudgetUsd(0.50)
.allowedTools(java.util.List.of("Bash", "Read", "Write"))
.appendSystemPrompt("Always follow our coding standards.")
.build())
.build();
// --- Blocking execution ---
AgentTaskRequest request = AgentTaskRequest.builder(
"Refactor the UserService to use the repository pattern",
Path.of("/my/project"))
.options(ClaudeAgentOptions.builder().model("claude-sonnet-4-5").yolo(true).build())
.build();
AgentResponse blockingResponse = model.call(request);
System.out.println(blockingResponse.getText());
// --- Reactive streaming ---
Flux stream = model.stream(request);
stream
.doOnNext(r -> System.out.print(r.getText()))
.doOnError(e -> System.err.println("Error: " + e.getMessage()))
.blockLast();
// --- Hook registration: block dangerous Bash commands ---
model.registerPreToolUse("Bash", input -> {
// Cast to HookInput.PreToolUseInput for argument access
// Return HookOutput.block("reason") or HookOutput.allow()
return null; // placeholder — actual HookOutput.allow() in real usage
});
// --- Check CLI availability ---
boolean available = model.isAvailable();
```
--------------------------------
### CLI Command with Prompt Separator
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Example of using the Claude CLI with the '--' separator to handle complex prompts containing special characters, preventing shell parsing issues.
```bash
claude --print -- "Create a directory called 'project', make README.md with info"
```
--------------------------------
### AgentClient.Builder Configuration
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Configure default options, working directory, timeout, advisors, and MCP server catalog for AgentClient instances.
```APIDOC
## AgentClient.Builder — Builder Configuration
`AgentClient.Builder` (returned by `AgentClient.builder(agentApi)`) configures defaults applied to every request dispatched by that client instance, including options, working directory, timeout, advisors, and MCP server catalog.
```java
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.DefaultAgentOptions;
import org.springaicommunity.agents.model.mcp.McpServerCatalog;
import org.springaicommunity.agents.model.mcp.McpServerDefinition;
import java.nio.file.Path;
import java.time.Duration;
// Portable options (provider-agnostic)
DefaultAgentOptions portableOptions = DefaultAgentOptions.builder()
.model("claude-sonnet-4-5")
.timeout(Duration.ofMinutes(5))
.workingDirectory("/my/project")
.build();
// MCP server catalog
McpServerCatalog catalog = McpServerCatalog.builder()
.add("brave-search", new McpServerDefinition.StdioDefinition(
"npx",
java.util.List.of("-y", "@modelcontextprotocol/server-brave-search"),
java.util.Map.of("BRAVE_API_KEY", System.getenv("BRAVE_API_KEY"))))
.add("weather-sse", new McpServerDefinition.SseDefinition("http://localhost:8080/sse"))
.build();
AgentClient client = AgentClient.builder(model)
.defaultOptions(portableOptions)
.defaultWorkingDirectory(Path.of("/workspace"))
.defaultTimeout(Duration.ofMinutes(8))
.mcpServerCatalog(catalog)
.defaultMcpServers("brave-search") // applied to every request
.build();
// Per-request MCP server override (unioned with defaults)
AgentClientResponse response = client
.goal("Search the web for Spring AI release notes and summarise")
.mcpServers("brave-search", "weather-sse")
.run();
```
```
--------------------------------
### Run HelloWorldAgentIT Integration Test
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Execute the HelloWorldAgentIT integration test for the hello-world-agent module.
```bash
./mvnw test -pl agents/hello-world-agent -Dtest=HelloWorldAgentIT
```
--------------------------------
### Build Antora Documentation Site
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Command to build the Antora documentation site for the project. The output will be located in the docs/target/antora/site/ directory.
```bash
./mvnw antora:antora -pl docs
```
--------------------------------
### Configure Gemini Agent Options and Client
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Configure Gemini CLI adapter options like model, temperature, and token limits. Instantiate the GeminiAgentModel and create an AgentClient.
```java
import org.springaicommunity.agents.gemini.GeminiAgentModel;
import org.springaicommunity.agents.gemini.GeminiAgentOptions;
GeminiAgentOptions geminiOptions = GeminiAgentOptions.builder()
.model("gemini-2.5-flash")
.timeout(java.time.Duration.ofMinutes(10))
.yolo(true)
.temperature(0.2)
.maxTokens(8192)
.build();
GeminiAgentModel geminiModel = new GeminiAgentModel(geminiOptions);
AgentClient client = AgentClient.create(geminiModel);
AgentClientResponse response = client
.goal("Write integration tests for the OrderService")
.workingDirectory(java.nio.file.Path.of("/my/project"))
.run();
System.out.println(response.getResult());
```
--------------------------------
### Agent Client Spring Boot Configuration
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Configure Agent Client behavior using application.yaml. This example shows settings for 'loose' mode and specific options for Claude Code, Codex, and Gemini providers.
```yaml
spring:
ai:
agents:
mode: loose # or strict
claude-code:
model: claude-sonnet-4-5
timeout: PT5M
yolo: true
codex:
model: gpt-5-codex
full-auto: true
gemini:
model: gemini-2.5-flash
yolo: true
```
--------------------------------
### Build Docker Image for Agents Runtime
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Command to build the Docker image for the agents runtime locally. This image includes necessary CLIs and JDK.
```bash
docker build -f Dockerfile.agents-runtime -t agents-runtime:local .
```
--------------------------------
### Configure AgentClient with Default Options and MCP Servers
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Use AgentClient.builder to set default options, working directory, timeout, and MCP server catalog. Defaults are applied to all requests unless overridden.
```java
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.DefaultAgentOptions;
import org.springaicommunity.agents.model.mcp.McpServerCatalog;
import org.springaicommunity.agents.model.mcp.McpServerDefinition;
import java.nio.file.Path;
import java.time.Duration;
// Portable options (provider-agnostic)
DefaultAgentOptions portableOptions = DefaultAgentOptions.builder()
.model("claude-sonnet-4-5")
.timeout(Duration.ofMinutes(5))
.workingDirectory("/my/project")
.build();
// MCP server catalog
McpServerCatalog catalog = McpServerCatalog.builder()
.add("brave-search", new McpServerDefinition.StdioDefinition(
"npx",
java.util.List.of("-y", "@modelcontextprotocol/server-brave-search"),
java.util.Map.of("BRAVE_API_KEY", System.getenv("BRAVE_API_KEY"))))
.add("weather-sse", new McpServerDefinition.SseDefinition("http://localhost:8080/sse"))
.build();
AgentClient client = AgentClient.builder(model)
.defaultOptions(portableOptions)
.defaultWorkingDirectory(Path.of("/workspace"))
.defaultTimeout(Duration.ofMinutes(8))
.mcpServerCatalog(catalog)
.defaultMcpServers("brave-search") // applied to every request
.build();
// Per-request MCP server override (unioned with defaults)
AgentClientResponse response = client
.goal("Search the web for Spring AI release notes and summarise")
.mcpServers("brave-search", "weather-sse")
.run();
```
--------------------------------
### Advanced Process Execution with zt-exec
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Shows advanced process execution including setting the working directory and environment variables. This pattern is mandatory for all process executions.
```java
import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.ProcessResult;
// Execute with working directory and environment
ProcessResult result = new ProcessExecutor()
.command("vendir", "sync", "--file", "vendir.yml")
.directory(workingDir.toFile())
.environment("VENDIR_CACHE_DIR", "/tmp/cache")
.timeout(300, TimeUnit.SECONDS)
.readOutput(true)
.execute();
```
--------------------------------
### AgentClient Configuration with Options
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Configure AgentClient with options such as model and timeout. Use AgentOptions.builder for customization.
```java
agentClient.goal("Generate code")
.workingDirectory("/project")
.options(AgentOptions.builder()
.model("claude-sonnet-4-0")
.timeout(Duration.ofMinutes(10))
.build())
.run();
```
--------------------------------
### Run Integration Tests for Spring AI Agent Client
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Run integration tests. This requires CLIs and API keys to be set up.
```bash
./mvnw clean verify -Pfailsafe
```
--------------------------------
### Configure McpServerCatalog for Agent Client
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Build an McpServerCatalog programmatically or load from JSON to define how AgentClient resolves and translates provider-specific MCP configurations for various services like search, GitHub, weather, and remote APIs.
```java
import org.springaicommunity.agents.model.mcp.McpServerCatalog;
import org.springaicommunity.agents.model.mcp.McpServerDefinition;
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.AgentClientResponse;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
// Programmatic catalog
McpServerCatalog catalog = McpServerCatalog.builder()
.add("brave-search", new McpServerDefinition.StdioDefinition(
"npx",
List.of("-y", "@modelcontextprotocol/server-brave-search"),
Map.of("BRAVE_API_KEY", System.getenv("BRAVE_API_KEY"))))
.add("github", new McpServerDefinition.StdioDefinition(
"npx",
List.of("-y", "@modelcontextprotocol/server-github"),
Map.of("GITHUB_PERSONAL_ACCESS_TOKEN", System.getenv("GITHUB_TOKEN"))))
.add("weather", new McpServerDefinition.SseDefinition("http://localhost:8080/sse"))
.add("remote-api", new McpServerDefinition.HttpDefinition(
"https://api.example.com/mcp",
Map.of("Authorization", "Bearer " + System.getenv("API_TOKEN"))))
.build();
// Load from Claude-compatible JSON file
// McpServerCatalog catalogFromFile = McpServerCatalog.fromJson(Path.of(".claude/mcp.json"));
AgentClient client = AgentClient.builder(model)
.mcpServerCatalog(catalog)
.defaultMcpServers("github") // always include github for all requests
.build();
AgentClientResponse response = client
.goal("Search for recent Spring AI releases and create a changelog entry")
.mcpServers("brave-search") // add brave-search for this request only
.run();
```
--------------------------------
### Enable Local Sandbox Configuration
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Configuration properties to enable the Local sandbox, which is the default. Specifies the working directory for local execution.
```properties
# Use Local sandbox (default, faster for development)
spring.ai.agents.sandbox.docker.enabled=false
spring.ai.agents.sandbox.local.working-directory=/path/to/workspace
```
--------------------------------
### Provider-Agnostic Agent Client Usage
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
This code demonstrates how to use the AgentClient with any supported provider by creating a model and then running a command. The specific provider is determined by the 'model' object passed to AgentClient.create().
```java
// This code works with ANY provider
AgentClient client = AgentClient.create(model);
AgentClientResponse response = client.run("Create hello.txt");
```
--------------------------------
### Compile Spring AI Agent Client
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Use this command to compile the project's code.
```bash
./mvnw clean compile
```
--------------------------------
### Basic AgentClient Usage
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Use AgentClient to execute defined goals. It takes a goal description and returns the result of the execution.
```java
String response = agentClient
.goal("Add Spring Security to project")
.run()
.result();
```
--------------------------------
### Configure Per-Request Options with JSON Schema
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Use AgentClient.goal() to configure a single request, including goal text, working directory, MCP servers, and JSON schema for structured output. The result is constrained by the provided schema.
```java
import org.springaicommunity.agents.client.AgentClient;
import org.springaicommunity.agents.client.AgentClientResponse;
import java.nio.file.Path;
import java.util.Map;
AgentClient client = AgentClient.create(model);
// Structured output via JSON schema
Map schema = Map.of(
"type", "object",
"properties", Map.of(
"summary", Map.of("type", "string"),
"issues", Map.of("type", "array", "items", Map.of("type", "string"))
),
"required", java.util.List.of("summary", "issues")
);
AgentClientResponse response = client
.goal("Analyse the codebase and return a JSON summary of technical debt")
.workingDirectory(Path.of("/my/project"))
.jsonSchema(schema)
.run();
String jsonOutput = response.getResult(); // constrained JSON output
System.out.println(jsonOutput);
```
--------------------------------
### Agent Input with Empty Value
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Demonstrates how to provide an empty string as a value for an agent input by using the key followed immediately by an equals sign.
```bash
jbang agents@springai hello-world path=output.txt content=
```
--------------------------------
### Basic JBang Agent CLI Usage
Source: https://github.com/spring-ai-community/agent-client/blob/main/jbang/README.md
Illustrates the fundamental command structure for running agents via JBang, including agent ID and key-value pairs.
```bash
jbang agents@springai key=value key2=value2 ...
```
--------------------------------
### Run Unit Tests for Spring AI Agent Client
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Execute unit tests to verify the correctness of the code.
```bash
./mvnw clean test
```
--------------------------------
### ChatClient Configuration with Options
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Configure ChatClient with specific options like model and max tokens. Use ChatOptionsBuilder for customization.
```java
chatClient.prompt("Generate code")
.options(ChatOptionsBuilder.builder()
.withModel("gpt-4")
.withMaxTokens(1000)
.build())
.call();
```
--------------------------------
### Enable Docker Sandbox Configuration
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Configuration properties to enable and configure the Docker sandbox for agent execution. Specifies the image tag to use.
```properties
# Use Docker sandbox (recommended for production)
spring.ai.agents.sandbox.docker.enabled=true
spring.ai.agents.sandbox.docker.image-tag=ghcr.io/spring-ai-community/agents-runtime:latest
```
--------------------------------
### Configure ClaudeAgentOptions
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Sets up specific options for the Claude Code provider, including model selection, timeouts, tool restrictions, and system prompts. Use `yolo(true)` to bypass permission prompts.
```java
import org.springaicommunity.agents.claude.ClaudeAgentOptions;
import org.springaicommunity.agents.claude.SystemPrompt;
import org.springaicommunity.agents.claude.SettingSource;
ClaudeAgentOptions options = ClaudeAgentOptions.builder()
.model("claude-sonnet-4-5")
.timeout(java.time.Duration.ofMinutes(15))
.yolo(true) // bypass all permission prompts
.maxTurns(30)
.maxBudgetUsd(1.00)
.maxThinkingTokens(8000) // extended thinking
.maxTokens(16384)
.allowedTools(java.util.List.of("Read", "Write", "Bash", "Glob"))
.disallowedTools(java.util.List.of("WebSearch"))
.systemPrompt("You are a senior Java engineer. Follow clean-code principles.")
.appendSystemPrompt("Never commit directly to main branch.")
.settingSources(SettingSource.PROJECT) // load project-level Claude settings
.forkSession(false)
.includePartialMessages(false)
.fallbackModel("claude-haiku-4")
.build();
```
--------------------------------
### Spring Boot Auto-Configuration for AgentClient
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
With a provider starter on the classpath, Spring Boot auto-wires an AgentClient.Builder prototype bean. Each injection point receives a fresh builder instance, matching the ChatClient.Builder pattern.
```xml
org.springaicommunity.agents
agent-starter-claude
0.15.0
```
--------------------------------
### Implement LoggingAdvisor for Agent Calls
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Implement this advisor to add pre-processing (context injection, request modification) or post-processing (evaluation, logging, metrics) to agent calls. Advisors are chained in order of priority.
```java
import org.springaicommunity.agents.client.AgentClientRequest;
import org.springaicommunity.agents.client.AgentClientResponse;
import org.springaicommunity.agents.client.advisor.api.AgentCallAdvisor;
import org.springaicommunity.agents.client.advisor.api.AgentCallAdvisorChain;
import org.springframework.core.Ordered;
// Custom logging advisor
public class LoggingAdvisor implements AgentCallAdvisor {
@Override
public AgentClientResponse adviseCall(AgentClientRequest request, AgentCallAdvisorChain chain) {
long start = System.currentTimeMillis();
System.out.printf("[BEFORE] goal=%s%n", request.goal().getContent());
AgentClientResponse response = chain.nextCall(request); // proceed
long elapsed = System.currentTimeMillis() - start;
System.out.printf("[AFTER] success=%s duration=%dms%n",
response.isSuccessful(), elapsed);
response.context().put("logging.durationMs", elapsed);
return response;
}
@Override public String getName() { return "LoggingAdvisor"; }
@Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 50; }
}
```
```java
// Usage — attach to builder (default for all requests) or per-request
AgentClient client = AgentClient.builder(model)
.defaultAdvisor(new LoggingAdvisor())
.build();
AgentClientResponse response = client
.goal("Optimise database queries in the UserRepository")
.advisors(new LoggingAdvisor()) // or per-request override
.run();
```
--------------------------------
### Generate Reference Documentation
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Regenerate Markdown reference tables for agent properties. This command should be run before submitting documentation pull requests if any properties have changed.
```bash
./mvnw -f tools/agent-options-docgen/pom.xml compile exec:java -Dexec.args=" [output-dir]"
```
--------------------------------
### Basic ChatClient Usage
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Use ChatClient for simple conversational prompts. It takes a prompt string and returns the content of the AI's response.
```java
String response = chatClient
.prompt("Explain Spring Security")
.call()
.content();
```
--------------------------------
### Configure and Use CodexAgentModel
Source: https://context7.com/spring-ai-community/agent-client/llms.txt
Configures the Codex provider with sandbox mode and approval policies, then uses it to run a code generation task. Set `fullAuto(true)` for automatic execution without approvals.
```java
import org.springaicommunity.agents.codex.CodexAgentModel;
import org.springaicommunity.agents.codex.CodexAgentOptions;
import org.springaicommunity.agents.codexsdk.types.SandboxMode;
import org.springaicommunity.agents.codexsdk.types.ApprovalPolicy;
CodexAgentOptions codexOptions = CodexAgentOptions.builder()
.model("gpt-5.4-mini")
.timeout(java.time.Duration.ofMinutes(10))
.fullAuto(true) // implies WORKSPACE_WRITE + NEVER approval
.sandboxMode(SandboxMode.WORKSPACE_WRITE)
.approvalPolicy(ApprovalPolicy.NEVER)
.skipGitCheck(false)
.build();
CodexAgentModel codexModel = new CodexAgentModel(codexOptions);
AgentClient client = AgentClient.create(codexModel);
AgentClientResponse response = client.run("Add input validation to all REST endpoints");
System.out.println(response.getResult());
```
--------------------------------
### Apply Java Code Formatting
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Mandatory command to run before any commit to apply Spring's Java code formatting conventions. CI will fail if formatting violations are found.
```bash
./mvnw spring-javaformat:apply
```
--------------------------------
### Run Docker Infrastructure Integration Tests
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Execute specific integration tests related to Docker infrastructure. Ensure the sandbox.integration.test property is set to true.
```bash
./mvnw test -Dsandbox.integration.test=true -Dtest="*DockerInfraIT"
```
--------------------------------
### Run Agent Client with Spring Boot Auto-Configuration
Source: https://github.com/spring-ai-community/agent-client/blob/main/README.md
Implement CommandLineRunner to leverage Spring Boot's auto-configuration for AgentClient. The client is injected and can be used to run agent commands.
```java
@Component
public class MyAgent implements CommandLineRunner {
private final AgentClient.Builder agentClientBuilder;
public MyAgent(AgentClient.Builder agentClientBuilder) {
this.agentClientBuilder = agentClientBuilder;
}
@Override
public void run(String... args) {
AgentClient client = agentClientBuilder.build();
AgentClientResponse response = client.run("Fix the failing test");
}
}
```
--------------------------------
### AgentClient for PR Review Automation
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Automate Pull Request reviews using AgentClient. It can provide risk assessments, architecture evaluations, and recommendations.
```java
@Component
class PRReviewDemo implements CommandLineRunner {
private final AgentClient agentClient;
public void run(String... args) {
AgentClientResponse response = agentClient
.goal("Review PR changes. Provide risk assessment, " +
"architecture evaluation, and recommendations")
.run();
// Generates structured Markdown report
}
}
```
--------------------------------
### Parse Transition Configuration
Source: https://github.com/spring-ai-community/agent-client/blob/main/springone-2025-presentation.html
Parses transition configuration from a JSON string, validating its structure. Returns the parsed object or null if invalid.
```javascript
const xe=e=>{if(e)try{const t=JSON.parse(e);if((e=>{if("object"!=typeof e)return!1;const t=e;return"string"==typeof t.name&&(void 0===t.duration||"string"==typeof t.duration)})(t))return t}catch{}}
```
--------------------------------
### Run Integration Tests with Maven
Source: https://github.com/spring-ai-community/agent-client/blob/main/CLAUDE.md
Execute all integration tests for the claude-agent-sdk module using Maven. Alternatively, specify a single integration test class to run.
```bash
# Run all IT tests
./mvnw test -pl provider-sdks/claude-agent-sdk -Dtest="*IT"
```
```bash
# Run a specific IT test
./mvnw test -pl provider-sdks/claude-agent-sdk -Dtest="HookIntegrationIT"
```