JSON Schema生成工具

从Jackson注解的Java类生成MCP服务器的JSON Schema,适用于Java 17和Jackson 3。

  • by sualeh
  • Java
  • 本地部署
  • 更新于
在 GitHub 查看 sualeh/mcp-json-schema

使用说明

MCP JSON模式

从Jackson注释的Java类为MCP服务器生成JSON模式。使用Java 17和Jackson 3。

此库针对模型上下文协议(MCP)JSON模式,它是通用JSON模式规范的一个子集。有关MCP JSON模式子集和基元类型的详细信息,请参阅MCP 基本模式定义.

用法

1) 定义参数类型

创建一个Jackson注释的记录/POJO,表示工具的输入参数。使用 @JsonProperty(required=true, defaultValue=...) 和 @JsonPropertyDescription 以丰富模式。

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import tools.jackson.databind.PropertyNamingStrategies;
import tools.jackson.databind.annotation.JsonNaming;

@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class)
public record SampleParameters(
    @JsonPropertyDescription("Type of database table dependant objects.")
    @JsonProperty(defaultValue = "NONE", required = true)
    DependantObjectType dependantObjectType,

    @JsonPropertyDescription("Table name.")
    String tableName) {

  public enum DependantObjectType { NONE, COLUMNS, INDEXES, FOREIGN_KEYS, TRIGGERS }
}

2) 在注册时生成MCP input_schema

注册MCP工具时,请使用 McpJsonSchemaUtility.inputSchema(...) 生成 input_schema 参数类型为JSON。

import us.fatehi.mcp_json_schema.McpJsonSchemaUtility;

String inputSchemaJson = McpJsonSchemaUtility.inputSchema(SampleParameters.class);

// Provide this value as the tool's input_schema in your MCP server implementation
System.out.println(inputSchemaJson);

您还可以通过Jackson获取模式 JsonNode 如果您更喜欢以编程方式嵌入或修改它:

var schemaNode = McpJsonSchemaUtility.generateJsonSchema(SampleParameters.class);

3) 在执行时实例化参数

当客户端调用该工具时,您将收到 arguments JSON字符串。使用将其转换为参数类型 instantiateArguments(...).

String arguments = "{\n  \"dependant-object-type\": \"COLUMNS\",\n  \"table-name\": \"customers\"\n}";

SampleParameters params = McpJsonSchemaUtility.instantiateArguments(arguments, SampleParameters.class);
if (params == null) {
  // handle error: bad arguments; return a suitable MCP error to the client
} else {
  // execute tool logic using params
}

备注

  • 生成的模式遵循MCP JSON模式子集(请参阅上面的规范链接)。它包括:
    • type: "object", properties,以及 required (从 @JsonProperty(required = true)).
    • description (从 @JsonPropertyDescription).
    • enum 枚举值(包括适用的数组项)。
    • additionalProperties: false.
  • 命名策略,例如 @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) 影响模式和反序列化中的属性名称。
  • instantiateArguments 使用共享 ObjectMapper 使用默认配置。在反序列化失败时,它将返回 null 并登录INFO。确保验证和处理 null 适当。

另见

  • us.fatehi.mcp_json_schema.McpJsonSchemaUtility API的Javadoc详细信息和使用指南。