2
2

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サーバで引数の制約の記述をする

2
Posted at

概要

MCPでは、不正な値を生成AIに教えるためにも、tools/listのレスポンスのJson Schemaで工夫をしたい。
Springでアノテーションによる制約の記述はまだ実装されていないが、ツール登録時に変更を加えることで、制約を記述することができる

tools/listのレスポンスについて

ツール登録時のinputSchema Map<String, Object>の構造がそのまま反映される。
そのため、inputSchemaにminimumを追加すると
image.png
tools/listのレスポンスにminimumが表示される
image.png

引数制約の記述方法

今回は、上記記事(SpringのMCPサーバのツールの説明文を外部ファイルで上書きする)の内容に変更を加えて、multiplyNumbersというツールのnumber1という引数にminimum = 0の制約を記述する。

ServerApplication.java

SpringのMCPサーバのツールの説明文を外部ファイルで上書きする部分の解説は省略する。
以下のコードでは、
multiplyNumbersのツールを特定し、inputSchemapropertiesnumber1を特定し、minimumを0として追加。
その追加されたinputSchemaでツール登録を行っている。

List<SyncToolSpecification> newTools = McpToolUtils
					.toSyncToolSpecifications(ToolCallbacks.from(new MathTools()));

			for (SyncToolSpecification newTool : newTools) {

				if (newTool.tool().name().equals("multiplyNumbers")) {
					McpSchema.Tool tool = newTool.tool();

					var input = tool.inputSchema();
					var properties = (Map<String, Object>) input.get("properties");
					var number1 = (Map<String, Object>) properties.get("number1");

					if (number1 != null) {
						number1.put("minimum", 0);
					}

					newTool = new SyncToolSpecification(
							new McpSchema.Tool(tool.name(), tool.title(), getDescrition(), input,
									tool.outputSchema(), tool.annotations(), tool.meta()),
							newTool.callHandler());
				}

				logger.info("Add new tool: " + newTool);
				mcpSyncServer.addTool(newTool);
			}

			logger.info("Tools updated: ");

実行結果

tools/listのレスポンスにminimumが表示された
image.png

不正な値を入力時の挙動

number1に不正な値(0より小さい値)を入れて実行すると、バリデーションチェックも行われた。
image.png

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?