Build Your First MCP Server with Spring Boot 4.1 and Spring AI 2.0 AI for developers and Programmers java MCP Spring AI by devs5003 - July 1, 2026July 1, 20260 Build Your First MCP Server with Spring Boot and Spring AI 2.0 Your Spring Boot services already hold years of business logic. The Model Context Protocol (MCP) is the protocol that lets AI models like Claude, GPT-4, or GitHub Copilot reach into those services and use them as callable tools. This tutorial shows you exactly how to build an MCP server using Spring Boot 4.1 and the brand-new Spring AI 2.0 GA (released June 2026). No prior AI experience needed. If you know Spring Boot, you are already most of the way there. (Java 21 + Spring Boot 4.1 + Spring AI 2.0) Spring AI 2.0.0 went GA on June 12, 2026, a major release that introduces the @McpTool/@McpResource annotation API, deprecates SSE transport in favour of Streamable-HTTP, and requires Spring Boot 4.1 + Spring Framework 7. Official documentation fetched directly from Spring AI reference doc and the Spring AI 2.0 GA release announcement to ensure all code, dependency names, and configuration properties are current and accurate. Table of Contents Toggle What You Will LearnPrerequisitesWhy This MattersUnderstanding the MCP ArchitectureSetting Up Your Spring Boot ProjectCreating Your First MCP Tool with @McpToolExposing a Resource with @McpResourceConfiguring Streamable-HTTP TransportRun and Test the ServerHow to Connect to Claude Desktop (Optional)Common Mistakes to AvoidFAQs (Interview Questions on This Topic)ConclusionWhat to Learn NextRelated What You Will Learn What MCP is and how it fits into an AI workflow How to add Spring AI 2.0 MCP support to a Spring Boot 4.1 project How to create MCP Tools using @McpTool How to expose read-only data using @McpResource How to configure Streamable-HTTP transport; the recommended protocol in Spring AI 2.0 How to test your MCP server locally using curl and the MCP Inspector Prerequisites Java 17 or later (Java 21 recommended) Familiarity with Spring Boot basics (dependency injection, @Component, REST controllers) Maven or Gradle curl or Postman for testing No AI platform API key is needed to build and test the server side. Why This Matters AI assistants are only as useful as the context they can access. A model that cannot reach your database, call your internal APIs, or query your business logic will always give generic answers. The moment you give it access to real data, its answers become precise and actionable. MCP solves this with a standardized protocol. You build a server once, and any MCP-compatible client Claude Desktop, VS Code Copilot, Cursor, or your own Spring Boot app can connect and discover your tools automatically. For Java teams, this is significant. There are millions of Spring Boot services already running in production. Wrapping them in an MCP layer lets AI agents act on real enterprise data without rewriting anything. Interview relevance: Interviewers at AI-forward companies increasingly ask about MCP, function calling, and tool-based AI architectures. Knowing how to build an MCP server in Java places you clearly ahead of most candidates who know AI only from the consumer side. Understanding the MCP Architecture Before touching code, understand the three roles: MCP Host: The AI application (e.g., Claude Desktop, a Spring Boot chat service) MCP Client: A connector that the host creates to talk to one MCP server (1:1 mapping) MCP Server: Your Spring Boot application, exposing tools, resources, and prompts through the protocol Think of it this way: you are building a power socket. The AI is whatever device plugs into it. Three capability types your server can expose: Tools: Callable functions. The AI does something: search products, fetch a record, trigger a workflow. The AI invokes these and gets a result back. Resources: Read-only data. The AI reads these and includes the content in its context window. Think configuration files, documentation snippets, or live summaries. Prompts: Reusable prompt templates for structured or repeated interactions. This tutorial focuses on Tools and Resources, which you will use in the vast majority of real-world scenarios. Setting Up Your Spring Boot Project Go to start.spring.io and generate a project with: Spring Boot: 4.1.0 Java: 21 Build tool: Maven Dependencies: Spring Web After downloading and extracting the project, open pom.xml and add the Spring AI BOM and MCP server starter: org.springframework.boot spring-boot-starter-parent 4.1.0 org.springframework.ai spring-ai-bom 2.0.0 pom import org.springframework.boot spring-boot-starter-web org.springframework.ai spring-ai-starter-mcp-server-webmvc Use spring-ai-starter-mcp-server-webflux instead if your project is reactive (WebFlux). Use spring-ai-starter-mcp-server (no suffix) if you need STDIO transport for CLI clients. Creating Your First MCP Tool with @McpTool Spring AI 2.0 introduced @McpTool, an annotation that marks a regular Spring bean method as an MCP tool. The framework generates the JSON schema from your method signature automatically. No manual schema authoring, no boilerplate callbacks. Here is a practical example: a product catalog server that lets an AI search for products and retrieve product details. First, create a simple domain model using a Java 21 record: // Product.java public record Product(String id, String name, String category, double price) {} Next, create the MCP tool component: // ProductCatalogTools.java import org.springframework.ai.mcp.annotation.McpTool; import org.springframework.ai.mcp.annotation.McpToolParam; import org.springframework.stereotype.Component; import java.util.List; @Component public class ProductCatalogTools { // In a real application, inject your repository or service here private static final List PRODUCTS = List.of( new Product("P001", "Wireless Headphones", "Electronics", 79.99), new Product("P002", "Mechanical Keyboard", "Electronics", 129.99), new Product("P003", "Ergonomic Chair", "Furniture", 349.00), new Product("P004", "Standing Desk", "Furniture", 499.00), new Product("P005", "Notebook Pack", "Stationery", 12.99) ); @McpTool( name = "search_products", description = "Search the product catalog by name or category. Returns a list of matching products." ) public List searchProducts( @McpToolParam(description = "Keyword to search in product name or category", required = true) String keyword) { String lower = keyword.toLowerCase(); return PRODUCTS.stream() .filter(p -> p.name().toLowerCase().contains(lower) || p.category().toLowerCase().contains(lower)) .toList(); } @McpTool( name = "get_product_by_id", description = "Retrieve the full details of a single product using its unique ID." ) public Product getProductById( @McpToolParam(description = "The unique product ID, for example P001", required = true) String productId) { return PRODUCTS.stream() .filter(p -> p.id().equalsIgnoreCase(productId)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Product not found: " + productId)); } } What Spring AI is doing here: At startup, it scans for Spring beans containing @McpTool methods, reads your method parameter types and @McpToolParam descriptions, builds a valid MCP JSON schema for each tool, and registers them with the server automatically. There is no XML, no manual callback registration, and no extra wiring in your @SpringBootApplication class. Exposing a Resource with @McpResource Resources are read-only content the AI can pull into its context. They are passive; the AI reads them and uses that information when generating a response, rather than calling them as actions. Here is how to expose a product catalog summary as an MCP resource: // CatalogResources.java import org.springframework.ai.mcp.annotation.McpResource; import org.springframework.stereotype.Component; @Component public class CatalogResources { @McpResource( uri = "catalog://summary", name = "Product Catalog Summary", description = "A summary of available product categories and total inventory counts." ) public String getCatalogSummary() { return """ Product Catalog — Version 1.0 Categories: - Electronics : 2 products ($79.99 – $129.99) - Furniture : 2 products ($349.00 – $499.00) - Stationery : 1 product ($12.99) Total: 5 products Last updated: 2026-06-01 """; } } An MCP client can now read this resource before prompting the AI. For example: “Given this catalog summary, which category has the widest price range?” answered entirely from your Spring Boot service. Configuring Streamable-HTTP Transport This is where many developers hit problems. The transport you configure on the server must match what your MCP client expects. In Spring AI 2.0, Streamable-HTTP is the recommended transport for web-based MCP servers. SSE (Server-Sent Events) is now deprecated and will be removed in a future release. Add this to src/main/resources/application.yml: spring: application: name: product-catalog-mcp-server ai: mcp: server: name: product-catalog-server version: 1.0.0 protocol: STREAMABLE # Recommended. Replaces deprecated SSE. type: SYNC # Use ASYNC for Project Reactor / non-blocking tools annotation-scanner: enabled: true # Picks up @McpTool and @McpResource beans automatically Your main application class needs no changes, standard @SpringBootApplication is all you need: // ProductCatalogMcpServerApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProductCatalogMcpServerApplication { public static void main(String[] args) { SpringApplication.run(ProductCatalogMcpServerApplication.class, args); } } At startup, Spring Boot's auto-configuration will: Scan all beans for @McpTool and @McpResource annotated methods Generate JSON schemas from method parameters Register every capability with the MCP server Start a JSON-RPC HTTP endpoint at http://localhost:8080/mcp Run and Test the Server Start the application: bash ./mvnw spring-boot:run You will see output similar to: Started ProductCatalogMcpServerApplication in 2.4 seconds (process running for 2.7) List available tools with curl: bash curl -X POST http://localhost:8080/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' The response lists search_products and get_product_by_id with their auto-generated input schemas. Call a tool directly: bash curl -X POST http://localhost:8080/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "search_products", "arguments": { "keyword": "electronics" } } }' You should receive a JSON array of the two electronics products. For a better experience, use the MCP Inspector a browser-based UI that connects to your server, lists all tools and resources, and lets you call them interactively without writing curl commands. How to Connect to Claude Desktop (Optional) To connect this server to Claude Desktop, add the following to your Claude configuration file (claude_desktop_config.json): { "mcpServers": { "product-catalog": { "url": "http://localhost:8080/mcp" } } } Restart Claude Desktop. It will auto-discover your tools and Claude can now answer questions like “Find all furniture products under $400” by calling your Spring Boot service directly. Note: For STDIO-based CLI clients like Claude Code CLI, switch to spring.ai.mcp.server.stdio=true in your yml and use the spring-ai-starter-mcp-server dependency (without the webmvc suffix). STDIO runs your server as a subprocess rather than an HTTP service. Common Mistakes to Avoid 1. Transport mismatch (the number one gotcha) Web-based clients (Claude Desktop, VS Code Copilot, browser IDEs) expect HTTP transport. CLI tools like Claude Code CLI expect STDIO. Mixing these causes silent handshake failures with no helpful error in the logs. Always check which transport your target client uses before picking your starter dependency and yml property. 2. Using the deprecated SSE protocol In Spring AI 2.0, protocol: SSE still works but is deprecated. Set protocol: STREAMABLE instead. Streamable-HTTP replaces SSE as the current MCP specification standard. SSE will be removed in a future Spring AI release. 3. SYNC server ignoring ASYNC annotated methods When type: SYNC, Spring AI only registers methods that return non-reactive types. If your method returns Mono<> or Flux<>, it will be silently ignored. Match your server type to your method signatures. 4. Leaking exception details in tool responses When your @McpTool method throws a runtime exception, Spring AI returns the exception message verbatim to the MCP client. This can expose internal stack traces or sensitive information to untrusted callers. Define a McpExceptionHandler bean to control what error detail goes back before exposing your server beyond localhost. 5. Wrong Spring Boot and Spring AI version combination Spring AI 2.0 requires Spring Boot 4.1 (Spring Framework 7). If your project is still on Spring Boot 3.x, use Spring AI 1.1.x instead. The @McpTool annotation exists in 1.1+ as well, but with slightly different package paths and without all the 2.0 transport options. FAQs (Interview Questions on This Topic) Q#1: What is the Model Context Protocol and why was it created? MCP is an open protocol introduced by Anthropic that standardizes how AI models connect to external tools, data sources, and services. It was designed to solve the integration problem: before MCP, every AI tool needed a custom adapter for every backend system. With MCP, you build the server once and any compatible client connects. Q#2: What is the difference between an MCP Tool and an MCP Resource? Tools are callable: the AI invokes them to perform an action and receive a result. Resources are read-only: the AI reads the content and includes it in its context window before generating a response. Tools use @McpTool; resources use @McpResource. Tools change or query state; resources describe state. Q#3: What transport protocols does Spring AI 2.0 support for MCP? STDIO for in-process or CLI-based clients; Streamable-HTTP (recommended) for web-based servers; Stateless for serverless or cloud-native microservice deployments. SSE is still available but deprecated as of Spring AI 2.0 and scheduled for removal. Q#4: How does Spring AI generate the JSON schema for MCP tools automatically? At startup, it reads the parameter types and @McpToolParam annotations on @McpTool methods and builds a JSON schema that the MCP protocol requires. Java records, standard POJOs, and primitives all work cleanly. Complex nested polymorphic types such as a method returning List where Animal is an interface may produce a vague schema and often need explicit configuration. Q#5: What is the difference between SYNC and ASYNC MCP server types in Spring AI? A SYNC server uses McpSyncServer with blocking threads, the right choice for standard REST-based backends. An ASYNC server uses McpAsyncServer with Project Reactor, suitable for non-blocking reactive workloads. The two modes do not mix: the server only registers methods that match its type and silently ignores the others. Configure type: SYNC or type: ASYNC explicitly in your yml. Conclusion You have built a fully functional MCP Server in Spring Boot using Spring AI 2.0. Your server exposes tools the AI can call and resources it can read all through a standardized protocol that works with Claude, Copilot, Cursor, and any application built on the MCP specification. The path was clean: project setup → annotate your tools → configure transport → test with JSON-RPC. That is the complete MCP server lifecycle. What to Learn Next MCP Client in Spring Boot: build a Spring Boot application that connects to an MCP server and uses an LLM to call its tools via ChatClient and ToolCallingAdvisor Spring AI ChatClient with Tool Calling: orchestrate full AI workflows where the model decides which of your tools to call and when Securing Your MCP Server: add Spring Security + OAuth2/JWT to protect your /mcp endpoint before exposing it beyond localhost Stateless MCP for Kubernetes: explore protocol: STATELESS for horizontally-scalable, session-free MCP deployments in cloud-native environments. References: Spring AI Reference Documentation Spring AI MCP Documentation Model Context Protocol (MCP) You may also like: AI Agents in Spring Boot: Building Autonomous Workflows with Spring AI 12 Essential AI Terms Java Developer Must Know in 2026 Top 10 AI Tools for Java Developers and Programmers in 2026 Best AI tools for Java Developers by Development Phase Free AI Framework for Java Developers in 2026: Think Like a Technology PRO (Try It Now) Related