Spring › Spring-AI

Building a Spring AI STDIO MCP server in Kotlin

Configure a Spring AI Model Context Protocol (MCP) server over STDIO in Kotlin, expose CRUD methods with @Tool, and test it as a local JAR.

Building a Spring AI STDIO MCP server in Kotlin

For a newer guide covering both STDIO and Streamable HTTP transports, see Building a Spring Boot MCP server with STDIO and Streamable HTTP.

I built a small Spring AI Model Context Protocol (MCP) server over STDIO to expose article CRUD operations as callable LLM tools. This post walks through the Kotlin tool registration, STDIO configuration, JAR packaging, and verification from an MCP client.

Why expose Spring services over STDIO MCP

When an LLM host like Claude Desktop or an IDE agent needs to query or mutate local data, you can either build a REST API with custom glue code or expose your methods through MCP. Spring AI’s MCP server starter lets you annotate existing Spring service methods with @Tool and serve them over standard input/output (STDIO) with almost no boilerplate.

STDIO works well for local developer tools because the MCP host spawns your Spring Boot fat JAR as a child process and exchanges JSON-RPC 2.0 frames over stdin and stdout. There’s no port conflict, no TLS setup, and no exposed network socket to secure.

TransportBest fitProcess modelTrade-off
STDIOLocal CLI/IDE agents, personal toolsHost spawns JAR per clientAny stray stdout log breaks JSON-RPC framing
Streamable HTTPShared team services, multi-tenant APIsLong-running web serverRequires auth, CORS, and network deployment
Custom REST wrapperLegacy systems without MCP clientsSeparate HTTP client + promptDuplicates schema definitions manually

When not to use STDIO: Skip STDIO if multiple users need to share one server instance, if the server must run inside a remote Kubernetes cluster, or if JVM cold-start latency (1–3 seconds per spawned process) hurts your workflow. In those cases, run a persistent HTTP MCP server instead.

Prerequisites and project setup

To follow along, you need:

  • A Spring Boot project with JDK and Gradle configured
  • Spring AI MCP server dependencies on the classpath (providing ToolCallbackProvider, MethodToolCallbackProvider, and @Tool)
  • A local MCP-compatible host (such as Claude Desktop or an IDE client) that can launch a STDIO server from a JSON config file

Under the hood, Spring AI scans any ToolCallbackProvider bean at startup, inspects methods annotated with @Tool, generates JSON Schema definitions for their parameters via Jackson, and registers them in the MCP tools/list response. When the model decides to call a tool, the MCP server deserializes the JSON arguments, invokes your Spring bean method, and serializes the return value back over stdout.

Exposing tools with ToolCallbackProvider and @Tool

The setup takes three pieces: a @Configuration class that registers ToolCallbackProvider, a service class whose methods carry @Tool, and Jackson-annotated request DTOs.

Registering ToolCallbackProvider in Kotlin

Wrap your service bean with MethodToolCallbackProvider so Spring AI’s MCP auto-configuration picks up its annotated methods:

1
2
3
4
5
6
7
8
9
@Configuration
class MCPConfig(
  private val articleService: ArticleService
) {
  @Bean
  fun myTools(): ToolCallbackProvider {
    return MethodToolCallbackProvider.builder().toolObjects(articleService).build()
  }
}

Defining @Tool methods in ArticleService

Each @Tool annotation takes a description that the LLM reads when deciding which tool to invoke. Keep descriptions concrete—state what the method returns on missing records or success:

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
import org.springframework.ai.tool.annotation.Tool
import org.springframework.stereotype.Component

@Component
class ArticleService(
  private val articleRepository: ArticleRepository
) {

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

  @Tool(description = "Fetches an article by ID. Returns null if it does not exist.")
  fun getArticle(id: Long): Article? {
    return articleRepository.findById(id).orElse(null)
  }

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

  @Tool(description = "Updates an existing article's title and content by ID.")
  fun updateArticle(form: ArticleUpdateForm): Article {
    val article = articleRepository.findById(form.id)
      .orElseThrow { IllegalArgumentException("Article with id=${form.id} not found") }

    article.update(
      title = form.title,
      content = form.content,
    )

    return articleRepository.save(article)
  }

  @Tool(description = "Deletes an article by ID. Returns true on success.")
  fun deleteArticle(id: Long): Boolean {
    if (!articleRepository.existsById(id)) return false
    articleRepository.deleteById(id)
    return true
  }
}

