Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ ArcadeClient client = ArcadeOkHttpClient.builder()
See this table for the available options:

| Setter | System property | Environment variable | Required | Default value |
| --------- | ---------------- | -------------------- | -------- | -------------------------- |
| --------- | ---------------- | -------------------- |----------| -------------------------- |
| `apiKey` | `arcade.apiKey` | `ARCADE_API_KEY` | true | - |
| `baseUrl` | `arcade.baseUrl` | `ARCADE_BASE_URL` | true | `"https://api.arcade.dev"` |
| `baseUrl` | `arcade.baseUrl` | `ARCADE_BASE_URL` | false | `"https://api.arcade.dev"` |

System properties take precedence over environment variables.

Expand Down Expand Up @@ -721,6 +721,39 @@ ArcadeClient client = ArcadeOkHttpClient.builder()
.build();
```

## Spring Boot Integration

The `dev.arcade:arcade-spring-boot-starter` provides a configured `ArcadeClient` bean if the following configuration values are set:

| Spring Property | Environment variable | Required | Default value |
|--------------------|----------------------|----------|--------------------------|
| `arcade.api-key` | `ARCADE_API_KEY` | true | - |
| `arcade.base-url` | `ARCADE_BASE_URL` | false | `"https://api.arcade.dev"` |

Read the Spring Boot [Externalized Configuration](https://docs.spring.io/spring-boot/reference/features/external-config.html) docs for more ways to configure these properties.

## Run the examples

The examples in `arcade-java-example` can be run in your IDE or on the command line by running:

```shell
# Configure the environment variables
export ARCADE_API_KEY="<your-api-key>"
export ARCADE_USER_ID="arcade-userid-or-email"

