0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SpringのMCPサーバでバリデーションチェックを実装する

0
Posted at

概要

MCPは生成AIが引数を決めるため、不正な値を除外するためにも、バリデーションチェックが必須である。
Springの機能を使って実装する。

バリデーションチェックの記述方法

今回も、Dynamic Tool Update Exampleのサンプルに修正を加える。動かし方について以下の記事を参照。

pom.xml

依存関係の設定。spring-boot-starter-validationを入れるため、以下の行を挿入する。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

WeatherService.java

今回必要なアノテーションは@Validated@Minなので、以下をimportする。

import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;

@Validatedをclassの前に追加する。

@Service
@Validated
public class WeatherService {

引数に@Minを追加する。今回は0よりも小さい値は不正とする。

	@Tool(description = "Get the temperature (in celsius) for a specific location") // @formatter:off
	public WeatherResponse weatherForecast( 
		@ToolParam(description = "The location latitude") @Min(value = 0) double latitude,
		@ToolParam(description = "The location longitude") double longitude,
		ToolContext toolContext) { // @formatter:on

実行結果

0より小さい値を入れてツールを呼ぶとエラーとメッセージが返ってくるようになる。
image.png

(おまけ) パラメータ制約の記述の実装状況

minimumなどのJSON Schemaの制約記述は2026/05/10時点では実装されていない。
このことは、以下のissuesで報告されている。

対応するPRがマージされれば、制約を記述できるようになるかもしれない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?