MCP Tutorial
In this tutorial, you will:
- build a simple MCP server in Java
- expose a tool (
add_numbers) - build the project in IntelliJ
- connect it to Codex and Claude CLI
- call it from natural language
MCP (Model Context Protocol) lets AI tools like Codex and Claude:
call your code as tools
Think of it like:
- REST → for frontend
- MCP → for AI
Create a new Maven project in IntelliJ:
- Open IntelliJ → New Project
- Choose Maven
- Set:
- GroupId:
demo - ArtifactId:
mcp-demo
- GroupId:
- Click Create
Edit your pom.xml:
<dependencies>
<dependency>
<groupId>io.modelcontextprotocol</groupId>
<artifactId>mcp</artifactId>
<version>0.18.1</version>
</dependency>
</dependencies>
Create a file:
src/main/java/demo/McpServerApp.java
Add this code:
package demo;
import io.modelcontextprotocol.server.McpServer;
public class McpServerApp {
public static void main(String[] args) {
var server = McpServer.builder()
.name("demo-mcp-server")
.version("1.0.0")
.build();
server.tool("add_numbers", "Add two numbers", input -> {
int a = input.getInt("a");
int b = input.getInt("b");
return "Result: " + (a + b);
});
// Start MCP server over STDIO
server.startStdio();
}
}
STDIO = standard input/output
👉 Instead of HTTP, the AI talks to your program directly via:
- input stream
- output stream
✔ simplest setup ✔ perfect for local tools
Use IntelliJ (not terminal):
- Open the Maven tool window (right side)
- Expand your project → Lifecycle
- Double-click clean
- Double-click package
You should now have a jar in:
target/mcp-demo-1.0-SNAPSHOT.jar
Run:
codex mcp add demo-server \
--command java \
--arg -jar \
--arg /FULL/PATH/TO/target/mcp-demo-1.0-SNAPSHOT.jar
👉 Replace with your actual path!
Run:
claude mcp add demo-server \
--command java \
--arg -jar \
--arg /FULL/PATH/TO/target/mcp-demo-1.0-SNAPSHOT.jar
👉 Use the same jar path as above.
Codex:
codex mcp list
Claude CLI:
claude mcp list
You should see demo-server in both outputs.
In Codex, try:
Use the add_numbers tool with a=5 and b=7
In Claude CLI, try:
Use the add_numbers tool with a=5 and b=7
👉 Both clients will:
- detect your tool
- call your Java server
- return the result
You built:
AI → MCP → your Java code
Instead of:
Frontend → REST → backend
MCP is just another interface to your backend logic
Add another tool:
server.tool("get_time", "Get current time", input -> {
return java.time.Instant.now().toString();
});
- Where does the logic live?
- What is the difference between MCP and REST?
- Why might AI tools need this instead of HTTP APIs?
- Did you run
codex mcp addorclaude mcp add? - Did you restart the client?
- Is the
.jarpath correct? - Does
java -jar ...run manually?
- Check for missing dependencies
- Run manually to debug:
java -jar target/mcp-demo-1.0-SNAPSHOT.jar
You can now:
- connect MCP to real services (database, APIs)
- combine with Javalin
- build AI-powered backend features