# run the example
./gradlew :arcade-java-example:run -Pexample=<example-name>
```

| Example Name | Description |
|-------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `springboot.SpringBoot` | Calls an aArcade tool using Spring Boot |
| `springai.SpringAI` | Allows a Spring AI chat client to call Arcade Tools, you must configure an OpenAI key for this example: `export SPRING_AI_OPENAI_API_KEY=<your-open-ai-key>` |
| `Auth` | Demos how to handle an OAuth authorization response |
| `PlaySpotify` | Calls an Arcade tool without a plain Java application. |
> [!NOTE]
> The above Spring Boot (and Spring AI) examples are not web applications, but the demonstrated logic will work the same way in a web app.

## FAQ

### Why don't you use plain `enum` classes?
Expand Down
18 changes: 17 additions & 1 deletion arcade-java-example/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
plugins {
id("arcade.java")
id("io.spring.dependency-management") version "1.1.7" // only needed for SpringBoot examples
application
}

Expand All @@ -9,11 +10,26 @@ repositories {

dependencies {
implementation(project(":arcade-java"))

// Only needed for SpringBootExample
implementation(project(":arcade-spring-boot-starter"))
implementation("org.springframework.boot:spring-boot-starter:3.5.10")

// only needed for SpringAIExample
implementation("org.springframework.ai:spring-ai-starter-model-openai")
implementation("org.apache.httpcomponents.client5:httpclient5:5.6")
}

// only needed for SpringAIExample
dependencyManagement {
imports {
mavenBom("org.springframework.ai:spring-ai-bom:1.1.2")
}
}

tasks.withType<JavaCompile>().configureEach {
// Allow using more modern APIs, like `List.of` and `Map.of`, in examples.
options.release.set(9)
options.release.set(17)
}

application {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
package dev.arcade.example.springai;

import dev.arcade.client.ArcadeClient;
import dev.arcade.core.JsonValue;
import dev.arcade.models.AuthorizationResponse;
import dev.arcade.models.tools.AuthorizeToolRequest;
import dev.arcade.models.tools.ExecuteToolRequest;
import dev.arcade.models.tools.ExecuteToolResponse;
import dev.arcade.models.tools.ToolAuthorizeParams;
import dev.arcade.models.tools.ToolExecuteParams;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

@SpringBootApplication
public class SpringAIExample {

private static final String SYSTEM_PROMPT =
"""
You are a specialized Music Assistant with access to two MCP tools: get_spotify_state and play_song.
Your goal is to provide a seamless, proactive audio experience. Follow these operational guidelines:
Context Awareness: Before playing any music, always use get_spotify_state to see if music is already playing. If it is, acknowledge what is currently playing before switching to the new track.
Proactive Assistance: If the user asks for a song and Spotify is currently paused, inform the user you are resuming playback or starting the session for them.
Error Handling: If a song fails to play or the tool returns an error, check the state again to see if the player is disconnected or if the track simply wasn't found.
Tone: Be concise, upbeat, and music-focused.
Chain of Thought: When a user asks for a song, your internal logic should be: Check State -> Inform User -> Execute Play.
""";

public static void main(String[] args) {
SpringApplication.run(SpringAIExample.class, args);
}

@Bean
ApplicationRunner runner(ChatClient.Builder chatClientBuilder, ArcadeToolProvider arcadeToolProvider) {
return args -> {
ChatClient chatClient = chatClientBuilder
.defaultSystem(SYSTEM_PROMPT)
.defaultTools(arcadeToolProvider) // see below, each tool is annotated with @Tool
.build();

String summary = chatClient
.prompt()
.user("If my music is not currently playing, play something to get me in the mood to write code.")
.call()
.content();

System.out.println(summary);
};
}

/**
* Exposes Arcade Tools to Spring AI.
*/
@Service
public static class ArcadeToolProvider {
private final Logger log = LoggerFactory.getLogger(ArcadeToolProvider.class);
private final ArcadeClient client;
private final String userId;

ArcadeToolProvider(ArcadeClient client, @Value("${arcade.user-id}") String userId) {
this.client = client;
this.userId = userId;
}

/**
* Exposes an Arcade Tool call to Spotify.GetPlaybackState, using Spring AI annotations.
*
* @return A string object of the playback state.
*/
@Tool(
name = "play_song",
description = "Plays a song by an artist and queues four more songs by the same artist")
String play(@ToolParam(description = "The name of the artist to play") String name) {
return executeTool(
"Spotify.PlayArtistByName",
ExecuteToolRequest.Input.builder()

// map the above input as "additional Properties"
.putAdditionalProperty("name", JsonValue.from(name))
.build());
}

/**
* Exposes an Arcade Tool call to Spotify.GetPlaybackState, using Spring AI annotations.
*
* @return A string object of the playback state.
*/
@Tool(
name = "get_spotify_state",
description =
"""
Get information about the user's current playback state,
including track or episode, and active device.
This tool does not perform any actions. Use other tools to control playback.
""")
String playbackState() {
return executeTool(
"Spotify.GetPlaybackState",
ExecuteToolRequest.Input.builder().build()); // this tool has no inputs
}

/**
* Executes the specified tool with the provided input.
*
* @param toolName the name of the tool to be executed
* @param input the input parameters required for tool execution
* @return the result of the tool execution as a string; the result may include
* the output of the tool, an error message, or an authorization requirement
*/
private String executeTool(String toolName, ExecuteToolRequest.Input input) {
log.debug("Executing tool {}, with input: {}", toolName, input);
try {
// call the tool
ExecuteToolResponse response = client.tools()
.execute(ToolExecuteParams.builder()
.executeToolRequest(ExecuteToolRequest.builder()
.toolName(toolName)
.userId(userId)
.input(input)
.build())
.build());

log.debug(
"Tool {} executed, with a status of '{}'",
toolName,
response.status().orElse(null));

// process the result
if (response.success().orElse(false)) {
String result =
response.output().map(o -> o._value().toString()).orElse("{}");

log.debug("Tool {} returned", result);
return result;
}

Optional<ExecuteToolResponse.Output.Error> error =
response.output().flatMap(ExecuteToolResponse.Output::error);

if (error.isPresent()) {
String errorMessage = error.get().message();

if (errorMessage.contains("authorization required")) {
AuthorizationResult auth = requestAuthorization(toolName);
if (auth.url() != null) {
log.debug("Tool requires {} authorization, open a browser to {}", toolName, auth.url());
return String.format(
"The '%s' tool requires authorization, open a browser to %s to continue.",
toolName, auth.url());
}
}
log.warn("Tool {} returned an error: {}", toolName, errorMessage);
return "Error: " + errorMessage;
}

return "Error: Tool execution failed";
} catch (Exception e) {
String message = e.getMessage();
if (message != null && message.contains("authorization")) {
AuthorizationResult auth = requestAuthorization(toolName);
if (auth.url() != null) {
log.debug("Tool requires {} authorization, open a browser to {}", toolName, auth.url());
return String.format(
"The '%s' tool requires authorization, open a browser to %s to continue.",
toolName, auth.url());
}
}
log.error("Tool execution failed for {}: {}", toolName, message);
return "Error: " + message;
}
}

/**
* Requests authorization for a tool and returns the OAuth URL.
*/
public AuthorizationResult requestAuthorization(String toolName) {
try {
AuthorizeToolRequest authRequest = AuthorizeToolRequest.builder()
.toolName(toolName)
.userId(userId)
.build();

AuthorizationResponse response = client.tools()
.authorize(ToolAuthorizeParams.builder()
.authorizeToolRequest(authRequest)
.build());

Optional<String> url = response.url();
Optional<AuthorizationResponse.Status> status = response.status();
String statusValue = status.map(s -> s.value().name()).orElse("unknown");

if ("PENDING".equalsIgnoreCase(statusValue) && url.isPresent()) {
return new AuthorizationResult(toolName, url.get(), statusValue);
}
return new AuthorizationResult(toolName, null, statusValue);
} catch (Exception e) {
log.error("Failed to request authorization for {}: {}", toolName, e.getMessage());
return new AuthorizationResult(toolName, null, "error: " + e.getMessage());
}
}

public record AuthorizationResult(String toolName, String url, String status) {
public boolean requiresAction() {
return url != null && "PENDING".equalsIgnoreCase(status);
}
}

public enum ResultType {
album,
artist,
playlist,
track,
show,
episode,
audiobook
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package dev.arcade.example.springboot;

import dev.arcade.client.ArcadeClient;
import dev.arcade.models.tools.ExecuteToolRequest;
import dev.arcade.models.tools.ExecuteToolResponse;
import dev.arcade.models.tools.ToolExecuteParams;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
* Example of calling a tool using the Arcade Java SDK.
*/
@SpringBootApplication
public class SpringBootExample {

/**
* Starts the Spring Boot application.
* @param args All args are passed into the SpringApplication
*/
public static void main(String[] args) {
SpringApplication.run(SpringBootExample.class, args);
}

/**
* Injects an <code>ArcadeClient</code>, and returns an ApplicationRunner that makes a tool call.
* @param client Arcade Client is autoinjected if ARCADE_API_KEY, or equivalent application.properties var is set.
* @return Runs code on application start.
*/
@Bean
ApplicationRunner appRunner(ArcadeClient client) {
return args -> {
String userId = System.getenv("ARCADE_USER_ID"); // the Spotify tool require a userId
if (userId == null) {
throw new IllegalArgumentException("Missing ARCADE_USER_ID environment variable");
}

ToolExecuteParams params = ToolExecuteParams.builder()
.executeToolRequest(ExecuteToolRequest.builder()
.toolName("Spotify.ResumePlayback@1.0.2")
.userId(userId)
.build())
.build();
ExecuteToolResponse executeToolResponse = client.tools().execute(params);
executeToolResponse
.output()
.ifPresentOrElse(
output -> System.out.println("Tool output: " + output._value()),
() -> System.out.println("No output for this tool"));
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Local configuration - copy to application-local.yml and fill in values
# DO NOT commit application-local.yml to version control

spring:
ai:
openai:
api-key: ${OPENAI_API_KEY:your-openai-api-key}
chat:
options:
model: gpt-4o

arcade:
api-key: ${ARCADE_API_KEY:your-arcade-api-key}
user-id: ${ARCADE_USER_ID:your-email@example.com}

8 changes: 8 additions & 0 deletions arcade-java-example/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
spring:
main:
web-application-type: none
config:
import: optional:application-local.yml
logging:
level:
dev.arcade.example: DEBUG
Loading