Uncorp
Log In
Java & Full Stack5 min readUpdated 2026-11-11

How to Build Production MCP Servers & Tool-Calling AI Agents in Java 21 with Spring AI

A practical enterprise blueprint for Java backend developers: expose Spring Boot microservices, PostgreSQL queries, and internal APIs safely to LLMs using Spring AI and Model Context Protocol (MCP).

Naitik Tailor & Uncorp Engineering Faculty
Spring AI, Java 21 & Model Context Protocol (MCP) Server Vector Illustration
TL;DR — Key Engineering & Career Takeaways
  • Java developers no longer need to rewrite enterprise backends in Python to build Agentic AI—Spring AI brings first-class `ChatClient`, `@Tool` function calling, Structured Outputs, and Model Context Protocol (MCP) directly to Spring Boot 3.
  • An MCP Server in Spring Boot exposes your existing `@Service` business logic and JPA/PostgreSQL repositories as standardized, schema-validated tools that any MCP-compatible AI agent can invoke securely.
  • Always enforce human-in-the-loop approval or read-only DB roles when exposing mutation tools (`createRefund`, `updateOrderStatus`) over MCP.

1. Why Spring AI + MCP Is the Enterprise Standard for Java Teams

In Fortune 500 banks, insurance platforms, and Global Capability Centers (GCCs), core business logic, RBAC security rules, and transactional databases live inside Java and Spring Boot microservices. Moving that logic to a separate Python script just to call an LLM duplicates business rules and introduces security gaps.

With Spring AI and the Model Context Protocol (MCP), your existing Spring Boot microservice acts as an authoritative MCP Server—exposing strictly typed tools, resources, and prompt templates while preserving Spring Security authentication, Resilience4j rate limits, and Micrometer observability.

2. End-to-End Architecture: Spring AI ChatClient + MCP Server

Here is how a tool-calling AI request flows through a production Spring Boot 3 + Spring AI service:

Spring Boot 3 + Spring AI + MCP Tool Execution Flow
[React UI / API Client] ──► [Spring Boot REST Controller (@PostMapping /ai/assist)]
   │
   ▼
[Spring AI ChatClient + QuestionAnswerAdvisor (pgvector RAG)]
   ├──► 1. Sends User Prompt + Registered MCP Tool Schemas (JSON Schema) to LLM
   ├──► 2. LLM Returns `tool_call: checkOrderStatus({ orderId: 'ORD-902' })`
   ├──► 3. Spring AI MCP Client / @Tool Invokes `OrderService.getOrderStatus()` w/ JWT Context
   └──► 4. LLM Synthesizes Final Grounded Response (Mapped to Java `record` via BeanOutputConverter)
Core Spring AI Abstractions Every Java Developer Should Master
Spring AI ComponentJava / Spring EquivalentProduction Purpose
`ChatClient` (Fluent API)`RestClient` / `WebClient`Portable, model-agnostic interface for OpenAI, Anthropic Claude, Ollama, and Azure OpenAI
`BeanOutputConverter<T>`Jackson `ObjectMapper`Forces the LLM to return strictly validated JSON mapped directly to a Java 21 `record`
`@Tool` & MCP Server Starter`@RestController` / `@Service`Exposes Java methods as discoverable LLM tools with automatic JSON Schema generation
`VectorStore` (`PgVectorStore`)`JpaRepository`Stores and queries embeddings using HNSW cosine similarity inside PostgreSQL

3. Three Production Guardrails for Java AI Agents

Before deploying a tool-calling agent in Spring Boot, implement these three safeguards:

  • 1. Propagate SecurityContext to Tool Calls: Never execute an MCP tool with a global admin database connection; validate the caller's JWT tenant and user ID inside the `@Tool` method.
  • 2. Cap Maximum Tool Loop Iterations: Configure a strict upper bound (e.g., max 4 tool calls per request) so a confused LLM cannot trigger an infinite billing loop.
  • 3. Use Java 21 Virtual Threads: Enable `spring.threads.virtual.enabled=true` so slow 2-second LLM streaming calls never block Tomcat platform threads.

