1. MCP Server Starters & Transport Architecture
| 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 byMcpSyncServer. Scans and registers imperative Java methods using standard blocking return types. -
Asynchronous Mode (
spring.ai.mcp.server.type=ASYNC): Backed byMcpAsyncServerand Project Reactor. Registers non-blocking methods returningMonoorFluxstreams. -
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
@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@McpToolParamdescriptions to generate the input JSON Schema returned intools/listresponses. -
@McpResource: Exposes read-only enterprise data via parameterized URI templates (such aslogs://{serviceName}/{date}orconfig://{key}). Spring AI extracts path variables automatically and passes them into the Java method when a client invokesresources/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.
MethodToolCallbackProvider.)3. Advanced Server Context & Special Parameters
@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 asAuthorizationbearer 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 orstderr. -
Secure HTTP Endpoints with Spring Security: Spring AI relies on standard Spring Security for authentication. Protect
/mcpendpoints 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, andinstructionsinapplication.ymlso connected AI agents understand the server’s domain scope immediately during theinitializehandshake. -
Handle Exceptions Cleanly: When a
@McpToolthrows 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:
- Generate the project using Spring Initializr
- Create the project structure (entity, repository, service, controller)
- Configure MySQL and the MCP server in
application.properties - Create the entities and repositories
- Create the service with
@Toolmethods - Register the tools with a
ToolCallbackProvider - Create the REST controller
- 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 runUniversityMcpApplicationfrom 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/summaryhttp://localhost:8080/api/university/studentshttp://localhost:8080/api/university/students?department=Computer Sciencehttp://localhost:8080/api/university/students/1http://localhost:8080/api/university/students/1/enrollmentshttp://localhost:8080/api/university/courses
Use in Postman (POST, Body > raw > JSON):
Add a student: POST /api/university/students
{ "name": "Priya Reddy", "email": "priya.reddy@university.edu",
"department": "Electronics", "yearOfStudy": 2 }
Add a course: POST /api/university/courses
{ "code": "EC101", "title": "Basic Electronics", "department": "Electronics", "credits": 3 }
Enroll a student: POST /api/university/enrollments
{ "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.
{ "jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": { "protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": { "name": "postman", "version": "1.0.0" } } }
{ "jsonrpc": "2.0", "method": "notifications/initialized" }
{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }
{ "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.
