Spring › Spring-AI

Building Spring Boot MCP servers with STDIO and WebMVC

Expose Spring Boot business logic to AI agents using Spring AI 2.0.1 MCP servers over STDIO and Streamable HTTP with @McpTool and @McpResource.

Building Spring Boot MCP servers with STDIO and WebMVC

Exposing internal Spring Boot services—order workflows, admin boards, or ERP queries—to AI agents doesn’t require writing custom glue code for every client. With Spring AI 2.0.1, I can turn existing Spring beans into standard MCP servers over either STDIO (spring-ai-starter-mcp-server) for local tools or Streamable HTTP (spring-ai-starter-mcp-server-webmvc) for shared production services.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and Java 25.


Choosing between STDIO and Streamable HTTP

In my earlier post on building a Spring AI MCP client, Spring Boot consumed tools from external servers. Flipping the direction—making a Spring Boot app act as the MCP server—starts with picking the right transport layer for your deployment model.

flowchart TD
    subgraph StdioArch["STDIO Server (mcp-server-stdio)"]
        Client1["Claude Desktop / CLI Agent"]
        SubProcess["Child Process (java -jar app.jar)"]
        Client1 -->|"stdin / stdout pipe"| SubProcess
    end
    subgraph HttpArch["Streamable HTTP Server (mcp-server-webmvc)"]
        Client2["Cursor / Internal AI Portal / MCP Client"]
        TomcatServer["Spring Boot 4.1 Embedded Tomcat (Port 8092)"]
        Client2 -->|"HTTP POST/GET /mcp (Mcp-Session-Id)"| TomcatServer
    end
DimensionSTDIO (mcp-server-stdio)Streamable HTTP (mcp-server-webmvc)
TransportProcess standard I/O (stdin/stdout)Single HTTP endpoint (POST/GET /mcp)
Best fitLocal dev tools (Claude Desktop, local CLI)Production microservices, shared internal AI servers
Starterspring-ai-starter-mcp-serverspring-ai-starter-mcp-server-webmvc
Session lifecycleTied to the child process lifecycleMulti-session via Mcp-Session-Id header
Auth & networkInherits local OS user permissionsStandard Spring Security, TLS, API gateways

When not to use an MCP server: If your backend only serves a single frontend or fixed internal workflow with static inputs, a plain REST API is simpler to test, cache, and version. MCP pays off when multiple LLM clients (Cursor, Claude Desktop, Claude Code, or an internal agent hub) need to discover and invoke your domain capabilities dynamically using the standard MCP primitives.


Building the WebMVC Streamable HTTP server

For a shared microservice that multiple agents call over the network, I use the WebMVC starter. It runs on Spring Boot’s embedded Tomcat and speaks the current MCP Streamable HTTP transport instead of the older SSE-only split endpoints.

Dependencies in build.gradle.kts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-mcp-server-webmvc")
    implementation("tools.jackson.module:jackson-module-kotlin")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}

Configuring application.yaml

Setting protocol: streamable enables the unified /mcp endpoint. Spring AI handles JSON-RPC 2.0 framing, initialize negotiation, and Mcp-Session-Id session tracking automatically.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server:
  port: 8092

spring:
  application:
    name: mcp-server-webmvc
  ai:
    mcp:
      server:
        name: order-server
        version: 0.1.0
        type: sync
        protocol: streamable     # streamable (default) | sse | stateless
        streamable-http:
          mcp-endpoint: /mcp

Under the hood, spring-ai-starter-mcp-server-webmvc registers a RouterFunction bound to /mcp. On POST /mcp with "method": "initialize", the transport creates a session entry, returns a UUID in the Mcp-Session-Id response header, and negotiates protocol capabilities (tools, resources, prompts). Subsequent tools/list, tools/call, and resources/read calls carry that same header so the server correlates state per client session.

Exposing tools and resources with @McpTool and @McpResource

You don’t need to hand-write JSON Schemas or wire manual ToolCallbackProvider beans for basic endpoints. Annotating methods on any Spring @Component with @McpTool and @McpResource lets Spring AI’s annotation scanner register them at startup:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package io.github.cmsong111.mcp_server_webmvc.tools

import io.github.cmsong111.mcp_server_webmvc.domain.Order
import io.github.cmsong111.mcp_server_webmvc.repository.OrderRepository
import org.springframework.ai.mcp.annotation.McpResource
import org.springframework.ai.mcp.annotation.McpTool
import org.springframework.ai.mcp.annotation.McpToolParam
import org.springframework.stereotype.Component

@Component
class OrderTools(
    private val orderRepository: OrderRepository
) {

    // 1. Read-only order lookup tool (marked with readOnlyHint)
    @McpTool(
        name = "get_order_status",
        description = "Look up order details and current shipping status by order ID.",
        annotations = McpTool.McpAnnotations(readOnlyHint = true)
    )
    fun getOrderStatus(
        @McpToolParam(description = "Order ID to query (e.g., ORD-1002)", required = true) orderId: String
    ): Order {
        return orderRepository.findById(orderId)
            ?: throw IllegalArgumentException("No order found for ID '$orderId'.")
    }

    // 2. Order cancellation tool (marked with destructiveHint)
    @McpTool(
        name = "cancel_order",
        description = "Cancel an order. Orders that have already shipped cannot be canceled.",
        annotations = McpTool.McpAnnotations(destructiveHint = true)
    )
    fun cancelOrder(
        @McpToolParam(description = "Order ID to cancel", required = true) orderId: String,
        @McpToolParam(description = "Reason for cancellation", required = true) reason: String
    ): Order {
        return orderRepository.cancel(orderId, reason)
    }

    // 3. URI-template-based resource exposure
    @McpResource(
        uri = "order://{orderId}",
        name = "order-detail-resource",
        description = "Plain-text order summary addressed by order ID"
    )
    fun orderResource(orderId: String): String {
        val order = orderRepository.findById(orderId) ?: return "Order not found"
        return "Order ID: ${order.orderId}, Item: ${order.item}, Status: ${order.status}"
    }
}

