Building MCP Servers with Spring AI – Exposing Java Services as Tools

In Spring AI, building a Model Context Protocol (MCP) Server turns standard Spring Boot applications and Java services into standardized, AI-discoverable capability providers. Rather than writing custom JSON-RPC framing, manual schema generators, or bespoke HTTP/STDIO handlers, developers rely on Spring AI’s MCP Server Boot Starters and declarative annotations to expose business services to any MCP-compatible host (such as Spring AI clients, Claude Desktop, Claude Code, or AI IDEs).

1. MCP Server Starters & Transport Architecture

Spring AI provides dedicated Boot starters tailored to your deployment model and transport protocol:

Starter Module Transport Protocol Execution & Deployment Model
spring-ai-starter-mcp-server STDIO (Standard Input/Output) Launches the Spring Boot JAR as a local subprocess communicating over console pipes; ideal for local CLI tools and desktop AI assistants.
spring-ai-starter-mcp-server-webmvc Streamable HTTP (and legacy SSE) Runs on embedded Servlet containers (Tomcat/Jetty), auto-wiring the POST /mcp JSON-RPC endpoint without custom controller boilerplate.
spring-ai-starter-mcp-server-webflux Streamable HTTP (and legacy SSE) Runs on reactive Netty servers (McpAsyncServer), delivering non-blocking backpressure and reactive Mono/Flux tool execution.

Server Execution Modes (SYNC vs. ASYNC)

  • Synchronous Mode (spring.ai.mcp.server.type=SYNC): Default mode backed by McpSyncServer. Scans and registers imperative Java methods using standard blocking return types.

  • Asynchronous Mode (spring.ai.mcp.server.type=ASYNC): Backed by McpAsyncServer and Project Reactor. Registers non-blocking methods returning Mono or Flux streams.

  • Stateless Streamable HTTP (protocol: STATELESS): Eliminates server-side session state, allowing remote MCP servers to scale horizontally behind load balancers or serverless platforms (such as Cloud Run) without sticky sessions.

2. Exposing Java Services via Declarative Annotations