4. Complete Java 21 Code: Exposing `@Tool` Methods via Spring AI MCP Server

Prior to the Model Context Protocol (MCP), every team wrote custom JSON-Schema glue code for OpenAI function calling, separate adapters for Anthropic Claude tool use, and custom connectors for internal IDEs or agent orchestrators. Spring AI's `spring-ai-mcp-server-spring-boot-starter` eliminates all custom protocol plumbing—turning annotated Spring `@Service` methods into standards-compliant MCP tools over SSE/Streamable HTTP or STDIO:

Spring Boot 3 MCP Tool Server with Tenant RBAC & Audit Logging (Java 21)
public record OrderStatusResult(String orderId, String status, LocalDate estimatedDelivery, BigDecimal amountInr) {}

@Service
public class OrderMcpTools {
    private final OrderRepository orderRepo;

    public OrderMcpTools(OrderRepository orderRepo) { this.orderRepo = orderRepo; }

    @Tool(description = "Fetch real-time shipment & payment status for a customer order ID (e.g. ORD-9021).")
    public OrderStatusResult checkOrderStatus(
            @ToolParam(description = "Exact alphanumeric Order ID") String orderId) {
        String callerTenant = SecurityContextHolder.getContext().getAuthentication().getName();
        Order order = orderRepo.findByOrderIdAndTenantId(orderId, callerTenant)
            .orElseThrow(() -> new AccessDeniedException("Order not found for authenticated tenant"));
        return new OrderStatusResult(order.getOrderId(), order.getStatus().name(), order.getEta(), order.getTotalInr());
    }
}

// Register MCP ToolCallbackProvider Bean in @Configuration:
@Bean
public ToolCallbackProvider orderMcpToolProvider(OrderMcpTools tools) {
    return MethodToolCallbackProvider.builder().toolObjects(tools).build();
}

5. Read-Only vs Mutating MCP Tools: Enforcing Human-in-the-Loop (HITL) Approval

In enterprise architecture interviews, distinguish sharply between **Read-Only Discovery Tools** (`checkOrderStatus`, `searchRunbook`, `queryMetrics`) and **State-Mutating Write Tools** (`issueRefund`, `terminatePod`, `transferFunds`). Read-only tools can be invoked autonomously by `ChatClient` inside a bounded tool loop with Resilience4j timeouts (`@TimeLimiter` / `RestClient` read timeouts).

Mutating tools, however, must never execute irreversible side effects solely on probabilistic LLM output—especially when processing untrusted external emails or tickets susceptible to indirect prompt injection. Instead, have the `@Tool` method create a `PENDING_APPROVAL` proposal token in Redis/PostgreSQL and return a structured confirmation card to the React UI, executing the database commit only after an authenticated human clicks 'Approve' or deterministic policy rules (`refundAmount <= ₹2,000 && accountAgeDays > 90`) pass.

Why Spring AI + MCP Doubles Your Backend Market Value

Companies with existing Java/Spring Boot backends overwhelmingly prefer upskilling or hiring Java engineers who know Spring AI and MCP over maintaining a separate Python microservice fleet just to call LLM APIs.

Frequently Asked Questions

Do I need Python to learn MCP and Agentic AI at Uncorp?

We teach you both! In our Java Backend & Full Stack with Gen AI tracks, you build AI integrations and MCP servers in Java 21 & Spring AI. In our Live Gen AI Cohorts, you also master LangGraph and MCP across enterprise stacks.

Can Spring AI switch between OpenAI in cloud and Ollama locally?

Yes—because Spring AI uses portable interfaces (`ChatModel`, `EmbeddingModel`), switching from OpenAI GPT-4o to a local Llama 3 model running on Ollama requires only a configuration profile change in `application.yml`.

Written & Reviewed By Uncorp Engineering Faculty

Naitik Tailor & Uncorp Engineering Faculty

Founder & Principal Engineering Mentors (12+ Yrs Enterprise Experience) · VIT CSE '21 · Symbiosis MBA '24 · Ex-Delhivery & Ex-Aditya Birla Capital

About Uncorp

Continue Reading in This Topic Cluster

All 73 Guides