Java MCP Server Generator

Java MCP Server Generator

Scaffolds a Maven or Gradle Java project with an MCP server using the MCP Java SDK 2.x, writes tools and JUnit tests, builds it and configures the client.

Skill files3 files

references/

SKILL.md303 lines
1
---
2
name: java-mcp-server-generator
3
description: 'Use this skill when the user wants to create a Model Context Protocol (MCP) server in Java or in a Spring Boot app. Also use it when the user wants AI agents, such as GitHub Copilot or Claude, to use Java code, an API, or a database. Use it even if the user does not say "MCP". The skill makes a Maven or Gradle project with the MCP Java SDK 2.x, tools, JUnit tests, and client configuration. Do not use it for Quarkus/Quarkiverse MCP servers (use the `quarkus-mcp-server-sse` instruction), for an MCP client or for a server in another language.'
4
compatibility: 'JDK 17 or later, Maven 3.9 or later or Gradle 9 or later, and network access to download dependencies. The MCP Inspector also uses Node.js.'
5
---
6
7
# Java MCP Server Generator
8
9
Create a Model Context Protocol (MCP) server in Java with the official [MCP Java SDK](https://github.com/modelcontextprotocol/java-sdk) 2.x. SDK 2.0.x supports the MCP specification revision [2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25) and the earlier revisions. SDK 3.x will add the revision [2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28).
10
11
## Workflow
12
13
Copy this checklist and track your progress:
14
15
- [ ] Step 1: Create the project.
16
- [ ] Step 2: Write the server.
17
- [ ] Step 3: Write the tests.
18
- [ ] Step 4: Build until the tests pass.
19
- [ ] Step 5: Configure the client.
20
21
### Step 1: Create the project
22
23
Use Maven by default. If the project uses Gradle or the user asks for Gradle, read [references/gradle.md](references/gradle.md). Use it for Step 1, Step 4, and Step 5.
24
25
Make this layout:
26
27
```text
28
project-name/
29
├── pom.xml
30
└── src/
31
├── main/java/com/example/McpServerApp.java
32
└── test/java/com/example/McpServerAppTest.java
33
```
34
35
Write `pom.xml`:
36
37
```xml
38
<?xml version="1.0" encoding="UTF-8"?>
39
<project xmlns="http://maven.apache.org/POM/4.0.0"
40
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
41
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
42
<modelVersion>4.0.0</modelVersion>
43
44
<groupId>com.example</groupId>
45
<artifactId>mcp-server-demo</artifactId>
46
<version>0.1.0</version>
47
48
<properties>
49
<maven.compiler.release>17</maven.compiler.release>
50
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
51
</properties>
52
53
<dependencyManagement>
54
<dependencies>
55
<dependency>
56
<groupId>io.modelcontextprotocol.sdk</groupId>
57
<artifactId>mcp-bom</artifactId>
58
<version>2.0.1</version>
59
<type>pom</type>
60
<scope>import</scope>
61
</dependency>
62
<dependency>
63
<groupId>org.junit</groupId>
64
<artifactId>junit-bom</artifactId>
65
<version>6.1.3</version>
66
<type>pom</type>
67
<scope>import</scope>
68
</dependency>
69
</dependencies>
70
</dependencyManagement>
71
72
<dependencies>
73
<dependency>
74
<groupId>io.modelcontextprotocol.sdk</groupId>
75
<artifactId>mcp</artifactId>
76
</dependency>
77
<dependency>
78
<groupId>org.slf4j</groupId>
79
<artifactId>slf4j-simple</artifactId>
80
<version>2.0.17</version>
81
<scope>runtime</scope>
82
</dependency>
83
<dependency>
84
<groupId>org.junit.jupiter</groupId>
85
<artifactId>junit-jupiter</artifactId>
86
<scope>test</scope>
87
</dependency>
88
</dependencies>
89
90
<build>
91
<plugins>
92
<plugin>
93
<groupId>org.apache.maven.plugins</groupId>
94
<artifactId>maven-shade-plugin</artifactId>
95
<version>3.6.2</version>
96
<executions>
97
<execution>
98
<phase>package</phase>
99
<goals>
100
<goal>shade</goal>
101
</goals>
102
<configuration>
103
<createDependencyReducedPom>false</createDependencyReducedPom>
104
<transformers>
105
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
106
<mainClass>com.example.McpServerApp</mainClass>
107
</transformer>
108
</transformers>
109
</configuration>
110
</execution>
111
</executions>
112
</plugin>
113
</plugins>
114
</build>
115
</project>
116
```
117
118
- The `mcp` artifact contains `mcp-core` and the Jackson 3 JSON mapper `mcp-json-jackson3`.
119
- `slf4j-simple` writes the SDK logs to stderr.
120
- The shade plugin makes one executable JAR with all dependencies.
121
122
### Step 2: Write the server
123
124
Start from this template:
125
126
```java
127
package com.example;
128
129
import java.util.List;
130
import java.util.Map;
131
132
import io.modelcontextprotocol.json.McpJsonDefaults;
133
import io.modelcontextprotocol.server.McpServer;
134
import io.modelcontextprotocol.server.McpServerFeatures.SyncToolSpecification;
135
import io.modelcontextprotocol.server.transport.StdioServerTransportProvider;
136
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
137
import io.modelcontextprotocol.spec.McpSchema.ServerCapabilities;
138
import io.modelcontextprotocol.spec.McpSchema.Tool;
139
140
public final class McpServerApp {
141
142
static SyncToolSpecification divideTool() {
143
Tool tool = Tool.builder("divide", Map.of(
144
"type", "object",
145
"properties", Map.of(
146
"a", Map.of("type", "number", "description", "Dividend"),
147
"b", Map.of("type", "number", "description", "Divisor")),
148
"required", List.of("a", "b")))
149
.description("Divide a by b.")
150
.build();
151
152
return SyncToolSpecification.builder()
153
.tool(tool)
154
.callHandler((exchange, request) -> {
155
double a = ((Number) request.arguments().get("a")).doubleValue();
156
double b = ((Number) request.arguments().get("b")).doubleValue();
157
if (b == 0) {
158
return CallToolResult.builder().addTextContent("b must not be zero.").isError(true).build();
159
}
160
return CallToolResult.builder().addTextContent(String.valueOf(a / b)).build();
161
})
162
.build();
163
}
164
165
public static void main(String[] args) {
166
McpServer.sync(new StdioServerTransportProvider(McpJsonDefaults.getMapper()))
167
.serverInfo("demo", "0.1.0")
168
.capabilities(ServerCapabilities.builder().tools(false).build())
169
.tools(divideTool())
170
.build();
171
}
172
}
173
```
174
175
Then change the template to match the request of the user:
176
177
1. Replace `divideTool()` with the tools that the user asks for. Make one method for each tool.
178
2. Give each tool a JSON Schema `inputSchema` and a `description`. The description tells the model when to use the tool.
179
3. When the client must get machine-readable data, add `.outputSchema(Map)` to the tool. Return the data with `CallToolResult.builder().structuredContent(map)`. Also add the same data as text content for older clients.
180
4. Mark a read-only tool with `.annotations(ToolAnnotations.builder().readOnlyHint(true).build())`. Use `destructiveHint(true)` for a destructive tool.
181
5. Add resources, resource templates, and prompts only when the user asks for them. Also enable them in `ServerCapabilities`.
182
183
Use stdio by default. Read [references/streamable-http.md](references/streamable-http.md) only when the user asks for a remote server, an HTTP server, or Spring Boot.
184
185
### Step 3: Write the tests
186
187
The test starts the server as a subprocess and connects to it with the SDK client. Write a test for each tool and for each error result:
188
189
```java
190
package com.example;
191
192
import static org.junit.jupiter.api.Assertions.assertEquals;
193
import static org.junit.jupiter.api.Assertions.assertTrue;
194
195
import java.nio.file.Path;
196
import java.util.Map;
197
198
import org.junit.jupiter.api.AfterAll;
199
import org.junit.jupiter.api.BeforeAll;
200
import org.junit.jupiter.api.Test;
201
202
import io.modelcontextprotocol.client.McpClient;
203
import io.modelcontextprotocol.client.McpSyncClient;
204
import io.modelcontextprotocol.client.transport.ServerParameters;
205
import io.modelcontextprotocol.client.transport.StdioClientTransport;
206
import io.modelcontextprotocol.json.McpJsonDefaults;
207
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
208
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
209
import io.modelcontextprotocol.spec.McpSchema.TextContent;
210
211
class McpServerAppTest {
212
213
private static McpSyncClient client;
214
215
@BeforeAll
216
static void startServer() {
217
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
218
ServerParameters server = ServerParameters.builder(java)
219
.args("-cp", System.getProperty("java.class.path"), McpServerApp.class.getName())
220
.build();
221
client = McpClient.sync(new StdioClientTransport(server, McpJsonDefaults.getMapper())).build();
222
client.initialize();
223
}
224
225
@AfterAll
226
static void stopServer() {
227
client.close();
228
}
229
230
@Test
231
void divide() {
232
CallToolResult result = client.callTool(
233
CallToolRequest.builder("divide").arguments(Map.of("a", 6, "b", 3)).build());
234
assertEquals("2.0", ((TextContent) result.content().get(0)).text());
235
}
236
237
@Test
238
void divideByZero() {
239
CallToolResult result = client.callTool(
240
CallToolRequest.builder("divide").arguments(Map.of("a", 1, "b", 0)).build());
241
assertTrue(result.isError());
242
assertTrue(((TextContent) result.content().get(0)).text().contains("must not be zero"));
243
}
244
}
245
```
246
247
- The test uses the `java` command of the JDK that runs Maven. Do not use the `java` command from `PATH`.
248
- The test uses the real stdio transport and the real JSON-RPC messages.
249
250
### Step 4: Build until the tests pass
251
252
1. Run `mvn verify`. This command compiles the code, runs the tests, and makes `target/mcp-server-demo-0.1.0.jar`.
253
2. If a test fails, read the error. Fix the server or the test.
254
3. Run `mvn verify` again.
255
4. Continue only when the build is successful.
256
257
### Step 5: Configure the client
258
259
For VS Code, write `.vscode/mcp.json`:
260
261
```json
262
{
263
"servers": {
264
"demo": {
265
"type": "stdio",
266
"command": "java",
267
"args": ["-jar", "/absolute/path/to/project/target/mcp-server-demo-0.1.0.jar"]
268
}
269
}
270
}
271
```
272
273
For Claude Desktop, put the same `command` and `args` in `claude_desktop_config.json`, below the `mcpServers` key.
274
275
For an HTTP server, use the client configuration in [references/streamable-http.md](references/streamable-http.md).
276
277
Tell the user these facts:
278
279
- `java -jar target/mcp-server-demo-0.1.0.jar` starts the stdio server. The server waits for a host on stdin. The SDK logs go to stderr.
280
- To test the server manually, start the MCP Inspector with the same command. The Inspector uses Node.js.
281
282
## Gotchas
283
284
SDK 2.x changed many patterns of SDK 0.x and 1.x. Do not copy examples from earlier versions. Read the [migration guide](https://github.com/modelcontextprotocol/java-sdk/blob/main/MIGRATION-2.0.md) for the full list.
285
286
- Use the builders that take the required fields first: `Tool.builder(name, inputSchema)`, `Resource.builder(uri, name)`, `Prompt.builder(name)`, `TextContent.builder(text)`, and `ReadResourceResult.builder(contents)`. The builders without arguments are deprecated.
287
- A required field must not be `null`. A `null` value causes an `IllegalArgumentException`.
288
- Tool names must have 1 to 128 characters: letters, digits, `_`, `-`, and `.`. The server builder rejects an incorrect name with an `IllegalArgumentException`. `addTool()` at runtime does not check the name.
289
- `inputSchema` and `outputSchema` are `Map<String, Object>` values. The `JsonSchema` record is deprecated.
290
- The server checks each schema against JSON Schema 2020-12 when you call `build()` or `addTool()`. An incorrect schema causes an `IllegalArgumentException`.
291
- The SDK validates the tool arguments against `inputSchema`. It also validates `structuredContent` against `outputSchema`. If the validation fails, the client gets a tool result with `isError` set to `true`. Thus, the handler gets only valid arguments.
292
- If a tool has an `outputSchema`, return `structuredContent` in each successful result. Without it, the SDK returns a tool result with `isError` set to `true`.
293
- Return `CallToolResult` with `isError(true)` for an error that the model must read.
294
- Do not throw an exception or an `McpError` for a tool failure. The client gets a JSON-RPC error, not a tool result. Many hosts do not show this error to the model.
295
- In a stdio server, stdout is the protocol channel. Do not call `System.out.println()`.
296
- Log with SLF4J to stderr. The default console appender of Logback writes to stdout. If you use Logback, set its target to `System.err`.
297
- The Spring transports moved to [Spring AI](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-overview.html) 2.0 and later (group `org.springframework.ai`). Do not use the `io.modelcontextprotocol.sdk:mcp-spring-*` artifacts.
298
- Do not use the deprecated SSE transports. Use Streamable HTTP for a remote server.
299
- The revision 2026-07-28 deprecates these features ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)). Do not add them to a new server:
300
- **Sampling** (`exchange.createMessage()`): Call the LLM provider API directly.
301
- **Protocol logging** (`exchange.loggingNotification()`): Use SLF4J.
302
- **Roots** (`exchange.listRoots()`): Get paths from tool arguments, resource URIs, or the server configuration.
303

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…