Spring Boot MCP サーバーの構築方法 (2026年版)
Spring Boot を使用した Java での Model Context Protocol サーバーの作成
Hyperealで構築を始めよう
Kling、Flux、Sora、Veoなどに単一のAPIでアクセス。無料クレジットで開始、数百万規模まで拡張可能。
クレジットカード不要 • 10万人以上の開発者 • エンタープライズ対応
Spring Boot MCP サーバーの構築方法 (2026年版)
Model Context Protocol (MCP) は、Anthropic によって作成されたオープン標準であり、Claude のような AI アシスタントが外部のツールやデータソースと対話することを可能にします。ほとんどの MCP サーバーの例は TypeScript や Python を使用していますが、Java 開発者は公式の MCP Java SDK を使用して、Spring Boot で MCP サーバーを構築できます。このガイドでは、完全に機能する MCP サーバーをゼロから構築する手順を説明します。
MCP とは?
MCP (Model Context Protocol) は、AI アシスタントが以下のことを行うための標準的な方法を定義しています:
- ツールの呼び出し (Call tools) -- データベースの照会、API の呼び出し、計算の実行などの関数を実行します。
- リソースの読み取り (Read resources) -- ファイル、データベースレコード、API レスポンスなどのデータにアクセスします。
- プロンプトの使用 (Use prompts) -- 事前に作成されたプロンプトテンプレートを取得します。
これは AI 用のプラグインシステムだと考えてください。Claude があなたの MCP サーバーに接続すると、利用可能なツールを検出し、会話の中でそれらを呼び出すことができます。
MCP アーキテクチャ
┌─────────────┐ MCP Protocol ┌──────────────┐
│ Claude │ ◄──────────────────► │ MCP Server │
│ Desktop │ (JSON-RPC over │ (Spring Boot)│
│ または IDE │ stdio または SSE) │ │
└─────────────┘ └──────┬───────┘
│
┌──────┴───────┐
│ あなたのツール │
│ - データベース │
│ - API │
│ - ファイル │
└──────────────┘
前提条件
- Java 17 以降
- Maven または Gradle
- Spring Boot 3.2+
- Claude Desktop または MCP 互換クライアント
Java のバージョンを確認してください:
java --version
# java 17.x.x 以上が出力されること
mvn --version
# Apache Maven 3.9.x 以上であること
ステップ 1: Spring Boot プロジェクトの作成
Spring Initializr を使用するか、手動でプロジェクトを作成します。
Spring Initializr を使用する場合
curl https://start.spring.io/starter.zip \
-d type=maven-project \
-d language=java \
-d bootVersion=3.4.2 \
-d baseDir=mcp-server \
-d groupId=com.example \
-d artifactId=mcp-server \
-d name=mcp-server \
-d packageName=com.example.mcpserver \
-d javaVersion=17 \
-d dependencies=web \
-o mcp-server.zip
unzip mcp-server.zip
cd mcp-server
MCP 依存関係の追加
pom.xml に MCP Java SDK を追加します:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MCP Java SDK -->
<dependency>
<groupId>io.modelcontextprotocol</groupId>
<artifactId>mcp-spring-boot-starter</artifactId>
<version>0.6.0</version>
</dependency>
<!-- JSON Processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
ステップ 2: MCP サーバーの設定
src/main/resources/application.yml にアプリケーションの設定を作成します:
server:
port: 8080
mcp:
server:
name: "my-spring-mcp-server"
version: "1.0.0"
transport: sse # CLIベースのクライアントの場合は "stdio" を使用
ステップ 3: ツールの定義
MCP ツールは、Claude が呼び出すことができる関数です。各ツールには名前、説明、入力スキーマ、およびハンドラーがあります。
ツール設定クラスの作成
package com.example.mcpserver.tools;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
@Configuration
public class ToolConfiguration {
private final ObjectMapper objectMapper = new ObjectMapper();
@Bean
public McpServer.ToolRegistration weatherTool() {
// 入力スキーマの定義
String inputSchema = """
{
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "天気を取得する都市名"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度単位",
"default": "celsius"
}
},
"required": ["city"]
}
""";
Tool tool = new Tool(
"get_weather",
"指定された都市の現在の天気を取得します",
objectMapper.readTree(inputSchema)
);
return new McpServer.ToolRegistration(tool, (arguments) -> {
String city = (String) arguments.get("city");
String units = (String) arguments.getOrDefault("units", "celsius");
// 実際のアプリでは、ここで天気 API を呼び出します
String weather = fetchWeather(city, units);
return new CallToolResult(
List.of(new TextContent(weather)),
false // isError
);
});
}
@Bean
public McpServer.ToolRegistration calculatorTool() {
String inputSchema = """
{
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["add", "subtract", "multiply", "divide"],
"description": "実行する計算操作"
},
"a": {
"type": "number",
"description": "第1演算子"
},
"b": {
"type": "number",
"description": "第2演算子"
}
},
"required": ["operation", "a", "b"]
}
""";
Tool tool = new Tool(
"calculate",
"基本的な数学計算を実行します",
objectMapper.readTree(inputSchema)
);
return new McpServer.ToolRegistration(tool, (arguments) -> {
String operation = (String) arguments.get("operation");
double a = ((Number) arguments.get("a")).doubleValue();
double b = ((Number) arguments.get("b")).doubleValue();
double result = switch (operation) {
case "add" -> a + b;
case "subtract" -> a - b;
case "multiply" -> a * b;
case "divide" -> {
if (b == 0) throw new ArithmeticException("ゼロ除算エラー");
yield a / b;
}
default -> throw new IllegalArgumentException(
"不明な操作: " + operation
);
};
return new CallToolResult(
List.of(new TextContent(String.valueOf(result))),
false
);
});
}
private String fetchWeather(String city, String units) {
// プレースホルダー - 実際の API 呼び出しに置き換えてください
return String.format(
"%sの天気: 22%s、時々曇り、湿度 65%%",
city,
units.equals("celsius") ? "°C" : "°F"
);
}
}
ステップ 4: リソースプロバイダーの追加
リソースにより、Claude はサーバーからデータを読み取ることができます:
package com.example.mcpserver.resources;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.spec.McpSchema.Resource;
import io.modelcontextprotocol.spec.McpSchema.ResourceContents;
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class ResourceConfiguration {
@Bean
public McpServer.ResourceRegistration configResource() {
Resource resource = new Resource(
"config://app/settings",
"アプリケーション設定",
"現在のアプリケーション構成と設定",
"application/json"
);
return new McpServer.ResourceRegistration(resource, (uri) -> {
String configJson = """
{
"app_name": "My MCP Server",
"version": "1.0.0",
"features": ["weather", "calculator"],
"max_requests_per_minute": 60
}
""";
return new ResourceContents(
List.of(new TextResourceContents(uri, "application/json", configJson))
);
});
}
}
ステップ 5: データベースツールの追加 (実践例)
より現実的な例として、データベースにクエリを実行するツールを紹介します:
@Bean
public McpServer.ToolRegistration databaseQueryTool(JdbcTemplate jdbcTemplate) {
String inputSchema = """
{
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "実行する SQL SELECT クエリ (読み取り専用)"
},
"limit": {
"type": "integer",
"description": "返される最大行数",
"default": 10
}
},
"required": ["query"]
}
""";
Tool tool = new Tool(
"query_database",
"アプリケーションデータベースに対して読み取り専用の SQL クエリを実行します",
objectMapper.readTree(inputSchema)
);
return new McpServer.ToolRegistration(tool, (arguments) -> {
String query = (String) arguments.get("query");
int limit = ((Number) arguments.getOrDefault("limit", 10)).intValue();
// セキュリティ:SELECT ステートメントのみを許可
if (!query.trim().toUpperCase().startsWith("SELECT")) {
return new CallToolResult(
List.of(new TextContent("エラー: SELECT クエリのみが許可されています")),
true // isError
);
}
// LIMIT が存在しない場合は追加
if (!query.toUpperCase().contains("LIMIT")) {
query += " LIMIT " + limit;
}
List<Map<String, Object>> results = jdbcTemplate.queryForList(query);
String json = objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(results);
return new CallToolResult(
List.of(new TextContent(json)),
false
);
});
}
ステップ 6: 実行とテスト
ビルドと実行
mvn clean package
java -jar target/mcp-server-0.0.1-SNAPSHOT.jar
サーバーはポート 8080 で起動し、/sse に SSE エンドポイントが作成されます。
cURL によるテスト
# サーバーが動作しているか確認
curl http://localhost:8080/sse
# 利用可能なツールをリストアップ (MCP プロトコル経由)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}'
ステップ 7: Claude Desktop への接続
Claude Desktop の設定ファイルに MCP サーバーを追加します。
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
SSE トランスポートの場合
{
"mcpServers": {
"spring-mcp": {
"url": "http://localhost:8080/sse"
}
}
}
stdio トランスポートの場合
stdio トランスポートでサーバーを構築した場合は、jar の実行をラップします:
{
"mcpServers": {
"spring-mcp": {
"command": "java",
"args": [
"-jar",
"/path/to/mcp-server-0.0.1-SNAPSHOT.jar"
]
}
}
}
設定を更新した後、Claude Desktop を再起動してください。Claude のツールリストにあなたのツールが表示されるはずです。
トラブルシューティング
| 問題 | 原因 | 解決策 |
|---|---|---|
| Claude でサーバーが見つからない | 設定ファイルの構文エラー | JSON を検証し、Claude Desktop を再起動する |
| "Connection refused" | サーバーが起動していない | 最初に Spring Boot アプリを起動する |
| ツールが表示されない | @Bean アノテーションの不足 |
ツール Bean が @Configuration クラス内にあることを確認する |
| SSE 接続が切れる | タイムアウト設定 | server.servlet.session.timeout を設定する |
| JSON パースエラー | スキーマの不一致 | 入力スキーマを MCP 仕様に照らして検証する |
プロジェクト構造
mcp-server/
├── pom.xml
├── src/
│ └── main/
│ ├── java/com/example/mcpserver/
│ │ ├── McpServerApplication.java
│ │ ├── tools/
│ │ │ └── ToolConfiguration.java
│ │ └── resources/
│ │ └── ResourceConfiguration.java
│ └── resources/
│ └── application.yml
結論
Spring Boot で MCP サーバーを構築することで、Java 開発者は既存のサービス、データベース、API を Claude のような AI アシスタントに公開できます。MCP Java SDK は Spring Boot の依存関係注入および設定システムと自然に統合されるため、ツールやリソースの登録を簡単に行うことができます。
製品ビデオの作成、説明文からの画像生成、話すアバターインターフェースの構築など、MCP 対応の AI ワークフローを視覚的コンテンツ生成で拡張したいチームにとって、Hypereal AI はビデオ、画像、アバター生成のための統合 API を提供しており、これらを簡単に追加の MCP ツールとしてラップすることができます。
