In this guide you build a working MCP server and MCP client in plain Java, with one tool called sayHello. It takes about 15 minutes, needs no LLM and no API key, and every line of code is shown.
The goal is not to memorise the MCP Java SDK. The goal is to see the shape of an MCP server once, so you know exactly which three spots you change when you build your own.
What you need: JDK 21, Maven, and any IDE. New to MCP? Read What is MCP? first; it explains the host, client and server, and the JSON-RPC messages underneath.
The big picture: Host + Client + Server
A complete MCP setup always has three parts working together:
| Part | What it is | Real-world example | In this article |
|---|---|---|---|
| Host | The AI app the user talks to. It holds the LLM and decides when a tool is needed. | Claude Desktop, an IDE, OpenCode, your own chat app | We skip the LLM and act as the host ourselves |
| MCP Client | Lives inside the host. Starts the server, asks what tools it has, and calls them. | Built into the host app | HelloWorldMCPClient.java |
| MCP Server | A small program that exposes tools (and data) in a standard way. | A GitHub server, a database server, a file server | HelloWorldMCPServer.java |
Think of a restaurant. The host is the customer who decides what they want. The client is the waiter who carries the order. The server is the kitchen that actually cooks. The menu card is the list of tools, and the dish is the tool’s response.
In a real AI app, the LLM reads the menu (the tool descriptions) and picks a tool. In this HelloWorld, our Java client plays the customer and orders sayHello directly. Once this works, plugging the same server into a real host is a config change, not new code.
Step 1: Add the dependencies
You need only two dependencies: the MCP Java SDK and a small logger. Create a normal Maven project and put this in pom.xml:
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<!-- The MCP BOM: fixes the versions of all MCP modules in one place -->
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp-bom</artifactId>
<version>2.2.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- The MCP Java SDK itself (no version: the BOM supplies it) -->
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp</artifactId>
</dependency>
<!-- A simple logger so we can see what the SDK is doing -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>
</dependencies>
| Dependency | Why you need it |
|---|---|
mcp-bom 2.2.0 |
A “bill of materials”. You set the MCP version once here, and every MCP module you add later gets a matching version. |
mcp |
The SDK. It gives you the server, the client, the transports and the JSON handling. |
slf4j-simple |
Prints the SDK’s internal logs. Optional, but it saves hours when something goes wrong (Step 6). |
One project holds both the server and the client, in two packages: org.example.server and org.example.client.
Step 2: Understand the transport (STDIO)
The client and the server must talk over some channel. MCP calls this the transport. We use the simplest one: STDIO (standard input and standard output).
Here is how it works, in three lines:
- The client starts the server as a child process, exactly like running
java -jar helloworld-mcp-server.jarin a terminal. - The client writes requests into the server’s stdin (keyboard input).
- The server writes replies to its stdout (console output), and the client reads them.
Each message is one line of JSON (the JSON-RPC format). For example, when the client calls our tool, the server receives something like this on stdin:
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sayHello","arguments":{"name":"Prasad"}}}
You never write this JSON yourself. The SDK builds and parses it for you.
STDIO is perfect for local tools that run on the same machine as the host. Servers that run on another machine use an HTTP transport instead, but the server code you write in the next step stays almost the same.
Step 3: Build the HelloWorld MCP server
The MCP Java SDK 2.x classes (McpSyncTool, ToolsFeature, StdioMcpTransport and friends) are very new, so please don’t try to memorise them. Copy them. About 90% of an MCP server is the same wiring every time, and the SDK handles the protocol for you.
Your real job is just three spots:
| # | Spot | Question it answers | Who reads it |
|---|---|---|---|
| ① | Tool definition | What is the tool called, what does it do, what input does it need? | The LLM |
| ② | Handler logic | What actually happens when the tool is called? | Your Java code |
| ③ | Response | What do we send back? | The LLM (through the client) |
The fill-in-the-blanks view
Before the real code, here is the server as a template. Everything marked SAME you copy as is. Only the ①②③ blanks change from one server to the next.
public class MyMCPServer implements McpSyncToolRepository { // SAME
private final McpSyncTool myTool = McpSyncTool.of( // SAME
McpSchema.Tool.builder("①_TOOL_NAME", ①_INPUT_SCHEMA) // ① CHANGE
.description("①_WHAT_THIS_TOOL_DOES") // ① CHANGE
.build(), // SAME
(ctx, request) -> { // SAME
②_READ_ARGUMENTS_AND_DO_THE_WORK // ② CHANGE
return McpSyncResponse.result(③_YOUR_RESULT); // ③ CHANGE
});
public ToolsPage list(...) { /* return all your tools */ } // SAME (add tools here)
public McpSyncTool find(...) { /* find a tool by name */ } // SAME (add tools here)
public static void main(...) { /* start server on STDIO */ } // SAME
}
Now let’s fill each blank for sayHello.
① The tool definition: the menu card for the LLM
McpSchema.Tool.builder("sayHello", Map.of( // ① the tool's name
"type", "object",
"properties", Map.of("name", Map.of("type", "string")), // ① its inputs
"required", List.of("name"))) // ① which inputs are mandatory
.description("Greets a person by name") // ① what it does, in plain English
.build()
This is the only part the LLM ever sees. It never reads your Java code; it reads this card and decides whether to call the tool and with what values.
| You write | Value here | Why it matters |
|---|---|---|
| Name | sayHello |
The ID the client uses to call the tool. Keep it short and unique. |
| Properties | name of type string |
The inputs, written as JSON Schema. Add one entry per input. |
| Required | ["name"] |
Tells the LLM it must always send name. |
| Description | Greets a person by name |
The LLM’s instructions. A clear description is what makes the LLM pick the right tool. |
Tip: write the description for a smart colleague who has never seen your code. “Greets a person by name” is good. “Tool 1” or “hello” is not.
② The handler: where the work happens
(ctx, request) -> {
String name = (String) request.arguments().get("name"); // ② read the input by its property name
String message = "Hello, " + name + "!"; // ② your business logic
...
}
request.arguments() is a Map with exactly the properties you declared in ①. The key "name" here must match the property name in the schema. In a real server, this is where you would query a database, call an API or read a file.
③ The response: what goes back
return McpSyncResponse.result( // ③ wrap it as a successful result
McpSchema.CallToolResult.builder()
.addContent(
McpSchema.TextContent.builder(message).build() // ③ your answer, as text
)
.build()
);
Read it from the inside out: put message into a TextContent, put that into a CallToolResult, and return it. The only word you usually change is message.
The menu and the lookup: list() and find()
Our class implements McpSyncToolRepository, which asks for two methods:
list()answers “what tools do you have?” It returns the menu: every tool’s definition from ①.find()answers “give me the tool called X”. It returns the tool, ornullif there is no such tool.
When you add a second tool later, you add it in both places. Nothing else changes.
The wiring in main()
McpServer server = McpServer.builder()
.serverInfo(McpSchema.Implementation.builder("hello-world-server", "1.0.0").build()) // name + version
.feature(ToolsFeature.ofSync(new HelloWorldMCPServer())) // "this server offers tools"
.build();
StdioMcpTransport transport = new StdioMcpTransport(server, McpJsonDefaults.getMapper()); // talk over STDIO
transport.start().block(); // keep serving until stdin closes
This block is the same for every STDIO server. Change only the server name and version.
The complete server
src/main/java/org/example/server/HelloWorldMCPServer.java:
package org.example.server;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.modern.McpSchema;
import io.modelcontextprotocol.modern.server.McpRequestContext;
import io.modelcontextprotocol.modern.server.McpServer;
import io.modelcontextprotocol.modern.server.McpSyncResponse;
import io.modelcontextprotocol.modern.server.feature.McpSyncTool;
import io.modelcontextprotocol.modern.server.feature.McpSyncToolRepository;
import io.modelcontextprotocol.modern.server.feature.ToolsFeature;
import io.modelcontextprotocol.modern.server.feature.ToolsPage;
import io.modelcontextprotocol.modern.server.transport.StdioMcpTransport;
import java.util.List;
import java.util.Map;
public class HelloWorldMCPServer implements McpSyncToolRepository {
private final McpSyncTool helloTool = McpSyncTool.of(
// ① Tool definition: name, inputs, description
McpSchema.Tool.builder("sayHello", Map.of(
"type", "object",
"properties", Map.of("name", Map.of("type", "string")),
"required", List.of("name")))
.description("Greets a person by name")
.build(),
(ctx, request) -> {
System.err.println("========== HANDLER STARTED ==========");
System.err.println("Arguments: " + request.arguments());
// ② Handler logic
String name = (String) request.arguments().get("name");
String message = "Hello, " + name + "!";
System.err.println("Executing: " + message);
// ③ Response
return McpSyncResponse.result(
McpSchema.CallToolResult.builder()
.addContent(McpSchema.TextContent.builder(message).build())
.build()
);
}
);
@Override
public ToolsPage list(McpRequestContext ctx, String cursor) {
System.err.println("Listing tools");
return ToolsPage.of(List.of(this.helloTool.definition()));
}
@Override
public McpSyncTool find(McpRequestContext ctx, String name) {
System.err.println("finding tool " + name);
if ("sayHello".equals(name)) {
return helloTool;
}
return null;
}
public static void main(String[] args) {
McpServer server = McpServer.builder()
.serverInfo(McpSchema.Implementation.builder("hello-world-server", "1.0.0").build())
.feature(ToolsFeature.ofSync(new HelloWorldMCPServer()))
.build();
StdioMcpTransport transport = new StdioMcpTransport(server, McpJsonDefaults.getMapper());
System.err.println("Running MCP Server");
transport.start().block(); // serve until stdin is closed
}
}
Step 4: Package the server as a runnable jar
Remember how STDIO works: the client starts the server as a separate process with java -jar .... So the server must be a single jar that runs on its own, with the MCP SDK and every other library packed inside. That’s called a “fat jar” or “uber jar”.
The maven-shade-plugin builds it. Add this to pom.xml, after </dependencies>:
<build>
<!-- The jar will be named target/helloworld-mcp-server.jar -->
<finalName>helloworld-mcp-server</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<!-- Tells java -jar which class has main() -->
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.example.server.HelloWorldMCPServer</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Two lines matter most:
finalNamesets the jar’s file name. The client will look for exactly this file.mainClasspoints to the server’smain()method, sojava -jarknows where to start.
Now build it:
mvn clean package
You should see target/helloworld-mcp-server.jar. Every time you change the server code, run this command again, or the client keeps starting the old jar.
Step 5: Build the MCP client
The client does three things, in this order:
- Start the server jar over STDIO.
- List the tools the server offers (read the menu).
- Call
sayHellowith an argument (place the order).
src/main/java/org/example/client/HelloWorldMCPClient.java:
package org.example.client;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.modern.McpSchema;
import io.modelcontextprotocol.modern.client.McpClient;
import io.modelcontextprotocol.modern.client.McpSyncClient;
import io.modelcontextprotocol.modern.client.transport.StdioMcpClientTransport;
import java.util.Map;
public class HelloWorldMCPClient {
public static void main(String[] args) {
// 1. START: the command that launches the server (same as typing it in a terminal)
ServerParameters params = ServerParameters.builder("java")
.args("-jar", "target/helloworld-mcp-server.jar")
.build();
// try-with-resources stops the server process when we are done
try (StdioMcpClientTransport transport = StdioMcpClientTransport.builder(params).start()) {
McpSyncClient client = McpClient.sync(transport).build();
// 2. LIST: ask the server for its tools
for (McpSchema.Tool tool : client.listTools().list().tools()) {
System.out.println(tool.name());
}
// 3. CALL: call a tool by name, with its arguments
var result = client.tool("sayHello")
.arguments(Map.of("name", "Prasad"))
.call();
System.out.println("\nServer response:");
System.out.println(result.content());
}
}
}
Match the client to the server like this:
| In the client | Must match in the server |
|---|---|
"target/helloworld-mcp-server.jar" |
<finalName> in pom.xml |
client.tool("sayHello") |
The name in ① Tool.builder("sayHello", ...) |
Map.of("name", "Prasad") |
The property name in ① and get("name") in ② |
The client can use System.out freely. Only the server’s stdout is reserved for the protocol.
In a real host app, step 3 is not hard-coded. The host sends the tool list from step 2 to the LLM, and the LLM decides to call sayHello with {"name": "Prasad"} because the user typed “say hello to Prasad”.
Step 6: Run it and read the logs
Build the server jar, then run the client from the project folder (so the path target/... resolves):
mvn clean package
java -cp target/helloworld-mcp-server.jar org.example.client.HelloWorldMCPClient
The shaded jar contains the client class too, so this one jar runs both. You can also just run HelloWorldMCPClient.main() from your IDE.
On the client side you’ll see the tool name, then the response, which contains Hello, Prasad!:
sayHello
Server response:
[... text=Hello, Prasad! ...]
The exact format of that last line depends on how the SDK prints a TextContent. The important part is Hello, Prasad!.
Why we added slf4j-simple
When something fails in an MCP setup, the error is usually hidden inside the server process, which you can’t see directly. Two things make it visible:
- Your own
System.errlines. “Listing tools”, “finding tool sayHello”, “HANDLER STARTED”,Arguments: {name=Prasad}. Following them tells you exactly how far a request got. - The SDK’s own logs. The MCP SDK logs through SLF4J. Without a logging library on the classpath, SLF4J prints a “no providers found” warning and silently drops every SDK log line.
slf4j-simplecatches them and writes them to stderr, the safe stream, so they never mix with the protocol on stdout.
Want more detail while debugging? Start the server with -Dorg.slf4j.simpleLogger.defaultLogLevel=debug added to the java command in ServerParameters.
| Symptom | Likely cause | Fix |
|---|---|---|
| Client hangs or fails to parse a message | The server printed to System.out |
Use System.err in the server |
| Jar not found | Client run from the wrong folder, or no build yet | Run mvn clean package from the project root |
| Change in server code has no effect | Client still starts the old jar | Rebuild the jar |
| “No main manifest attribute” | mainClass missing or misspelled |
Check the shade plugin’s <mainClass> |
| Tool not found | Name in client.tool(...) differs from ① or from find() |
Make all three names identical |
Cheat sheet: building your next MCP server
To turn this HelloWorld into any tool you like, copy the project and change only these spots:
| To… | Change |
|---|---|
| Rename the tool | ① the name in Tool.builder(...), the check in find(), and client.tool(...) |
| Add or change inputs | ① properties and required; ② request.arguments().get(...) |
| Help the LLM pick the tool | ① .description(...) |
| Change what the tool does | ② the handler body |
| Change what comes back | ③ the text inside TextContent |
| Add a second tool | A new McpSyncTool field, then add it to list() and find() |
Everything else (the BOM, the transport, main(), the shade plugin) stays the same.
FAQ
Do I need an LLM or API key for this? No. The client calls the tool directly. An LLM comes in when you plug this server into a host app.
Why STDIO and not HTTP? STDIO is the simplest transport for local tools: no ports, no network, no auth. Use HTTP when the server runs on another machine.
Why can’t the server use System.out? With STDIO, stdout carries the protocol messages. Any extra text corrupts them. Log to System.err.
What’s next
Want the theory behind what you just built (why JSON-RPC, what tools/list and tools/call look like on the wire, stdio vs HTTP)? Read What is MCP?.
Next in this MCP thread: connect this same server to a real AI host so an LLM decides when to call sayHello, and build a server with more useful tools. New to calling models from Java? Start with Call a local LLM from Java with Ollama.
See it in action
Prefer watching? This video walks through the same ideas with live, hands-on demos.
Watch on YouTube ↗
Comments