> ## Documentation Index
> Fetch the complete documentation index at: https://springaicommunity.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Spring AI Bedrock AgentCore

> Spring Boot starter for AWS Bedrock AgentCore Runtime integration

<img src="https://img.shields.io/badge/Status-Incubating-blue" alt="Incubating Status" />

[GitHub](https://github.com/spring-ai-community/spring-ai-bedrock-agentcore) • [Maven Central](https://central.sonatype.com/search?q=org.springaicommunity%20bedrock-agentcore)

## Overview

A Spring Boot starter that enables existing Spring Boot applications to conform to the AWS Bedrock AgentCore Runtime contract with minimal configuration. Simply add the dependency and annotate your agent methods.

<Note>
  **Version**: 1.0.0-RC3
</Note>

## Modules

| Module                                | Description                                           |
| ------------------------------------- | ----------------------------------------------------- |
| `spring-ai-bedrock-agentcore-starter` | Core starter for AgentCore Runtime integration        |
| `spring-ai-memory-bedrock-agentcore`  | Spring AI ChatMemoryRepository using AgentCore Memory |

## Key Features

<CardGroup cols={2}>
  <Card title="Auto-configuration" icon="gear">
    Automatically sets up AgentCore endpoints when added as dependency
  </Card>

  <Card title="Annotation-based" icon="at">
    Simple `@AgentCoreInvocation` annotation to mark agent methods
  </Card>

  <Card title="SSE Streaming" icon="wave-pulse">
    Server-Sent Events support with `Flux<String>` return types
  </Card>

  <Card title="Health Checks" icon="heart-pulse">
    Built-in `/ping` endpoint with Spring Boot Actuator integration
  </Card>

  <Card title="Async Task Tracking" icon="list-check">
    Prevents premature shutdown during background work
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    Built-in Bucket4j throttling for invocations and ping endpoints
  </Card>
</CardGroup>

## Quick Start

### 1. Add Dependency

```xml theme={null}
<dependency>
    <groupId>org.springaicommunity</groupId>
    <artifactId>spring-ai-bedrock-agentcore-starter</artifactId>
    <version>1.0.0-RC3</version>
</dependency>
```

### 2. Create Agent Method

```java theme={null}
@Service
public class MyAgentService {

    @AgentCoreInvocation
    public String handleUserPrompt(MyRequest request) {
        return "You said: " + request.prompt;
    }
}
```

### 3. Run Application

The application will automatically expose:

* `POST /invocations` - Agent processing endpoint
* `GET /ping` - Health check endpoint

## Supported Method Signatures

<AccordionGroup>
  <Accordion title="Basic POJO Method">
    ```java theme={null}
    @AgentCoreInvocation
    public MyResponse processRequest(MyRequest request) {
        return new MyResponse("Processed: " + request.prompt());
    }

    record MyRequest(String prompt) {}
    record MyResponse(String message) {}
    ```
  </Accordion>

  <Accordion title="With AgentCore Context">
    ```java theme={null}
    @AgentCoreInvocation
    public MyResponse processWithContext(MyRequest request, AgentCoreContext context) {
        var sessionId = context.getHeader(AgentCoreHeaders.SESSION_ID);
        return new MyResponse("Session " + sessionId + ": " + request.prompt());
    }
    ```
  </Accordion>

  <Accordion title="Map Method (Flexible)">
    ```java theme={null}
    @AgentCoreInvocation
    public Map<String, Object> processData(Map<String, Object> data) {
        return Map.of(
            "input", data,
            "response", "Processed: " + data.get("message"),
            "timestamp", System.currentTimeMillis()
        );
    }
    ```
  </Accordion>

  <Accordion title="String Method (text/plain)">
    ```java theme={null}
    @AgentCoreInvocation
    public String handlePrompt(String prompt) {
        return "Response: " + prompt;
    }
    ```
  </Accordion>

  <Accordion title="SSE Streaming with Spring AI">
    ```java theme={null}
    @AgentCoreInvocation
    public Flux<String> streamingAgent(String prompt) {
        return chatClient.prompt().user(prompt).stream().content();
    }
    ```
  </Accordion>
</AccordionGroup>

## Background Task Tracking

AWS Bedrock AgentCore Runtime monitors agent health and may shut down agents that appear idle. Use `AgentCoreTaskTracker` to communicate active work:

```java theme={null}
@AgentCoreInvocation
public String asyncTaskHandling(MyRequest request, AgentCoreContext context) {
    agentCoreTaskTracker.increment();  // Starting background work

    CompletableFuture.runAsync(() -> {
        // Long-running background work
    }).thenRun(agentCoreTaskTracker::decrement);  // Work completed

    return "Task started";
}
```

The `/ping` endpoint returns:

* **"Healthy"** - Agent is ready, no background tasks
* **"HealthyBusy"** - Agent is healthy but actively processing (prevents shutdown)
* **"Unhealthy"** - Agent has issues (with Actuator integration)

## Health Monitoring

**Without Spring Boot Actuator:**

* Returns static "Healthy" status
* Always responds with HTTP 200

**With Spring Boot Actuator:**

```xml theme={null}
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
```

* Integrates with Actuator health checks
* Maps Actuator status: `UP` → "Healthy", `DOWN` → "Unhealthy"
* Tracks status change timestamps

## Custom Controller Override

Override default controllers with custom implementations using marker interfaces:

```java theme={null}
// Override /invocations
@RestController
public class CustomInvocationsController implements AgentCoreInvocationsHandler {

    @PostMapping("/invocations")
    public ResponseEntity<?> handleInvocations(@RequestBody String request) {
        return ResponseEntity.ok("Custom response");
    }
}

// Override /ping
@RestController
public class CustomPingController implements AgentCorePingHandler {

    @GetMapping("/ping")
    public ResponseEntity<?> ping() {
        return ResponseEntity.ok(Map.of("status", "Custom Healthy"));
    }
}
```

## Configuration

```properties theme={null}
# Rate limits in requests per minute (optional, disabled by default)
agentcore.throttle.invocations-limit=50
agentcore.throttle.ping-limit=200
```

***

## Memory Module

The `spring-ai-memory-bedrock-agentcore` module provides Spring AI `ChatMemoryRepository` integration with AWS Bedrock AgentCore Memory for persistent conversation storage.

### Add Dependency

```xml theme={null}
<dependency>
    <groupId>org.springaicommunity</groupId>
    <artifactId>spring-ai-memory-bedrock-agentcore</artifactId>
    <version>1.0.0-RC3</version>
</dependency>
```

### Configure Memory

```yaml theme={null}
agentcore:
  memory:
    memory-id: your-agentcore-memory-id    # Required
    total-events-limit: 100                # Max events to retrieve
    default-session: default-session       # Default session name
    page-size: 50                          # API pagination size
    ignore-unknown-roles: false            # Handle unknown roles
```

### Use with Spring AI

```java theme={null}
@Service
public class ChatService {

    private final ChatClient chatClient;
    private final ChatMemory chatMemory;

    public ChatService(ChatClient.Builder chatClientBuilder, ChatMemoryRepository memoryRepository) {
        this.chatClient = chatClientBuilder.build();
        this.chatMemory = MessageWindowChatMemory.builder()
            .chatMemoryRepository(memoryRepository)
            .maxMessages(10)
            .build();
    }

    public String chat(String conversationId, String message) {
        return chatClient.prompt()
            .user(message)
            .advisors(chatMemory.getChatMemoryAdvisor(conversationId))
            .call()
            .content();
    }
}
```

### Conversation ID Format

* **Simple**: `user123` → actor: `user123`, session: `default-session`
* **With Session**: `user123:session456` → actor: `user123`, session: `session456`

### Message Type Mapping

| Spring AI Message     | AgentCore Role | Supported |
| --------------------- | -------------- | --------- |
| `UserMessage`         | `USER`         | Yes       |
| `AssistantMessage`    | `ASSISTANT`    | Yes       |
| `SystemMessage`       | N/A            | Filtered  |
| `ToolResponseMessage` | N/A            | Filtered  |

### AWS Permissions

```json theme={null}
{
  "Effect": "Allow",
  "Action": [
    "bedrock-agentcore:ListEvents",
    "bedrock-agentcore:CreateEvent",
    "bedrock-agentcore:DeleteEvent"
  ],
  "Resource": "arn:aws:bedrock-agentcore:*:*:memory/*"
}
```

## Examples

See the `examples/` directory in the repository:

| Example                           | Description                                            |
| --------------------------------- | ------------------------------------------------------ |
| `simple-spring-boot-app/`         | Minimal AgentCore agent with async task tracking       |
| `spring-ai-sse-chat-client/`      | SSE streaming with Spring AI and Amazon Bedrock        |
| `spring-ai-simple-chat-client/`   | Traditional Spring AI integration                      |
| `spring-ai-override-invocations/` | Custom controller override using marker interfaces     |
| `spring-ai-extended-chat-client/` | Extended chat client with JWT and Terraform deployment |
| `spring-ai-memory-integration/`   | Memory module integration example                      |

## Requirements

* Java 17+
* Spring Boot 3.x
* Spring AI 1.1.1+ (for memory module)

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/spring-ai-community/spring-ai-bedrock-agentcore">
    Source code and contribution guidelines
  </Card>

  <Card title="AWS Bedrock AgentCore" icon="aws" href="https://docs.aws.amazon.com/bedrock/latest/userguide/agents-core.html">
    AWS Bedrock AgentCore documentation
  </Card>
</CardGroup>

## License

This project is licensed under the [Apache License 2.0](https://github.com/spring-ai-community/spring-ai-bedrock-agentcore/blob/main/LICENSE).