Spring AI’s auto-configuration annotation scanner automatically detects MCP annotations on Spring @Service or @Component beans at startup, generates parameter JSON Schemas, and registers them with the MCP runtime:

  • @McpTool & @McpToolParam: Marks a Java method as an executable MCP tool. Spring AI inspects method parameters, Java records/POJOs, and @McpToolParam descriptions to generate the input JSON Schema returned in tools/list responses.

  • @McpResource: Exposes read-only enterprise data via parameterized URI templates (such as logs://{serviceName}/{date} or config://{key}). Spring AI extracts path variables automatically and passes them into the Java method when a client invokes resources/read.

  • @McpPrompt & @McpArg: Exposes reusable, parameterized prompt workflows (prompts/get) so client applications fetch standardized domain prompts directly from the server.

  • @McpComplete: Provides intelligent auto-completion suggestions for prompt arguments or resource URI variables.

(Note: For legacy or programmatic registration without annotations, Spring AI also supports wrapping existing service beans via MethodToolCallbackProvider.)

3. Advanced Server Context & Special Parameters

Spring AI automatically injects special framework objects into @McpTool methods while excluding them from the LLM-visible JSON Schema:
  • McpSyncRequestContext / McpAsyncRequestContext: Gives Java services bidirectional access to the active MCP client session:

    • Progress Notifications (progress()): Emits real-time progress percentages and status messages back to the client during long-running backend jobs.

    • Structured Logging (info(), debug(), error()): Streams server-side diagnostic logs directly to the connected MCP host.

    • Client Sampling & Elicitation (sampling(), elicitation()): Allows the MCP server to request an LLM completion or user confirmation mid-execution via the host.

    • Transport Context (transportContext()): Exposes HTTP headers (such as Authorization bearer tokens or tenant headers) inside tool execution for authentication and multi-tenant scoping.

  • McpMeta & @McpProgressToken: Provide direct access to request metadata and correlation tokens.

4. Architectural Patterns & Testing

  • Two Deployment Patterns: Teams either embed MCP starters directly as a thin protocol layer inside existing domain microservices, or build a dedicated MCP Gateway / Adapter Service that aggregates downstream REST APIs and databases into a unified enterprise tool surface.

  • Interactive Testing with MCP Inspector: Remote Streamable HTTP servers can be inspected and tested interactively in the browser using the official MCP Inspector (npx @modelcontextprotocol/inspector http://localhost:8080/mcp) without writing custom client code.

5. Production Best Practices

  • Disable Console Banner & Logs in STDIO Mode: When running a local STDIO MCP server, any stray text printed to stdout (including the Spring Boot startup banner or console appenders) corrupts JSON-RPC framing; always disable the banner and redirect logs strictly to files or stderr.

  • Secure HTTP Endpoints with Spring Security: Spring AI relies on standard Spring Security for authentication. Protect /mcp endpoints with OAuth 2.0 / OIDC JWT validation or API keys, and enforce method-level authorization inside your Java services.

  • Set Meaningful Server Metadata & Instructions: Configure spring.ai.mcp.server.name, version, and instructions in application.yml so connected AI agents understand the server’s domain scope immediately during the initialize handshake.

  • Handle Exceptions Cleanly: When a @McpTool throws an exception, Spring AI wraps it into a structured MCP error payload; return clear, actionable business error messages rather than raw stack traces so the calling LLM can recover gracefully.

Hands-on Experiment: Building a University Management MCP Server

Aim: To build a Spring Boot MCP server that exposes university services (students, courses, enrollments) as tools that AI clients can discover and call.

Description: The application manages students, courses and enrollments in MySQL. Its service methods are published as eight MCP tools: add and find students, add and list courses, enroll a student, view a student’s enrollments and get a university summary. The same methods are also available as normal REST endpoints. An AI client connects to http://localhost:8080/mcp, lists the tools and calls them.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ IDEA / Eclipse / VS Code), Postman (and Node.js for MCP Inspector, optional)

Steps:
  1. Generate the project using Spring Initializr
  2. Create the project structure (entity, repository, service, controller)
  3. Configure MySQL and the MCP server in application.properties
  4. Create the entities and repositories
  5. Create the service with @Tool methods
  6. Register the tools with a ToolCallbackProvider
  7. Create the REST controller
  8. Run the application and test the MCP server

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven, Language: Java, Spring Boot: 3.5.x (Spring AI 1.1 needs Boot 3.4 or higher, so 3.3.x cannot be used here)
  • Group: com.example, Artifact: university-mcp-server
  • Packaging: Jar, Java: 17
  • Dependencies: MCP Server (Spring Web MVC), Spring Data JPA, MySQL Driver

Step 2: Project Structure

university-mcp-server
├── pom.xml
├── README.md
└── src/main
    ├── java/com/example/universitymcp
    │   ├── UniversityMcpApplication.java
    │   ├── entity
    │   │   ├── Student.java
    │   │   ├── Course.java
    │   │   └── Enrollment.java
    │   ├── repository
    │   │   ├── StudentRepository.java
    │   │   ├── CourseRepository.java
    │   │   └── EnrollmentRepository.java
    │   ├── service
    │   │   └── UniversityService.java
    │   └── controller
    │       └── UniversityController.java
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

Run the application

  • Start MySQL, then run mvn spring-boot:run (or run UniversityMcpApplication from the IDE).
  • REST APIs: http://localhost:8080/api/university/...
  • MCP server: http://localhost:8080/mcp

URLs and Request Payloads

Open in the browser (GET):

  • http://localhost:8080/api/university/summary
  • http://localhost:8080/api/university/students
  • http://localhost:8080/api/university/students?department=Computer Science
  • http://localhost:8080/api/university/students/1
  • http://localhost:8080/api/university/students/1/enrollments
  • http://localhost:8080/api/university/courses

Use in Postman (POST, Body > raw > JSON):

Add a student: POST /api/university/students

json
{ "name": "Priya Reddy", "email": "priya.reddy@university.edu",
  "department": "Electronics", "yearOfStudy": 2 }

Add a course: POST /api/university/courses

json
{ "code": "EC101", "title": "Basic Electronics", "department": "Electronics", "credits": 3 }

Enroll a student: POST /api/university/enrollments

json
{ "studentId": 1, "courseCode": "ME101" }

Test the MCP server:

Option 1 (recommended): run npx @modelcontextprotocol/inspector, choose Transport Streamable HTTP, enter http://localhost:8080/mcp, click Connect, then Tools > List Tools and run a tool.

Option 2 (Postman): POST http://localhost:8080/mcp with headers Content-Type: application/json and Accept: application/json, text/event-stream. After initialize, copy the Mcp-Session-Id response header and send it with every following request.

json
{ "jsonrpc": "2.0", "id": 1, "method": "initialize",
  "params": { "protocolVersion": "2025-06-18", "capabilities": {},
              "clientInfo": { "name": "postman", "version": "1.0.0" } } }
 
json
{ "jsonrpc": "2.0", "method": "notifications/initialized" }
 
json
{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }
 
json
{ "jsonrpc": "2.0", "id": 3, "method": "tools/call",
  "params": { "name": "enroll_student", "arguments": { "studentId": 2, "courseCode": "CS101" } } }

The complete project is in university-mcp-server.zip, with the MySQL setup and a README listing every URL and payload. It uses only the four packages entity, repository, service and controller.

Scroll to Top