One Annotation to Rule AI: um-sdk Turns Java Methods into MCP Tools
I Built a Java Capability Pack: Let AI Directly Call Your Business Code
One annotation turns your business methods into tools usable by large models. The source code in this article is open source: https://gitee.com/wizard-cn/um-sdk
Hello everyone, I am Xiao Wu.
Today I'm not discussing concepts, but something I built myself and use every day — um-sdk.
The problem it solves is simple: In Java projects, the things that need to be rewritten over and over — can they be written only once?
Tool classes, enums, payment, email, caching... every project has to copy them again. More troublesome is that in the past two years, everyone has been integrating large models and AI assistants, but how to make business code callable by AI is yet another set of manual labor.
So I gathered all of this into a package, and also welded the AI layer in.
Conclusion First: What It Can Actually Do
In one sentence: One dependency eliminates 80% of the repetitive wheel-building work in daily Java development, and also lets AI directly call your business methods.
For example, you're writing an order system and want an AI assistant to query orders. The traditional way is to study the MCP protocol, hand-write JSON-RPC, manually write parameter descriptions... that takes a long time.
With um-sdk, you only need this:
public class OrderTools {
@McpTool(name = "query_order", description = "Query order details by order number")
public String query(@McpParam(name = "orderNo", description = "Order number", required = true) String orderNo) {
return JacksonUtils.toJson(orderService.findByNo(orderNo));
}
}
That one piece of code turns your order query capability into an AI-callable tool.
Then start a Stdio service, configure the address in Cursor or Claude, and the AI can call your method on its own:
McpServer server = McpServer.builder()
.name("Order MCP")
.version("1.0.0")
.transport(Transport.stdio())
.scan(OrderTools.class)
.build();
server.start();
This is the most interesting part of um-sdk for me — AI capability is not an external add-on, but a first-class citizen natively.
Why It Exists: Why I Had to Build My Own
Let me clarify the background first: this package didn't come out of nowhere.
I've been writing Java for over a decade. Over the years, I've found myself and my team repeating three things:
First, tool classes are copied and pasted everywhere.
Every new project starts by copying DateUtils, HttpUtils, AesUtils from the old project. Then you have to modify them — because this project uses JDK 17, that one JDK 8; this one uses hutool, that one forbids third-party dependencies. I've written the same MD5 logic at least twenty times.
Second, enums are never enough. The business side wants to add an order status; you have to change code and release. The business side wants English display; you have to stuff translations into every enum. The business side wants the dictionary table to be configurable; you have to rewrite everything.
Third, the new manual labor of the AI era. After 2024, almost every project started integrating large models. But you quickly discover: OpenAI has one SDK, DeepSeek another, Bailian another, local Ollama yet another. Wanting to switch models means rewriting the integration layer.
These three things stacked up gave birth to um-sdk's positioning:
Put all the repetitive parts that every Java project has to write into one package, and also put all the repetitive parts that every AI application has to write into the same package.
The applicable scenarios are broad: Spring Boot microservices, pure Java command-line tools, edge devices, Serverless functions, even embedded Java scenarios.
First Look at the Overall Architecture
um-sdk is organized along two technology stacks, with a shared base module at the bottom:
graph TB
subgraph 应用宿主层
SA[um-spring-starter<br/>Spring Boot 宿主]
UA[um-ultra-starter<br/>轻量框架宿主]
end
subgraph 框架层
SP[Spring Boot<br/>宿主自带, compileOnly]
UL[um-ultra<br/>零依赖 IoC/AOP]
end
subgraph um-ultra 生态
UW[um-ultra-web<br/>Netty]
UD[um-ultra-db<br/>MyBatis-Plus]
UC[um-ultra-cache<br/>三介质缓存]
UN[um-ultra-nacos<br/>注册配置]
end
subgraph 基础能力层
UT[um-util<br/>工具集]
UE[um-enums<br/>动态枚举]
EP[um-epay<br/>支付]
ML[um-mail<br/>邮件]
MC[um-mcp<br/>MCP 协议]
AG[um-agent<br/>LLM Agent]
end
SA --> SP
SA --> UT
SA --> UE
SA --> EP
SA --> ML
SA --> MC
SA --> AG
UA --> UL
UA --> UW
UA --> UD
UA --> UC
UA --> UN
UA --> EP
UA --> ML
UA --> MC
UA --> AG
UL --> UT
UL --> UE
UW --> UL
UD --> UL
UC --> UL
UN --> UL
AG --> MC
MC --> UT
Pay attention to two places:
Left, um-spring-starter — You already have a Spring Boot project and want to add AI capabilities? Just add this dependency; no architecture changes. Spring dependencies are only compileOnly, so you keep full control of versions.
Right, um-ultra-starter — You want to completely leave Spring and run a lightweight service with millisecond startup? Add this; it includes IoC, AOP, Web, DB, cache, registry — everything.
The base is 6 foundation modules, with zero mandatory framework dependencies — any Java project can use them directly.
Five-Minute Getting Started: Three Dependencies to Run
Step 1: Add the Repository
<repositories>
<repository>
<id>um-nexus</id>
<url>https://nexus.umnet.com.cn/repository/um-maven/</url>
</repository>
<repository>
<id>aliyun-public</id>
<url>https://maven.aliyun.com/repository/public/</url>
</repository>
</repositories>
Step 2: Add Dependencies
If you only want one capability, add just that module:
implementation 'cn.com.umnet:um-util:1.3.21-SNAPSHOT'
To add AI capabilities:
implementation 'cn.com.umnet:um-mcp:1.3.21-SNAPSHOT'
implementation 'cn.com.umnet:um-agent:1.3.21-SNAPSHOT'
For a Spring Boot project full set:
implementation 'cn.com.umnet:um-spring-starter:1.3.21-SNAPSHOT'
Step 3: Write Code
Start with the simplest — tool classes, static calls, no container needed:
// Safe execution: exceptions don't crash business, failures get default values
int size = TryUtils.get(() -> Integer.parseInt(input)).orElse(0);
// One-line JWT signing and verification
String token = SimpleJwtUtils.sign("userId=1001", secret, 3600);
String data = SimpleJwtUtils.verify(token, secret);
// Tree structure in one line
List<TreeNode> menu = TreeBuilder.build(flatList, "id", "parentId", "children");
// HTTP call with retry
RetryPolicy policy = RetryPolicy.of(3, Duration.ofSeconds(1), 2.0);
String resp = SimpleHttpUtils.getWithRetry(url, policy);
No Spring, no startup class, no configuration file. Import and use.
That's the design bottom line for um-util: Tool classes shouldn't require you to prepare a runtime environment for them.
Core Capabilities Explained
1. um-util: Making Tool Classes Thorough
um-util has over 20 static tool classes, grouped by purpose:
| Group | Representative Classes | What They Solve |
|---|---|---|
| Basics | StrUtils AssertUtils BeanUtils |
Strings, assertions, Bean copying |
| Crypto | AesUtils RsaUtils SignUtils |
Symmetric/asymmetric encryption, signing/verification |
| Data | JacksonUtils TreeBuilder |
Unified JSON, tree structures |
| Network | SimpleHttpUtils RetryPolicy |
HTTP calls, retry policies |
| Utilities | SimpleJwtUtils QrcodeUtils TryUtils ProfilerUtils |
JWT, QR codes, safe execution, timing analysis |
| Monitoring | Jvm Server |
JVM and server runtime metrics |
Personally, my favorite is TryUtils. The most annoying thing in Java is try-catch nesting; a method with three try-catches destroys readability.
TryUtils compresses it to one line:
// Traditional way
int result;
try {
result = Integer.parseInt(input);
} catch (NumberFormatException e) {
result = 0;
}
// TryUtils way
int result = TryUtils.get(() -> Integer.parseInt(input)).orElse(0);
Behind this one line, hundreds of repeated try-catches get deleted.
2. um-enums: Bringing Enums to Life
Ordinary Java enums are static — hard-coded into the code, changing requires a release.
um-enums does two things:
First, descriptions support internationalization. An enum item is called "已支付" in Chinese and "Paid" in English, without needing a bunch of translation methods in the enum.
Second, it supports SPI dynamic supply. Through the EnumProvider interface, you can pull enum items from a database or config center at runtime. The business side wants to add a status? Just add a row to the dictionary table — no release needed.
// Get multilingual description by code
String zh = EnumUtils.getDescription(OrderStatus.class, "PAID", "zh-CN");
String en = EnumUtils.getDescription(OrderStatus.class, "PAID", "en");
// Access properties through a proxy
EnumProxy<OrderStatus> proxy = EnumUtils.proxy(OrderStatus.class);
OrderStatus s = proxy.valueOf("PAID");
3. um-mcp: The Bridge for AI Calls (Core Highlight)
Let me expand on this because it's the most forward-looking module in the entire SDK.
What is MCP? Simply put, it's a standard protocol that lets large models call external tools. An analogy: USB is the standard interface for connecting devices to computers; MCP is the standard interface for AI to connect to business systems.
um-sdk implements MCP as an annotation-driven mini framework, providing three transport methods:
| Transport | Use Case | Analogy |
|---|---|---|
Stdio |
Called directly by Cursor/Claude | Printer plugged into the computer, exclusive |
HTTP |
Shared by multiple Agents | Network printer, anyone can connect |
Embedded |
In-process direct connection, local testing | Built-in module, no external connection needed |
The annotation system is simple; four annotations are enough:
| Annotation | Purpose |
|---|---|
@McpTool |
Declare a tool method |
@McpParam |
Declare tool parameters (including description, required flag) |
@McpResource |
Declare a resource (e.g., cache, file) |
@McpPrompt |
Declare a prompt template |
Complete example:
public class WeatherTools {
@McpTool(name = "get_weather", description = "Query weather for a specified city")
public String getWeather(
@McpParam(name = "city", description = "City name", required = true) String city) {
return WeatherClient.query(city);
}
@McpResource(uri = "weather://cache", name = "Weather cache")
public String getCache() {
return JacksonUtils.toJson(WeatherCache.getAll());
}
}
Note the description field — it's written for the large model. The clearer your description, the more accurately AI calls it. Anyone who has written prompts knows how important this is.
4. um-agent: Five Models, One-Line Switch (Core Highlight)
Tools aren't enough; you also need an Agent to orchestrate the conversation between the large model and tools.
um-agent provides a unified abstraction supporting five platforms:
Agent agent = AgentBuilder.create()
.platform(LlmPlatform.DEEPSEEK, c -> c.apiKey(key).model("deepseek-chat"))
.systemPrompt("You are an operations assistant, able to call tools to check system status")
.mcp("http://localhost:9005/mcp") // Automatically mount remote MCP tools
.memory(new FileMemory("./.agent-memory"))
.build();
agent.chat("Check what alerts are there today and summarize into a table", event -> {
if (event.type() == StreamType.CONTENT_DELTA) {
System.out.print(event.delta());
}
});
Switching to OpenAI only requires changing one line:
.platform(LlmPlatform.OPENAI, c -> c.apiKey(key).model("gpt-4o"))
It has several built-in capabilities I find very practical:
- Tool call loop — Automatically handles the loop of "model wants to call a tool → execute → return result to the model"
- Streaming output — Event callbacks output character by character, ideal for typewriter effects
- Memory — In-memory and file versions, session context can persist
- Skill plugins — Built-in database Skill, sandbox Skill
- Multi-model routing — Keyword routing + LLM classification routing, can route by task to different models to reduce costs
Here's a practical example of multi-model routing: route math questions to the cheap DeepSeek, code questions to gpt-4o, small talk to a small model. The same Agent, automatically routing by content, directly cuts costs.
Agent routerAgent = AgentBuilder.create()
.routing(RoutingModel.builder()
.addStrategy(new KeywordStrategy(Map.of(
"数学", "deepseek-math",
"代码", "gpt-4o",
"default", "gpt-4o-mini"
)))
.build())
.build();
5. um-ultra: A Lightweight Framework with Millisecond Startup (Differentiating Highlight)
This module took the most effort.
Why build it? Because Spring is too heavy.
When working on edge computing and some Serverless scenarios, I was tormented by Spring's startup time and memory usage. A service that only needs to expose three endpoints would have Spring eating hundreds of MB of memory and taking several seconds to start.
um-ultra's positioning is clear: It occupies the same ecological niche as Spring, but with zero third-party framework dependencies.
Only two small packages are included: snakeyaml (for parsing YAML) and asm (for bytecode enhancement). Startup is millisecond-level, memory is tens of MB.
Its core capabilities compared to Spring:
| Capability | um-ultra | Spring |
|---|---|---|
| IoC container | ✅ @Component @Inject |
✅ |
| AOP interception | ✅ MethodInterceptor |
✅ |
| Configuration injection | ✅ @Value with hot refresh |
✅ |
| Web server | ✅ Netty | ✅ Servlet |
| Transactions | ✅ @Transactional |
✅ |
| Multiple data sources | ✅ @DS |
✅ |
| Event bus | ✅ EventManager |
✅ |
Starting it is extremely simple:
public class DemoApp {
public static void main(String[] args) {
Ultra.run(DemoApp.class, args);
}
}
With that one line, a complete application runs.
Here's a complete small service:
@Controller
@Mapping("/user")
public class UserController {
@Inject
private UserService userService;
@GetMapping("/{id}")
public Object detail(@RequestParam("id") Long id) {
return userService.findById(id);
}
}
@Component
public class UserService {
@Inject
private UserMapper mapper;
@Transactional
public Object findById(Long id) {
return mapper.selectById(id);
}
}
If you've written Spring, you'll see this has almost zero learning cost. The annotation names are copied from Spring; migration is basically changing the imports.
um-ultra uses Plugin SPI for extensions, and ecosystem modules are assembled as needed:
| Module | Capability |
|---|---|
um-ultra-web |
Netty HTTP + routing + CORS/CSRF/XSS filters + WebSocket |
um-ultra-db |
Multiple data sources + MyBatis-Plus + declarative transactions |
um-ultra-cache |
Unified cache, three media types |
um-ultra-nacos |
Service discovery + config center |
6. um-ultra-cache: One Interface, Three Media Types
This is a module I recently added, solving an old problem: When the cache medium changes, so must the code.
In development you use memory, in production Redis, and for certain large-object scenarios you might want MongoDB... Each medium has its own API, and switching means changing code.
um-ultra-cache unifies it into a single UCache interface:
UCache cache = UCacheManager.create(
UCacheProperties.ofRedis("redis://127.0.0.1:6379", "", 0));
// Auto-load on miss, naturally prevents cache breakdown
User user = cache.getOrLoad("user:" + id, User.class, k -> userService.load(id));
// Simple distributed lock semantics
boolean locked = cache.putIfAbsent("lock:order:" + no, "1", Duration.ofSeconds(30));
// Directly access lower-level capabilities using Redisson when needed
RedissonClient client = cache.client(RedissonClient.class);
Three key designs:
First, getOrLoad naturally prevents cache breakdown. Redis uses a distributed lock, memory uses Caffeine atomic operations. The classic cache breakdown problem is blocked at the interface layer.
Second, change configuration to switch media. Only change one field in YAML:
app:
cache:
type: memory # change to redis / mongo
ttlSeconds: 1800
maxSize: 10000
Third, the client() escape hatch. I insist on this — a cache abstraction shouldn't lock away the lower layers. If you need Redisson's distributed collections or Mongo's aggregation queries, get the native client directly without going around the abstraction layer.
A good abstraction doesn't hide the bottom layer; it simplifies 80% of scenarios while leaving a door open for the remaining 20%.
A Table to Understand Applicable Scenarios
| Scenario | Recommendation | How to Use |
|---|---|---|
| Add AI / MCP capability to an existing project | ⭐⭐⭐⭐⭐ | Add um-mcp or um-agent, no architecture change |
| Need a unified tool / enum base library | ⭐⭐⭐⭐⭐ | Add um-util + um-enums, zero framework pollution |
| Edge devices, CLI, Serverless | ⭐⭐⭐⭐⭐ | Add um-ultra, millisecond startup and low memory |
| New enterprise microservices | ⭐⭐⭐ | Spring Cloud as the primary, um-sdk as a supplement |
| Strong compliance / depends on a mature community | ⭐⭐ | Wait for formal Release and improved documentation |
Honest Downsides
I've written only benefits so far, so let me honestly mention the problems.
First, the version is still SNAPSHOT.
1.3.21-SNAPSHOT is a snapshot version; the API has no promise of full stability. In production, lock a specific version, or wait for a formal Release.
Second, it depends on a private repository.
Artifacts are published on nexus.umnet.com.cn, and external teams need repository access. That's also why I open-sourced it on Gitee — the source code is visible and tangible; you can clone it and build locally.
git clone https://gitee.com/wizard-cn/um-sdk.git
cd um-sdk
./gradlew clean build -x test
Third, um-ultra's ecosystem is not as mature as Spring's. It only covers core IoC/AOP/Web/DB/Cache/Nacos. Spring's Security, Batch, Cloud Gateway, Actuator have no counterparts. For complex enterprise scenarios, I still recommend Spring as the primary.
Fourth, the community is small. This is a personal system; available resources when facing problems are limited. The upside is that all source code is in the repository; the downside is that troubleshooting mostly depends on reading code and figuring things out yourself.
Fifth, um-ultra has a learning curve. Although the annotations are copied from Spring, the Plugin SPI extension mechanism and configuration hot-update design need to be re-learned. Teams deeply bound to Spring will have short-term migration costs.
I'd rather write all this out clearly than have you discover it after importing. The worst thing about tool selection isn't having flaws; it's not being told about the flaws.
Comparison with Similar Tools
| Tool | Advantages | Disadvantages | Use Cases |
|---|---|---|---|
| um-sdk | MCP/Agent natively built-in, zero mandatory framework dependencies, lightweight framework optional | SNAPSHOT, small community, private repo | Java projects needing AI capabilities or a unified base library |
| Hutool | Extremely comprehensive tool classes, mature ecosystem, large community | No framework layer, no AI capability | Only need tool classes |
| Spring Boot | Most complete ecosystem, largest community, enterprise standard | Large size, slow startup, heavy dependencies | Traditional enterprise microservices |
| LangChain4j | Strong LLM orchestration capabilities on the Java side | Requires manual MCP wrapping, relatively heavy | Pure AI applications |
The differentiation of um-sdk: It puts "business base capabilities" and "AI call capabilities" in the same package, and gives you an exit to choose either Spring or a lightweight framework.
In Conclusion
um-sdk started as my personal project to write less repetitive code.
Later I realized that the truly scarce resource in the AI era isn't models, but "business structures that models can understand and call".
An @McpTool annotation is essentially writing instructions for a large model — telling it "there's a capability here, here are the parameters, and what problem it solves."
The earlier you do this, the higher your system's reusability in the AI era.
In one sentence: um-sdk is a Java capability pack that puts repetitive work into one dependency and turns AI calls into one annotation.
About Us
The source code is open-sourced on Gitee under the Apache-2.0 license. Stars and issues are welcome:
- Repository: https://gitee.com/wizard-cn/um-sdk
- Branch:
master - License: Apache-2.0
If you're also wrestling with "how to make business code callable by AI", feel free to reach out.
I hope this article helps! If you have any questions, feel free to discuss. Follow the 小巫编程室 official account for more content. Likes and shares are also appreciated. Your support is the biggest encouragement for me. 🎉🎉🎉🚀🚀🚀
References
- um-sdk source repository https://gitee.com/wizard-cn/um-sdk
- MCP protocol official specification https://modelcontextprotocol.io
- MyBatis-Plus documentation https://baomidou.com