Request DTOs and Kotlin default values

When I first tested Kotlin data class parameters, MCP JSON deserialization failed unless every property had a default value like val title: String = "". That happens when Jackson attempts to instantiate the DTO via a no-arg constructor (for example, if the Kotlin Jackson module isn’t registered on the internal ObjectMapper used by the MCP tool callback). Adding default values generates a no-arg constructor in Kotlin bytecode and avoids the error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyDescription

@JsonIgnoreProperties(ignoreUnknown = true)
data class ArticleCreateForm(

  @field:JsonProperty("title", required = true)
  @field:JsonPropertyDescription("Title of the new article (e.g., 'Getting Started with Spring AI').")
  val title: String = "",

  @field:JsonProperty("content", required = true)
  @field:JsonPropertyDescription("Body content of the article. Markdown is supported.")
  val content: String = "",

  @field:JsonProperty("author", required = true)
  @field:JsonPropertyDescription("Author name or handle (e.g., 'Gemini').")
  val author: String = "",
)

Using @field:JsonPropertyDescription also enriches the generated JSON Schema, which helps the LLM pass well-formatted arguments on the first try.

Configuring STDIO transport and building the JAR

Because STDIO uses stdout exclusively for JSON-RPC messages, you must disable the embedded web server and turn off the Spring Boot startup banner. If Spring prints its ASCII banner or console logs to stdout, the MCP host fails to parse the stream as JSON and drops the connection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
spring:
  application:
    name: article-server

  main:
    web-application-type: none
    banner-mode: off

  ai:
    mcp:
      server:
        name: article-server
        version: 0.0.1-SNAPSHOT
        stdio: true

Redirect any application logging to a file or stderr (logging.pattern.console= cleared or routed via Logback). Even a single println() call will corrupt the STDIO JSON-RPC protocol.

Package the executable JAR with Gradle:

1
./gradlew bootJar

Then register the JAR in your MCP client configuration file (for example, mcp-config.json):

1
2
3
4
5
6
7
8
9
10
11
12
{
  "mcpServers": {
    "article-server": {
      "type": "stdio",
      "command": "java",
      "args": [
        "-jar",
        "./spring-mcp-example-0.0.1-SNAPSHOT.jar"
      ]
    }
  }
}

With this config in place, the MCP host spawns the JAR as a child process and communicates over standard input and output.

Verifying tool calls from an MCP client

Once connected, the client queries tools/list and displays all five @Tool methods exposed by ArticleService.

Available MCP tools listed in the client Figure 1. MCP client listing the five article CRUD tools registered from ArticleService.

Next, I asked the assistant to create a new article and update its content. The client routed both requests to createArticle and updateArticle:

Creating and updating an article via MCP Figure 2. Invoking createArticle and updateArticle through natural language prompts.

Then I tested reading the stored record and deleting it:

Querying and deleting an article via MCP Figure 3. Fetching the updated article with getArticle and triggering deleteArticle.

Finally, listing articles again confirmed the record was removed:

Confirming article deletion via MCP Figure 4. Confirming deletion by calling listArticles after deleteArticle.

Production caveats and references

Before turning a local STDIO prototype into a daily tool, run through this quick checklist:

  • Keep stdout clean: Set spring.main.banner-mode: off and disable console logging, or redirect logs to stderr/files so JSON-RPC frames stay valid.
  • Provide default values on Kotlin DTOs: Give every @Tool input field a default value (or verify jackson-module-kotlin is active on the MCP ObjectMapper) to prevent deserialization errors.
  • Guard destructive tools: deleteArticle executes immediately once approved; add confirmation prompts or soft-delete logic if the database holds real data.
  • Use absolute JAR paths in client configs: Relative paths like ./spring-mcp-example-0.0.1-SNAPSHOT.jar break when the host launches from a different working directory.

Official docs and the full sample repository:

The Model Context Protocol (MCP) is a standardized protocol that enables AI models to interact with external tools and resources in a structured way. Think of it as a bridge between your AI models and the real world - allowing them to access databases, APIs, file systems, and other external services through a consistent interface. It supports multiple transport mechanisms to provide flexibility across different environments.
Spring AI 다양한 실전 예제 모음 (Text Generation, SSE Streaming, MCP Server) - cmsong111/spring-ai-examples
This post is licensed under CC BY 4.0 by the author.