Safety hints (readOnlyHint and destructiveHint): Clients like Claude Desktop and Cursor inspect tool annotations before execution. Marking cancel_order with destructiveHint = true signals the client to prompt for human-in-the-loop approval before mutating production state. Remember that hints are advisory—never rely on client UI prompts as your only authorization barrier.


Building and packaging the STDIO server

When an agent runs locally—such as Claude Desktop spawning a subprocess on your laptop—opening an HTTP port is unnecessary overhead. The spring-ai-starter-mcp-server starter binds JSON-RPC directly to System.in and System.out.

Implementing the tool bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
class ArticleService(
    private val articleRepository: ArticleRepository
) {

    @Tool(description = "Create a new article.")
    fun createArticle(form: ArticleCreateForm): Article {
        return articleRepository.save(Article.create(form.title, form.content, form.author))
    }

    @Tool(description = "Return a list of all articles.")
    fun listArticles(): List<Article> = articleRepository.findAll()

    @Tool(description = "Delete an article by ID.")
    fun deleteArticle(id: Long): Boolean = articleRepository.deleteById(id)
}

Packaging the JAR and wiring Claude Desktop

A STDIO server uses stdout exclusively for JSON-RPC frames. Any stray Spring Boot banner or INFO log written to stdout will corrupt the JSON stream and cause the client to drop the connection immediately. Disable the Spring banner (spring.main.banner-mode=off) and route all logs to stderr or a rolling log file.

Build the executable JAR with ./gradlew :mcp-server-stdio:bootJar, then register it in claude_desktop_config.json:

1
2
3
4
5
6
7
8
9
10
11
{
  "mcpServers": {
    "article-server": {
      "command": "/usr/bin/java",
      "args": [
        "-jar",
        "/path/to/spring-ai-examples/mcp-server-stdio/build/libs/mcp-server-stdio-0.1.0.jar"
      ]
    }
  }
}

Verifying both transports

Running unit and protocol tests

I run the test suites for both modules together to verify tool registration, schema generation, and JSON-RPC serialization:

1
./gradlew :mcp-server-stdio:test :mcp-server-webmvc:test

Console output showing passing tests for MCP server STDIO and WebMVC modules Figure 1. Passing protocol and unit tests for both mcp-server-stdio and mcp-server-webmvc.

Testing the Streamable HTTP handshake with curl

You don’t need an LLM client to verify the HTTP transport. Sending a raw initialize request confirms the server responds with HTTP 200 and issues a Mcp-Session-Id header. Note that the Accept header must include both application/json and text/event-stream as required by the Streamable HTTP spec:

1
2
3
4
5
6
7
8
9
10
11
12
curl -i -X POST http://localhost:8092/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-06-18",
      "clientInfo": {"name": "curl-agent", "version": "1.0"}
    }
  }'

Console output of JSON-RPC initialize handshake returning Mcp-Session-Id header Figure 2. initialize handshake returning HTTP 200 OK along with the generated Mcp-Session-Id session header.

Invoking tools/call with the session header

Pass the returned Mcp-Session-Id back to execute get_order_status directly:

1
2
3
4
5
6
7
8
9
10
11
12
curl -s -X POST http://localhost:8092/mcp \
  -H "Content-Type: application/json" \
  -H "Mcp-Session-Id: 9f72b380-41da-4589-9a21-99521ef32091" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_order_status",
      "arguments": {"orderId": "ORD-1002"}
    }
  }' | jq .

Console output of JSON-RPC tools/call returning OrderTools result Figure 3. JSON-RPC response wrapping the serialized OrderTools result as MCP text content.


Connecting external AI clients

Once /mcp responds cleanly to curl, wiring it into desktop or CLI clients takes a few lines:

  • Cursor (~/.cursor/mcp.json):
    1
    2
    3
    4
    5
    
    {
      "mcpServers": {
        "order-server": { "url": "http://localhost:8092/mcp" }
      }
    }
    
  • Claude Code:
    1
    
    claude mcp add --transport http order-server http://localhost:8092/mcp
    

Production caveats and checklist

Watch out for stateful sessions behind a load balancer: protocol: streamable stores active Mcp-Session-Id state in JVM memory by default. If you scale mcp-server-webmvc across multiple replicas behind a load balancer without sticky sessions, a client’s tools/call can hit a different pod and fail with an unknown session error. Use sticky routing on Mcp-Session-Id or switch to protocol: stateless if your tools don’t need server-initiated notifications.

Before shipping a Spring Boot MCP server to production, verify these four items:

  • STDOUT isolation (STDIO): Banner is disabled and Logback writes strictly to stderr or a file—never stdout.
  • Safety annotations + real auth: Destructive mutations carry destructiveHint = true, and HTTP endpoints enforce server-side authentication and RBAC via Spring Security.
  • Clear parameter descriptions: Every @McpToolParam includes concrete format examples (like ORD-1002) so models don’t guess argument shapes.
  • Session topology: Multi-instance deployments either route Mcp-Session-Id stickily or run in stateless mode.
This post is licensed under CC BY 4.0 by the author.