-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathDiceRollMcpServer.java
More file actions
63 lines (46 loc) · 2.11 KB
/
Copy pathDiceRollMcpServer.java
File metadata and controls
63 lines (46 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 25+
//FILES application.properties
//REPOS mavencentral,spring-milestones=https://repo.spring.io/milestone
//DEPS tools.jackson:jackson-bom:3.1.4@pom
//DEPS org.springframework.boot:spring-boot-starter-web:4.0.2
//DEPS org.springframework.ai:spring-ai-starter-mcp-server-webmvc:2.0.0
package com.amazonaws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
// Provided for you: the MCP annotation imports that expose your tools over the network.
import org.springframework.ai.mcp.annotation.McpTool;
import org.springframework.ai.mcp.annotation.McpToolParam;
import java.util.Arrays;
import java.util.Random;
/// MCP Server that exposes dice rolling tools over HTTP.
/// Run this first, then run DungeonMasterMCPClient.java to connect.
/// The key difference from Chapter 3: tools are now accessible over the NETWORK via MCP protocol.
@SpringBootApplication
public class DiceRollMcpServer {
public static void main(final String[] args) {
SpringApplication.run(DiceRollMcpServer.class, args);
}
}
@Component
class DiceTools {
private static final Logger log = LoggerFactory.getLogger("DiceTools");
private static final Random random = new Random();
record DiceRollResponse(int[] rolls, int total, String description) {}
// TODO 1: Annotate the method with @McpTool to expose it as an MCP tool
// TODO 2: Annotate each parameter with @McpToolParam
DiceRollResponse rollDice(int faces, int count) {
var rolls = new int[count];
var total = 0;
for (int i = 0; i < count; i++) {
rolls[i] = random.nextInt(faces) + 1;
total += rolls[i];
}
var description = "Rolled %dd%d: %s = %d".formatted(count, faces, Arrays.toString(rolls), total);
log.info("TOOL CALLED: {}", description);
return new DiceRollResponse(rolls, total, description);
}
}