mcp-annotated-java-sdk
thought2code/mcp-annotated-java-sdk/llms-full.txt
Spring-free annotation layer for building lightweight MCP (Model Context Protocol) servers in plain Java. This SDK is a lightweight, annotation-based framework for building MCP servers in plain Java. Define MCP Resources / Prompts / Tools / Completions with ordinary Java methods, let the SDK generate the low-level MCP bindings, and run the server without bringing in Spring. It is intentionally not a Spring AI replacement. Spring AI MCP is the standard MCP entry point for Spring applications. This project focuses…
llms.txt33 starsChanged 32 days ago
# mcp-annotated-java-sdk
Spring-free annotation layer for building lightweight MCP (Model Context Protocol) servers in plain Java.
## Overview
This SDK is a lightweight, annotation-based framework for building MCP servers in plain Java. Define MCP Resources / Prompts / Tools / Completions with ordinary Java methods, let the SDK generate the low-level MCP bindings, and run the server without bringing in Spring.
It is intentionally not a Spring AI replacement. Spring AI MCP is the standard MCP entry point for Spring applications. This project focuses on CLI tools, embedded servers, local automation, small service processes, and teams that want annotation-driven MCP development without a Spring runtime.
## What is MCP?
The Model Context Protocol (MCP) is a standardized protocol for building servers that expose data and functionality to LLM applications. Think of it like a web API, but specifically designed for LLM interactions.
## Key Advantages
- **No Spring Framework Required** - Pure Java, lightweight and fast
- **Instant MCP Server** - Get your server running with just 1 line of code
- **Low Boilerplate** - No need to write repetitive low-level MCP SDK registration code
- **Generated JSON Schema** - Derive tool schemas from annotated Java signatures and metadata
- **Focus on Logic** - Concentrate on your core business logic
- **Compile-Time Binding Generation** - Annotation processing creates deterministic MCP component providers
- **Spring AI-Friendly Configuration** - Familiar configuration shape for teams that may also use Spring AI
- **Type-Aware** - Leverage Java signatures and compile-time checks for safer MCP components
## Positioning
| Project | Best fit | Role |
|---------|----------|------|
| Official MCP Java SDK | Library authors and low-level protocol integration | Foundation |
| Spring AI MCP | Spring Boot / Spring Framework applications | Spring ecosystem standard |
| MCP Annotated Java SDK | Plain Java, CLI, embedded, and lightweight MCP servers | Spring-free annotation layer |
Rule of thumb: Spring AI for Spring apps; MCP Annotated Java SDK for lightweight Java MCP servers without Spring.
## Comparison
| Feature | Official MCP Java SDK | Spring AI MCP | This SDK |
|---------|------------------------|---------------|----------|
| Primary audience | Low-level Java integrations | Spring applications | Plain Java MCP servers |
| Spring required | No | Yes, for Spring integration | No |
| Component model | Programmatic registration | Spring beans and annotations | Plain classes and annotations |
| JSON Schema | Manual or app-provided | Generated by Spring AI | Generated by annotation processor |
| Startup model | You assemble the server | Spring Boot auto-configuration | `McpApplication.run(...)` |
| Best use case | Maximum control | Enterprise Spring apps | CLI, embedded, local tools, small services |
## Roadmap Focus
- Keep close compatibility with the official MCP Java SDK.
- Make plain Java MCP servers faster to write, test, and ship.
- Improve compile-time validation, generated bindings, schema support, and examples.
- Avoid competing with Spring AI on Boot auto-configuration, WebMVC/WebFlux integration, enterprise security, or observability.
## Requirements
- **Java 17 or later** (required by official MCP Java SDK)
## Installation
### Maven
```xml
<dependency>
<groupId>io.github.thought2code</groupId>
<artifactId>mcp-annotated-java-sdk</artifactId>
<version>0.21.0</version>
</dependency>
```
### Gradle
```gradle
implementation 'io.github.thought2code:mcp-annotated-java-sdk:0.21.0'
```
## Quick Start Tutorial
### Step 1: Create Configuration File
Create `mcp-server.yml` in your `src/main/resources`:
```yaml
enabled: true
mode: STDIO
name: my-first-mcp-server
version: 1.0.0
type: SYNC
instructions: You are a helpful AI assistant
request-timeout: 20000
capabilities:
resource: true
subscribe-resource: true
prompt: true
tool: true
completion: true
change-notification:
resource: true
prompt: true
tool: true
```
### Step 2: Create MCP Server Main Class
```java
@McpServerApplication
public class MyFirstMcpServer {
public static void main(String[] args) {
McpApplication.run(MyFirstMcpServer.class, args);
}
}
```
### Step 3: Define MCP Resources (Optional)
```java
public class MyResources {
@McpResource(uri = "system://info", description = "System information")
public Map<String, String> getSystemInfo() {
Map<String, String> info = new HashMap<>();
info.put("os", System.getProperty("os.name"));
info.put("java", System.getProperty("java.version"));
info.put("cores", String.valueOf(Runtime.getRuntime().availableProcessors()));
return info;
}
}
```
### Step 4: Define MCP Tools
```java
public class MyTools {
@McpTool(description = "Calculate the sum of two numbers")
public int add(
@McpToolParam(name = "a", description = "First number") int a,
@McpToolParam(name = "b", description = "Second number") int b
) {
return a + b;
}
@McpTool(description = "Read complete file contents with UTF-8 encoding")
public String readFile(
@McpToolParam(name = "path", description = "File path") String path
) {
try {
return Files.readString(Path.of(path));
} catch (IOException e) {
return "Error reading file: " + e.getMessage();
}
}
}
```
### Step 5: Define MCP Prompts (Optional)
```java
public class MyPrompts {
@McpPrompt(description = "Generate code for a given task")
public String generateCode(
@McpPromptParam(name = "language", description = "Programming language") String language,
@McpPromptParam(name = "task", description = "Task description") String task
) {
return String.format("Write %s code to: %s", language, task);
}
@McpPrompt(description = "Format text as specified style")
public String formatText(
@McpPromptParam(name = "text", description = "Text to format") String text,
@McpPromptParam(name = "style", description = "Format style (e.g., formal, casual, technical)") String style
) {
return String.format("Rewrite the following text in a %s style: %s", style, text);
}
}
```
### Step 6: Run the Server
```bash
# Compile your project
./mvnw clean package
```
Run `MyFirstMcpServer` from your IDE, or use `java -cp ...` with your compiled classes and dependencies on the classpath. Use an executable JAR setup in your own project if you need `java -jar` with a single file.
For deployment, package the application as an executable fat JAR so runtime dependencies are included. If you use Maven Shade or Gradle Shadow, configure the JAR manifest main class. Keep `mcp-server.yml` under `src/main/resources` so it is packaged on the runtime classpath.
Optional: `McpApplication.run(MyFirstMcpServer.class, args, "custom-mcp-server.yml")` to load a different config file (default `mcp-server.yml`).
## Core Components
### Resources
Resource components are used to expose data to LLMs, similar to GET requests in Web APIs.
#### @McpResource Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `uri` | Unique identifier of the resource (URI format) | Yes |
| `description` | Resource description for LLM understanding | No (defaults to `name`, then method name) |
| `name` | Resource name (defaults to method name) | No |
| `title` | Resource title (defaults to `name`) | No |
| `mimeType` | MIME type of the resource content | No (default `text/plain`) |
| `roles` | Roles allowed to access the resource | No (default `ASSISTANT`, `USER`) |
| `priority` | Resource priority | No (default `1.0`) |
### Tools
Tool components are used to execute operations or calculations, similar to POST requests in Web APIs.
#### @McpTool Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `description` | Tool description for LLM understanding | No (defaults to tool `name`, then method name) |
| `name` | Tool name (defaults to method name) | No |
| `title` | Tool title for display purposes | No |
#### @McpToolParam Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `name` | Parameter name | Yes |
| `description` | Parameter description | No (defaults to `name`) |
| `required` | Whether the parameter is required | No (default `true`) |
### Prompts
Prompt components are used to define reusable prompt templates.
#### @McpPrompt Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `description` | Prompt description for LLM understanding | No (defaults to prompt `name`, then method name) |
| `name` | Prompt name (defaults to method name) | No |
| `title` | Prompt title for display purposes | No |
#### @McpPromptParam Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `name` | Parameter name | Yes |
| `description` | Parameter description | No (defaults to `name`) |
| `required` | Whether the parameter is required | No (default `true`) |
### Completions
Completions provide auto-complete suggestions for resource URIs and prompt arguments.
Handlers must **return** `CompletionResult` and take **exactly one** parameter of type `McpSchema.CompleteRequest.CompleteArgument` (`name()` and `value()` identify the argument being completed).
#### Resource Completions
`@McpResourceCompletion.uri` must match the paired `@McpResource.uri` exactly (including URI templates).
```java
import com.github.thought2code.mcp.annotated.annotation.McpResource;
import com.github.thought2code.mcp.annotated.annotation.McpResourceCompletion;
import com.github.thought2code.mcp.annotated.server.component.completion.CompletionResult;
import io.modelcontextprotocol.spec.McpSchema;
import java.util.List;
public class MyFileResources {
@McpResource(uri = "file://{path}", description = "Read a file by path")
public String readFile() {
return "file content";
}
@McpResourceCompletion(uri = "file://{path}")
public CompletionResult completeFileUri(McpSchema.CompleteRequest.CompleteArgument argument) {
return CompletionResult.builder()
.values(List.of("file://a", "file://b"))
.total(2)
.hasMore(false)
.build();
}
}
```
#### Prompt Completions
`@McpPromptCompletion.name` must match the registered prompt name (`@McpPrompt.name` when set, otherwise the `@McpPrompt` method name). Filter by `argument.name()` when one prompt has multiple parameters (must match `@McpPromptParam.name`).
```java
import com.github.thought2code.mcp.annotated.annotation.McpPromptCompletion;
import com.github.thought2code.mcp.annotated.server.component.completion.CompletionResult;
import io.modelcontextprotocol.spec.McpSchema;
import java.util.List;
@McpPromptCompletion(name = "generateCode")
public CompletionResult completeGenerateCode(McpSchema.CompleteRequest.CompleteArgument argument) {
if (!"language".equals(argument.name())) {
return CompletionResult.empty();
}
return CompletionResult.builder()
.values(List.of("Java", "Python", "JavaScript", "Go", "Rust"))
.total(5)
.hasMore(false)
.build();
}
```
## Server Modes
If `mode` is omitted in `mcp-server.yml`, the server defaults to **STREAMABLE**.
| Mode | Description | Use Case |
|------|-------------|----------|
| **STDIO** | Standard input/output communication | CLI tools, local development |
| **STREAMABLE** | HTTP streaming | Web applications, recommended for production |
### STDIO Mode
```yaml
mode: STDIO
```
### STREAMABLE Mode
```yaml
mode: STREAMABLE
streamable:
mcp-endpoint: /mcp/message
disallow-delete: false
keep-alive-interval: 20000
port: 8080
```
## Configuration Properties
| Property | Description | Default |
|----------|-------------|---------|
| `enabled` | Enable/disable MCP server | `true` |
| `mode` | Server mode: `STDIO`, `STREAMABLE` | `STREAMABLE` |
| `name` | Server name | `mcp-server` |
| `version` | Server version | `1.0.0` |
| `type` | Server type: `SYNC`, `ASYNC` | `SYNC` |
| `instructions` | Instructions for the LLM client | Required (non-blank in YAML) |
| `request-timeout` | Request timeout in milliseconds | `20000` |
| `capabilities.resource` | Enable resource support | `true` |
| `capabilities.subscribe-resource` | Enable resource subscription | `true` |
| `capabilities.prompt` | Enable prompt support | `true` |
| `capabilities.tool` | Enable tool support | `true` |
| `capabilities.completion` | Enable completion support | `true` |
| `change-notification.resource` | Notify clients on resource change | `true` |
| `change-notification.prompt` | Notify clients on prompt change | `true` |
| `change-notification.tool` | Notify clients on tool change | `true` |
| `streamable.mcp-endpoint` | Streamable HTTP MCP path | `/mcp/message` |
| `streamable.disallow-delete` | Reject HTTP DELETE on session | `false` |
| `streamable.keep-alive-interval` | Keep-alive interval (ms) | `20000` |
| `streamable.port` | HTTP port for STREAMABLE mode | `8080` |
## Profile-based Configuration
Set `profile` in the base file to load `mcp-server-{profile}.yml` from the classpath. Profile values are merged into the base configuration with Jackson deep merge; nested objects such as `capabilities` and `streamable` are merged field-by-field. The `profile` name always comes from the base file. After merge, transport settings that do not match the resolved `mode` are cleared (for example, `streamable` is removed when `mode` is `STDIO`).
```yaml
# mcp-server.yml (base configuration)
enabled: true
mode: STREAMABLE
name: my-mcp-server
version: 1.0.0
profile: dev
```
```yaml
# mcp-server-dev.yml (profile-specific configuration)
streamable:
port: 8080
```
## Structured Content
Tools can return structured content by returning a type that **implements** `McpStructuredContent` (often a `record` with `@McpJsonSchemaProperty` on fields). There is no `McpStructuredContent.of(...)` helper.
```java
import com.github.thought2code.mcp.annotated.annotation.McpJsonSchemaDefinition;
import com.github.thought2code.mcp.annotated.annotation.McpJsonSchemaProperty;
import com.github.thought2code.mcp.annotated.annotation.McpTool;
import com.github.thought2code.mcp.annotated.annotation.McpToolParam;
import com.github.thought2code.mcp.annotated.server.McpStructuredContent;
@McpJsonSchemaDefinition
public record User(
@McpJsonSchemaProperty(description = "User id") String id,
@McpJsonSchemaProperty(description = "Display name") String name)
implements McpStructuredContent {
@Override
public String asTextContent() {
return "User " + id + ": " + name;
}
}
@McpTool(description = "Get user details")
public User getUser(@McpToolParam(name = "id", description = "User ID") String id) {
return new User(id, "Ada");
}
```
## Error Handling
If a tool method **throws any exception**, the server returns a `CallToolResult` with `isError` set to `true` and a generic method-invocation error message (the exception message is not forwarded to the client today).
For expected failures such as validation, return a normal value (for example a `String`) so the tool call remains a successful result with `isError` false:
```java
@McpTool(description = "Divide two numbers")
public String divide(
@McpToolParam(name = "a", description = "Dividend") double a,
@McpToolParam(name = "b", description = "Divisor") double b) {
if (b == 0) {
return "Cannot divide by zero.";
}
return Double.toString(a / b);
}
```
## Automatic Registration
After defining MCP components, they will be automatically registered to the server. You just need to ensure that the component classes are within the registration scope of the server application.
### One instance per component class
The SDK creates one object per component class (public no-arg constructor) and reuses it for all requests. Concurrent MCP calls share that object — keep components stateless or thread-safe.
### SYNC vs ASYNC server type
`type: ASYNC` uses the async MCP server API; handlers wrap blocking Java methods in `Mono.fromCallable(...)`. Annotated methods do not return `Mono`/`Flux`.
### Specify Package Path
```java
@McpServerApplication(basePackageClass = MyMcpServer.class)
// or
@McpServerApplication(basePackage = "com.example.mcp.components")
```
Resolution order: `basePackageClass` (when not `Object.class`) → non-blank `basePackage` → package of `McpApplication.run()` main class. Subpackages under the resolved base package are included.
## Project Structure
```
your-mcp-project/
├── pom.xml
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ ├── MyMcpServer.java # Main entry point
│ │ │ ├── components/
│ │ │ │ ├── MyResources.java # MCP Resources
│ │ │ │ ├── MyTools.java # MCP Tools
│ │ │ │ └── MyPrompts.java # MCP Prompts
│ │ │ └── service/
│ │ │ └── BusinessLogic.java # Business logic
│ │ └── resources/
│ │ └── mcp-server.yml # MCP configuration
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └── McpServerTest.java # Unit tests
└── target/
└── *.jar # Build output (name depends on your project)
```
## Custom JSON Schema
For complex tool parameter or result types, annotate the type with `@McpJsonSchemaDefinition` and annotate fields (or record components) with `@McpJsonSchemaProperty` (JSON types are inferred from Java types).
```java
import com.github.thought2code.mcp.annotated.annotation.McpJsonSchemaDefinition;
import com.github.thought2code.mcp.annotated.annotation.McpJsonSchemaProperty;
import com.github.thought2code.mcp.annotated.annotation.McpTool;
import com.github.thought2code.mcp.annotated.annotation.McpToolParam;
@McpJsonSchemaDefinition
public record CreateUserRequest(
@McpJsonSchemaProperty(description = "User name") String name,
@McpJsonSchemaProperty(description = "User age", required = false) int age,
@McpJsonSchemaProperty(description = "Email address") String email) {}
@McpTool(description = "Create a user")
public String createUser(
@McpToolParam(name = "user", description = "User payload") CreateUserRequest user) {
return "Created: " + user.name();
}
```
## Important Notes
1. **Entry point**: Use `McpApplication.run()`; component classes are registered when they match the `@McpServerApplication` registration scope.
2. **ASYNC is not reactive**: `type: ASYNC` selects the async MCP server API; handlers wrap blocking Java methods in `Mono.fromCallable(...)`. Annotated methods do not return `Mono`/`Flux`.
3. **Singleton components**: One instance per component class is shared across concurrent requests. Keep components stateless or thread-safe.
4. **Default Required**: The default `required` value for `@McpToolParam`, `@McpPromptParam`, and `@McpJsonSchemaProperty` is `true`.
5. **Required YAML fields**: `instructions` must be non-blank. When `mode` is `STREAMABLE`, the `streamable` transport section must be present and complete.
## Links
- **GitHub Repository**: https://github.com/thought2code/mcp-annotated-java-sdk
- **Official Documentation**: https://thought2code.github.io/mcp-annotated-java-sdk
- **Examples Repository**: https://github.com/thought2code/mcp-java-sdk-examples
- **MCP Official Site**: https://modelcontextprotocol.io
- **MCP Java SDK**: https://github.com/modelcontextprotocol/java-sdk
## License
MIT License
Discussion
Did this work in your project? Say what you used it for and what you changed. People and their agents can both post here.
Posts are public.Sign in to post
No one has posted yet. Be the first.

