commit 6f4ac0b9ee3f9e81af33cd4c46a9e73f685af5f1 Author: wangbing Date: Mon Aug 4 18:01:38 2025 +0800 上传备份 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3a502c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +Thumbs.db +.DS_Store +target/ +out/ +.micronaut/ +.idea +*.iml +*.ipr +*.iws +.project +.settings +.classpath +.factorypath +.m2/ +maven-wrapper.jar +maven-wrapper.properties diff --git a/README.md b/README.md new file mode 100644 index 0000000..402eaba --- /dev/null +++ b/README.md @@ -0,0 +1,82 @@ +# A simple MCP Server implemented with Micronaut + +This project implements a simple MCP ([Model Context Protocol](https://modelcontextprotocol.io/introduction)) server, +with an HTTP SSE transport, using [Micronaut](https://micronaut.io/). + +A test class uses [LangChain4j's MCP client](https://docs.langchain4j.dev/tutorials/mcp) support to call and interact with the Micronaut MCP server. + +## What it does + +The server provides dummy weather information ☀️ for a given city. + +The MCP server implements a subset of the MCP protocol to handle requests for weather data. + +In particular, it implements the following operations: +* `initialize` +* `notifications/initialize` +* `tools/list` +* `tools/call` + +All the MCP protocol classes can be found in the `xyz.wbsite.mcp.basic.model` package. + +There are two main controllers working together to implement the server-side of the MCP communication over HTTP/SSE: + +### The `SseController` (serving `/mcp/sse`): + +This controller acts as the entry point for the Server-Sent Events (SSE) connection. +When an MCP client wants to connect, it first makes an HTTP GET request to this endpoint (`/mcp/sse`). + +How it works: +* It's annotated with `@Controller("/mcp/sse")`. +* It has a single method `connectSse()` annotated with `@Get(produces = MediaType.TEXT_EVENT_STREAM)`. This tells Micronaut that GET requests to `/mcp/sse` should be handled by this method and that the response will be an SSE stream. +* It injects the `SseBroadcaster` singleton bean. +* The `connectSse()` method simply calls `broadcaster.getEventsPublisher()` and returns the result. + +What it does: +* It establishes the persistent SSE connection with the client. +* It delegates the responsibility of actually sending events over this connection to the SseBroadcaster. The broadcaster ensures the first event sent tells the client where to send POST requests (the endpoint event), and then sends subsequent responses or notifications. + +### The `PostController` (`/mcp/post`): + +This controller handles the incoming MCP command requests sent by the client after the SSE connection is established. The client learns the path for this controller (`/mcp/post`) from the initial endpoint event received via the SseController. + +How it works: + +* It's annotated with `@Controller("/mcp/post")`. +* It has a method `handleMcpPostRequest(@Body McpRequest request)` annotated with `@Post(consumes = MediaType.APPLICATION_JSON)`. This means it handles HTTP POST requests to `/mcp/post` where the body contains JSON data conforming to the `McpRequest` structure. +* It also injects the `SseBroadcaster`. + +Inside `handleMcpPostRequest`: +* It deserializes the JSON request body into an `McpRequest` object. +* It calls a private helper method `processRequest(request)` to determine the appropriate action based on the `request.method()` (e.g., `initialize`, `tools/list`, `tools/call`). +* `processRequest` generates an `McpResponse` object containing the result (or an error, or `null` for notifications). +* If `processRequest` returns a response object, `handleMcpPostRequest` calls `broadcaster.broadcastResponse(mcpResponse)`. This sends the actual MCP result back to the client over the previously established SSE connection. +* Finally, it returns an immediate `HttpResponse.ok()` to the original POST request. This HTTP response simply acknowledges that the server received the POST request; it does not contain the actual MCP result. + +What it does: +* It receives specific commands from the MCP client (like "list available tools" or "execute the weather tool"). It processes these commands, generates the corresponding MCP response, and uses the `SseBroadcaster` to send that response back asynchronously over the SSE channel managed initially by the `SseController`. + +### The `SseBroadcaster` + +The `SseBroadcaster` manages the SSE stream, sends the initial configuration (endpoint event), and provides a way for other parts of the server (like the `PostController`) to send JSON-formatted responses and notifications back to the connected client over that stream. + +## The `McpWeatherClientTest` client + +The `McpWeatherClientTest` class is an integration test that verifies the functionality of the MCP server. + +You can run the test class with `./gradlew test`. + +What it does: +* It starts a local server (via Micronaut). +* It sets up a LangChain4j AI assistant (`WeatherAssistant`) configured to use Google Cloud Vertex AI's Gemini 2.0 Flash mode. +* It configures this assistant to find and use tools provided by the local server via a specific protocol (MCP over HTTP/SSE). +* It tests if the client can discover the tools correctly. +* It tests if the assistant correctly uses the remote weather tool when asked about weather. +* It tests if the assistant correctly avoids using the weather tool for unrelated questions like simple greeting prompts. + +--- + +>[!NOTE] +> This project is not an official Google project. + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..9519243 --- /dev/null +++ b/pom.xml @@ -0,0 +1,80 @@ + + + 4.0.0 + + xyz.wbsite + starter-mcp-server + 0.1 + pom + + starter-mcp-server + Spring Boot MCP Server Demo + + starter-mcp-server-app + starter-mcp-server-basic + + + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + + + 17 + 17 + 17 + UTF-8 + + + + + + central + Central Repository + default + https://maven.aliyun.com/repository/public + + + + + + central + Central Repository + https://maven.aliyun.com/repository/public + default + + + + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + cn.hutool + hutool-all + 5.8.24 + + + + + + + + + io.modelcontextprotocol.sdk + mcp-spring-webflux + 0.8.1 + + + \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/basic/BasicApplication.java b/src/main/java/xyz/wbsite/mcp/basic/BasicApplication.java new file mode 100644 index 0000000..d802129 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/BasicApplication.java @@ -0,0 +1,18 @@ +package xyz.wbsite.mcp.basic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * MCP基础原理示例入口 + * 该方式适合理解mcp原理,开发较繁琐,需要自己解析工具,不适合生产环境下使用,请参考@link{McpServerApplication} + * + * @author wangbing + */ +@SpringBootApplication +public class BasicApplication { + + public static void main(String[] args) { + SpringApplication.run(BasicApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/basic/CallToolResult.java b/src/main/java/xyz/wbsite/mcp/basic/CallToolResult.java new file mode 100644 index 0000000..b866aee --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/CallToolResult.java @@ -0,0 +1,50 @@ +package xyz.wbsite.mcp.basic; + +import java.util.List; + +/** + * 调用工具的结果类 + * 用于封装工具调用后的返回数据和错误状态 + * + * @author wangbing + */ +public class CallToolResult extends Data { + + /** + * 工具调用返回的内容数据列表 + */ + private List content; + + /** + * 工具调用是否出错 + */ + private Boolean isError; + + public CallToolResult() { + } + + public CallToolResult(List content, Boolean isError) { + this.content = content; + this.isError = isError; + } + + public CallToolResult(List content) { + this(content, false); + } + + public List getContent() { + return content; + } + + public void setContent(List content) { + this.content = content; + } + + public Boolean getIsError() { + return isError; + } + + public void setIsError(Boolean isError) { + this.isError = isError; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/Data.java b/src/main/java/xyz/wbsite/mcp/basic/Data.java new file mode 100644 index 0000000..7905ff8 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/Data.java @@ -0,0 +1,18 @@ +package xyz.wbsite.mcp.basic; + +import java.io.Serial; +import java.io.Serializable; + +/** + * 可序列化基类. + * + * @author wangbing + * @version 0.0.1 + * @since 1.8 + */ +public class Data implements Serializable { + + @Serial + private static final long serialVersionUID = -1L; + +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/InitializeResult.java b/src/main/java/xyz/wbsite/mcp/basic/InitializeResult.java new file mode 100644 index 0000000..7fd2e99 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/InitializeResult.java @@ -0,0 +1,30 @@ +package xyz.wbsite.mcp.basic; + +/** + * 初始化结果类 + * 用于封装服务器初始化后的能力信息 + * + * @author wangbing + */ +public class InitializeResult extends Data { + + /** + * 服务器能力信息 + */ + private ServerCapabilities capabilities; + + public InitializeResult() { + } + + public InitializeResult(ServerCapabilities capabilities) { + this.capabilities = capabilities; + } + + public ServerCapabilities getCapabilities() { + return capabilities; + } + + public void setCapabilities(ServerCapabilities capabilities) { + this.capabilities = capabilities; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/InputSchema.java b/src/main/java/xyz/wbsite/mcp/basic/InputSchema.java new file mode 100644 index 0000000..de24605 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/InputSchema.java @@ -0,0 +1,75 @@ +package xyz.wbsite.mcp.basic; + +import java.util.List; +import java.util.Map; + +/** + * 输入模式类 + * 用于定义工具输入参数的结构和验证规则 + * + * @author wangbing + */ +public class InputSchema extends Data { + + /** + * 输入模式的类型 + */ + private String type; + + /** + * 输入模式的属性定义 + */ + private Map properties; + + /** + * 输入模式的必填字段列表 + */ + private List required; + + /** + * 输入模式是否允许额外属性 + */ + private Boolean additionalProperties; + + public InputSchema() { + } + + public InputSchema(String type, Map properties, List required, Boolean additionalProperties) { + this.type = type; + this.properties = properties; + this.required = required; + this.additionalProperties = additionalProperties; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public List getRequired() { + return required; + } + + public void setRequired(List required) { + this.required = required; + } + + public Boolean getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Boolean additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/ListToolsResult.java b/src/main/java/xyz/wbsite/mcp/basic/ListToolsResult.java new file mode 100644 index 0000000..5bf4f07 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/ListToolsResult.java @@ -0,0 +1,32 @@ +package xyz.wbsite.mcp.basic; + +import java.util.List; + +/** + * 工具列表结果类 + * 用于封装可用工具的列表信息 + * + * @author wangbing + */ +public class ListToolsResult extends Data { + + /** + * 工具列表 + */ + private List tools; + + public ListToolsResult() { + } + + public ListToolsResult(List tools) { + this.tools = tools; + } + + public List getTools() { + return tools; + } + + public void setTools(List tools) { + this.tools = tools; + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/basic/McpError.java b/src/main/java/xyz/wbsite/mcp/basic/McpError.java new file mode 100644 index 0000000..7fd63a4 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/McpError.java @@ -0,0 +1,36 @@ +package xyz.wbsite.mcp.basic; + +/** + * 错误信息类 + * 用于封装错误代码和错误消息 + * + * @author wangbing + */ +public class McpError extends Data { + private int code; + private String message; + + public McpError() { + } + + public McpError(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/basic/McpRequest.java b/src/main/java/xyz/wbsite/mcp/basic/McpRequest.java new file mode 100644 index 0000000..ce1d850 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/McpRequest.java @@ -0,0 +1,58 @@ +package xyz.wbsite.mcp.basic; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * MCP协议请求类 + * 用于封装JSON-RPC格式的请求数据 + * + * @author wangbing + */ +public class McpRequest extends Data { + private String jsonrpc; + private Long id; + private String method; + private JsonNode params; // Use JsonNode for flexible params + + public McpRequest() { + } + + public McpRequest(String jsonrpc, Long id, String method, JsonNode params) { + this.jsonrpc = jsonrpc; + this.id = id; + this.method = method; + this.params = params; + } + + public String getJsonrpc() { + return jsonrpc; + } + + public void setJsonrpc(String jsonrpc) { + this.jsonrpc = jsonrpc; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public JsonNode getParams() { + return params; + } + + public void setParams(JsonNode params) { + this.params = params; + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/basic/McpResponse.java b/src/main/java/xyz/wbsite/mcp/basic/McpResponse.java new file mode 100644 index 0000000..229a342 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/McpResponse.java @@ -0,0 +1,65 @@ +package xyz.wbsite.mcp.basic; + +/** + * MCP协议响应类 + * 用于封装JSON-RPC格式的响应数据 + * 支持成功结果和错误信息的返回 + * + * @author wangbing + */ +public class McpResponse extends Data { + private String jsonrpc; + private Long id; + private Object result; // Can be ListToolsResult, CallToolResult, etc. + private McpError error; // Optional error field + + public McpResponse() { + } + + public McpResponse(String jsonrpc, Long id, Object result, McpError error) { + this.jsonrpc = jsonrpc; + this.id = id; + this.result = result; + this.error = error; + } + + public McpResponse(Long id, Object result) { + this("2.0", id, result, null); + } + + public McpResponse(Long id, McpError error) { + this("2.0", id, null, error); + } + + public String getJsonrpc() { + return jsonrpc; + } + + public void setJsonrpc(String jsonrpc) { + this.jsonrpc = jsonrpc; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + } + + public McpError getError() { + return error; + } + + public void setError(McpError error) { + this.error = error; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/PostController.java b/src/main/java/xyz/wbsite/mcp/basic/PostController.java new file mode 100644 index 0000000..3e76159 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/PostController.java @@ -0,0 +1,113 @@ +package xyz.wbsite.mcp.basic; + +import jakarta.annotation.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * 后控制器类 + * 用于处理MCP POST请求 + * + * @author wangbing + */ +@RestController +@RequestMapping("/mcp/post") +public class PostController { + + private static final Logger log = LoggerFactory.getLogger(PostController.class); + private static final String WEATHER_TOOL_NAME = "getWeatherForecast"; + private static final String FAKE_WEATHER_JSON = "{\"forecast\": \"sunny\"}"; + + @Resource + SseBroadcaster broadcaster; + + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity handleMcpPostRequest(@RequestBody McpRequest request) { + log.info("Received MCP POST Request: ID={}, Method={}", request.getId(), request.getMethod()); + + McpResponse mcpResponse = processRequest(request); + + if (mcpResponse != null) { + // Send the response back over the SSE channel + broadcaster.broadcastResponse(mcpResponse); + } else { + // 处理可能不会生成McpResponse对象的通知等情况 + // 在我们的例子中,'通知/初始化'落在这里。 + log.debug("No explicit response object generated for method '{}', assuming notification ack.", request.getMethod()); + } + // 立即返回HTTP 200 OK或202 Accepted以确认收到POST。 + // 实际结果通过SSE异步发送。 + // 200 OK可能更简单,因为客户希望得到一些响应体,即使是空的。 + // 202 Accepted明确表示处理正在其他地方进行。让我们用200。 + return ResponseEntity.ok().build(); + } + + private McpResponse processRequest(McpRequest request) { + switch (request.getMethod()) { + case "initialize": + log.info("Handling initialize request"); + InitializeResult initResult = new InitializeResult(new ServerCapabilities()); + return new McpResponse(request.getId(), initResult); + + case "notifications/initialized": + log.info("Received initialized notification"); + // 这是来自客户端的通知。MCP规范称通知 + // 没有回应。所以我们在这里返回null,POST处理程序 + // 将只返回HTTP OK。 + return null; + + case "tools/list": + log.info("Handling tools/list request"); + ToolSpecificationData weatherTool = new ToolSpecificationData( + WEATHER_TOOL_NAME, + "Gets the current weather forecast.", + new InputSchema( + "object", + Map.of("location", Map.of( + "type", "string", + "description", "Location to get the weather for") + ), + List.of("location"), + false) + ); + ListToolsResult listResult = new ListToolsResult(List.of(weatherTool)); + return new McpResponse(request.getId(), listResult); + + case "tools/call": + log.info("Handling tools/call request"); + if (request.getParams() != null && request.getParams().has("name")) { + String toolName = request.getParams().get("name").asText(); + if (WEATHER_TOOL_NAME.equals(toolName)) { + log.info("Executing tool: {}", toolName); + TextContentData textContent = new TextContentData(FAKE_WEATHER_JSON); + CallToolResult callResult = new CallToolResult(List.of(textContent)); + return new McpResponse(request.getId(), callResult); + } else { + log.warn("Unknown tool requested: {}", toolName); + return new McpResponse(request.getId(), new McpError(-32601, "Method not found: " + toolName)); + } + } else { + log.error("Invalid tools/call request: Missing 'name' in params"); + return new McpResponse(request.getId(), new McpError(-32602, "Invalid params for tools/call")); + } + + case "ping": + log.info("Handling ping request"); + return new McpResponse(request.getId(), Collections.emptyMap()); + + default: + log.warn("Unsupported MCP method: {}", request.getMethod()); + return new McpResponse(request.getId(), new McpError(-32601, "Method not found: " + request.getMethod())); + } + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/ServerCapabilities.java b/src/main/java/xyz/wbsite/mcp/basic/ServerCapabilities.java new file mode 100644 index 0000000..de5cf59 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/ServerCapabilities.java @@ -0,0 +1,15 @@ +package xyz.wbsite.mcp.basic; + +import java.io.Serial; + +/** + * 服务器能力类 + * 用于封装服务器支持的功能和特性 + * + * @author wangbing + */ +public class ServerCapabilities extends Data { + + @Serial + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/SseBroadcaster.java b/src/main/java/xyz/wbsite/mcp/basic/SseBroadcaster.java new file mode 100644 index 0000000..d5b2c99 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/SseBroadcaster.java @@ -0,0 +1,139 @@ +package xyz.wbsite.mcp.basic; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * SSE广播器类 + * 用于管理和广播SSE事件给所有已连接的客户端 + * + * @author wangbing + */ +@Service // Manages the SSE emitters +public class SseBroadcaster { + + private static final Logger log = LoggerFactory.getLogger(SseBroadcaster.class); + + private final List emitters = new CopyOnWriteArrayList<>(); + private final ObjectMapper objectMapper; + + public SseBroadcaster(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * 注册新的SSE发射器 + * + * @param emitter sse发射器 + */ + public void registerEmitter(SseEmitter emitter) { + // Add the emitter to the list + emitters.add(emitter); + log.info("New SSE emitter registered, total emitters: {}", emitters.size()); + + // Set up completion handlers to remove the emitter when the connection is closed + emitter.onCompletion(() -> { + emitters.remove(emitter); + log.info("SSE emitter completed, remaining emitters: {}", emitters.size()); + }); + + emitter.onTimeout(() -> { + emitters.remove(emitter); + log.info("SSE emitter timed out, remaining emitters: {}", emitters.size()); + }); + + emitter.onError((e) -> { + emitters.remove(emitter); + log.error("Error on SSE emitter: {}", e.getMessage(), e); + }); + } + + /** + * 将初始端点事件发送到特定发射器 + * + * @param emitter sse发射器 + */ + public void sendEndpointEvent(SseEmitter emitter) { + try { + emitter.send(SseEmitter.event() + .name("endpoint") + .data("/mcp/post")); + log.info("Sent endpoint event to SSE emitter"); + } catch (IOException e) { + log.error("Failed to send endpoint event: {}", e.getMessage(), e); + emitter.completeWithError(e); + } + } + + /** + * 由POST端点处理程序调用,通过SSE发回响应 + * + * @param response 响应. + */ + public void broadcastResponse(McpResponse response) { + if (emitters.isEmpty()) { + log.warn("No active SSE emitters to broadcast response (ID: {})\n", response.getId()); + return; + } + + try { + // Responses are sent as events of type "message" + String jsonResponse = objectMapper.writeValueAsString(response); + + for (SseEmitter emitter : emitters) { + try { + emitter.send(SseEmitter.event() + .name("message") + .data(jsonResponse)); + log.debug("Successfully sent SSE message for Response ID: {}", response.getId()); + } catch (IOException e) { + log.error("Failed to send SSE message (Response ID: {}): {}", response.getId(), e.getMessage(), e); + // 考虑移除有故障的发射器 + emitter.completeWithError(e); + } + } + } catch (IOException e) { + log.error("Failed to serialize McpResponse (ID: {}) to JSON for SSE: {}", response.getId(), e.getMessage(), e); + } + } + + /** + * Sends a simple notification (like log messages, tool updates) over SSE. + * This isn't used in the simple weather example but shows how non-response + * messages would be sent. + * + * @param notification An object representing the notification. + * @param eventName The SSE event name (e.g., "notifications/message"). + */ + public void broadcastNotification(Object notification, String eventName) { + if (emitters.isEmpty()) { + log.warn("No active SSE emitters to broadcast notification ({})\n", eventName); + return; + } + + try { + String jsonNotification = objectMapper.writeValueAsString(notification); + + for (SseEmitter emitter : emitters) { + try { + emitter.send(SseEmitter.event() + .name(eventName) + .data(jsonNotification)); + log.debug("Successfully sent SSE notification ({})\n", eventName); + } catch (IOException e) { + log.error("Failed to send SSE notification ({}): {}", eventName, e.getMessage(), e); + emitter.completeWithError(e); + } + } + } catch (IOException e) { + log.error("Failed to serialize notification ({}) to JSON for SSE: {}", eventName, e.getMessage(), e); + } + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/SseController.java b/src/main/java/xyz/wbsite/mcp/basic/SseController.java new file mode 100644 index 0000000..cfa522a --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/SseController.java @@ -0,0 +1,35 @@ +package xyz.wbsite.mcp.basic; + +import jakarta.annotation.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +/** + * SSE控制器类 + * 用于处理SSE连接请求和事件发送 + * + * @author wangbing + */ +@RestController +@RequestMapping("/mcp/sse") +public class SseController { + + private static final Logger log = LoggerFactory.getLogger(SseController.class); + + @Resource + private SseBroadcaster broadcaster; + + @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public SseEmitter connectSse() { + log.info("Client requesting SSE connection..."); + SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); + broadcaster.registerEmitter(emitter); + broadcaster.sendEndpointEvent(emitter); + return emitter; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/TextContentData.java b/src/main/java/xyz/wbsite/mcp/basic/TextContentData.java new file mode 100644 index 0000000..0dd7c9b --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/TextContentData.java @@ -0,0 +1,44 @@ +package xyz.wbsite.mcp.basic; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 文本内容数据类 + * 用于封装文本类型的内容数据 + * + * @author wangbing + */ +public class TextContentData extends Data { + @JsonProperty("type") + private String type; + @JsonProperty("text") + private String text; + + public TextContentData() { + } + + public TextContentData(String type, String text) { + this.type = type; + this.text = text; + } + + public TextContentData(String text) { + this("text", text); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/basic/ToolSpecificationData.java b/src/main/java/xyz/wbsite/mcp/basic/ToolSpecificationData.java new file mode 100644 index 0000000..3f82974 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/basic/ToolSpecificationData.java @@ -0,0 +1,46 @@ +package xyz.wbsite.mcp.basic; + +/** + * 工具规格数据类 + * 用于封装工具的基本信息和输入规范 + * + * @author wangbing + */ +public class ToolSpecificationData extends Data { + private String name; + private String description; + private InputSchema inputSchema; + + public ToolSpecificationData() { + } + + public ToolSpecificationData(String name, String description, InputSchema inputSchema) { + this.name = name; + this.description = description; + this.inputSchema = inputSchema; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public InputSchema getInputSchema() { + return inputSchema; + } + + public void setInputSchema(InputSchema inputSchema) { + this.inputSchema = inputSchema; + } +} diff --git a/src/main/java/xyz/wbsite/mcp/easy/McpServerApplication.java b/src/main/java/xyz/wbsite/mcp/easy/McpServerApplication.java new file mode 100644 index 0000000..afe5330 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/easy/McpServerApplication.java @@ -0,0 +1,17 @@ +package xyz.wbsite.mcp.easy; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * MCP服务程序入口 + * + * @author wangbing + */ +@SpringBootApplication +public class McpServerApplication { + + public static void main(String[] args) { + SpringApplication.run(McpServerApplication.class, args); + } +} diff --git a/src/main/java/xyz/wbsite/mcp/easy/annotation/P.java b/src/main/java/xyz/wbsite/mcp/easy/annotation/P.java new file mode 100644 index 0000000..a5ae5de --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/easy/annotation/P.java @@ -0,0 +1,23 @@ +package xyz.wbsite.mcp.easy.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.PARAMETER}) +public @interface P { + /** + * Description of a parameter + * @return the description of a parameter + */ + String value(); + + /** + * Whether the parameter is required + * @return true if the parameter is required, false otherwise + * Default is true. + */ + boolean required() default true; +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/easy/annotation/Tool.java b/src/main/java/xyz/wbsite/mcp/easy/annotation/Tool.java new file mode 100644 index 0000000..e3f73c7 --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/easy/annotation/Tool.java @@ -0,0 +1,28 @@ +package xyz.wbsite.mcp.easy.annotation; + +import org.springframework.core.annotation.AliasFor; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface Tool { + + /** + * Name of the tool. If not provided, method name will be used. + * + * @return name of the tool. + */ + String name() default ""; + + /** + * Description of the tool. + * + * @return description of the tool. + */ + String value() default ""; +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/easy/config/McpServerConfig.java b/src/main/java/xyz/wbsite/mcp/easy/config/McpServerConfig.java new file mode 100644 index 0000000..198b37f --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/easy/config/McpServerConfig.java @@ -0,0 +1,24 @@ +package xyz.wbsite.mcp.easy.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.modelcontextprotocol.server.transport.WebFluxSseServerTransportProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RouterFunction; + +/** + * @author quanyu + * @date 2025/5/6 22:39 + */ +@Configuration +class McpServerConfig { + @Bean + WebFluxSseServerTransportProvider webFluxSseServerTransportProvider() { + return new WebFluxSseServerTransportProvider(new ObjectMapper(), "/mcp/message"); + } + + @Bean + RouterFunction mcpRouterFunction(WebFluxSseServerTransportProvider provider) { + return provider.getRouterFunction(); + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/easy/registrar/McpServerRegistrar.java b/src/main/java/xyz/wbsite/mcp/easy/registrar/McpServerRegistrar.java new file mode 100644 index 0000000..cbecebd --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/easy/registrar/McpServerRegistrar.java @@ -0,0 +1,166 @@ + +package xyz.wbsite.mcp.easy.registrar; + +import cn.hutool.json.JSONUtil; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.modelcontextprotocol.server.McpServer; +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.server.McpSyncServer; +import io.modelcontextprotocol.server.transport.WebFluxSseServerTransportProvider; +import io.modelcontextprotocol.spec.McpSchema; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.Resource; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; +import xyz.wbsite.mcp.easy.annotation.P; +import xyz.wbsite.mcp.easy.annotation.Tool; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component +public class McpServerRegistrar { + + @Resource + private ApplicationContext applicationContext; + @Resource + private WebFluxSseServerTransportProvider transport; + + @PostConstruct + public void registerMcpServers() { + // 创建具有自定义配置的服务器 + McpSyncServer syncServer = McpServer.sync(transport) + .serverInfo("Mcp Server", "1.0.0") + .capabilities(McpSchema.ServerCapabilities.builder() + .resources(true, true) // 启用资源支持 + .tools(true) // 启用工具支持 + .prompts(true) // 启用提示支持 + .logging() // 启用日志支持 + .build()) + .build(); + // 查找方法级别的Tool注解 + String[] beanNames = applicationContext.getBeanDefinitionNames(); + for (String beanName : beanNames) { + // 跳过自身 Bean,避免循环依赖 + if (beanName.equals("mcpServerRegistrar")) { + continue; + } + Object bean = applicationContext.getBean(beanName); + for (Method method : bean.getClass().getMethods()) { + if (method.isAnnotationPresent(Tool.class)) { + Tool tool = method.getAnnotation(Tool.class); + // 处理参数 + ObjectNode schema = new ObjectNode(JsonNodeFactory.instance); + schema.put("type", "object"); + ArrayNode required = schema.putArray("required"); + Parameter[] parameters = method.getParameters(); + for (Parameter parameter : parameters) { + this.putProperties(schema, parameter); + required.add(parameter.getName()); + } + McpServerFeatures.SyncToolSpecification syncToolSpecification = buildSyncToolSpecification(bean, method, tool.value(), schema.toPrettyString()); + syncServer.addTool(syncToolSpecification); + } + } + } + // 发送日志通知 + syncServer.loggingNotification(McpSchema.LoggingMessageNotification.builder() + .level(McpSchema.LoggingLevel.INFO) + .logger("Mcp Server Log") + .data("The server has been initialized") + .build()); + } + + private void putProperties(ObjectNode schema, Parameter parameter) { + // 处理参数 + String typeName = jsonTypeMapper(parameter); + + ObjectNode properties = (ObjectNode) schema.get("properties"); + if (properties == null) { + properties = schema.putObject("properties"); + } + ObjectNode paramSchema = properties.putObject(parameter.getName()); + paramSchema.put("type", typeName); + if (parameter.isAnnotationPresent(P.class)) { + P p = parameter.getAnnotation(P.class); + paramSchema.put("description", p.value()); + } + } + + private String jsonTypeMapper(Parameter parameter) { + Class paramType = parameter.getType(); + Type genericType = parameter.getParameterizedType(); + + // 基础类型判断 + if (paramType.isPrimitive()) { + if (paramType == boolean.class) { + return "boolean"; + } else if (paramType == char.class) { + return "string"; + } else { + return "number"; + } + } else if (Number.class.isAssignableFrom(paramType)) { + return "number"; + } else if (paramType == String.class) { + return "string"; + } else if (paramType == Boolean.class) { + return "boolean"; + } + + // 复合类型判断 + if (paramType.isArray() || Collection.class.isAssignableFrom(paramType)) { + return "array"; + } else if (Map.class.isAssignableFrom(paramType)) { + return "object"; + } + + // 泛型类型处理 + if (genericType instanceof ParameterizedType) { + Type rawType = ((ParameterizedType) genericType).getRawType(); + if (rawType == List.class || rawType == Set.class) { + return "array"; + } + } + + // 默认视为对象 + return "object"; + } + + private McpServerFeatures.SyncToolSpecification buildSyncToolSpecification(Object instance, Method method, String toolDesc, String schema) { + // 定义Tool + McpSchema.Tool tool = new McpSchema.Tool( + method.getName(), + toolDesc, + schema + ); + // 定义同步工具 + return new McpServerFeatures.SyncToolSpecification( + tool, + (exchange, arguments) -> { + //执行函数 + try { + Parameter[] parameters = method.getParameters(); + Object[] argArr = new Object[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + argArr[i] = arguments.get(parameters[i].getName()); + } + Object obj = method.invoke(instance, argArr); + String str = obj == null ? "" : JSONUtil.toJsonStr(obj); + return new McpSchema.CallToolResult(Collections.singletonList(new McpSchema.TextContent(str)), false); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + ); + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/mcp/easy/tools/WeatherService.java b/src/main/java/xyz/wbsite/mcp/easy/tools/WeatherService.java new file mode 100644 index 0000000..d5642ac --- /dev/null +++ b/src/main/java/xyz/wbsite/mcp/easy/tools/WeatherService.java @@ -0,0 +1,17 @@ +package xyz.wbsite.mcp.easy.tools; + +import org.springframework.stereotype.Service; +import xyz.wbsite.mcp.easy.annotation.P; +import xyz.wbsite.mcp.easy.annotation.Tool; + +/** + * 示例工具定义 + */ +@Service +public class WeatherService { + + @Tool("Gets the current weather forecast.") + public String getWeatherForecast(@P("Location to get the weather for") String location) { + return location + "天气晴,23℃~27℃"; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..2d76a14 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 + +# spring.jackson.serialization.fail-on-empty-beans=false diff --git a/starter-mcp-server-app/pom.xml b/starter-mcp-server-app/pom.xml new file mode 100644 index 0000000..d5b21b5 --- /dev/null +++ b/starter-mcp-server-app/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + xyz.wbsite + starter-mcp-server + 0.1 + + + starter-mcp-server-app + + + 17 + 17 + UTF-8 + + + \ No newline at end of file diff --git a/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/McpServerApplication.java b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/McpServerApplication.java new file mode 100644 index 0000000..afe5330 --- /dev/null +++ b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/McpServerApplication.java @@ -0,0 +1,17 @@ +package xyz.wbsite.mcp.easy; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * MCP服务程序入口 + * + * @author wangbing + */ +@SpringBootApplication +public class McpServerApplication { + + public static void main(String[] args) { + SpringApplication.run(McpServerApplication.class, args); + } +} diff --git a/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/annotation/P.java b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/annotation/P.java new file mode 100644 index 0000000..a5ae5de --- /dev/null +++ b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/annotation/P.java @@ -0,0 +1,23 @@ +package xyz.wbsite.mcp.easy.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.PARAMETER}) +public @interface P { + /** + * Description of a parameter + * @return the description of a parameter + */ + String value(); + + /** + * Whether the parameter is required + * @return true if the parameter is required, false otherwise + * Default is true. + */ + boolean required() default true; +} \ No newline at end of file diff --git a/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/annotation/Tool.java b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/annotation/Tool.java new file mode 100644 index 0000000..e3f73c7 --- /dev/null +++ b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/annotation/Tool.java @@ -0,0 +1,28 @@ +package xyz.wbsite.mcp.easy.annotation; + +import org.springframework.core.annotation.AliasFor; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface Tool { + + /** + * Name of the tool. If not provided, method name will be used. + * + * @return name of the tool. + */ + String name() default ""; + + /** + * Description of the tool. + * + * @return description of the tool. + */ + String value() default ""; +} \ No newline at end of file diff --git a/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/config/McpServerConfig.java b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/config/McpServerConfig.java new file mode 100644 index 0000000..198b37f --- /dev/null +++ b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/config/McpServerConfig.java @@ -0,0 +1,24 @@ +package xyz.wbsite.mcp.easy.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.modelcontextprotocol.server.transport.WebFluxSseServerTransportProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RouterFunction; + +/** + * @author quanyu + * @date 2025/5/6 22:39 + */ +@Configuration +class McpServerConfig { + @Bean + WebFluxSseServerTransportProvider webFluxSseServerTransportProvider() { + return new WebFluxSseServerTransportProvider(new ObjectMapper(), "/mcp/message"); + } + + @Bean + RouterFunction mcpRouterFunction(WebFluxSseServerTransportProvider provider) { + return provider.getRouterFunction(); + } +} \ No newline at end of file diff --git a/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/registrar/McpServerRegistrar.java b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/registrar/McpServerRegistrar.java new file mode 100644 index 0000000..cbecebd --- /dev/null +++ b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/registrar/McpServerRegistrar.java @@ -0,0 +1,166 @@ + +package xyz.wbsite.mcp.easy.registrar; + +import cn.hutool.json.JSONUtil; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.modelcontextprotocol.server.McpServer; +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.server.McpSyncServer; +import io.modelcontextprotocol.server.transport.WebFluxSseServerTransportProvider; +import io.modelcontextprotocol.spec.McpSchema; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.Resource; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; +import xyz.wbsite.mcp.easy.annotation.P; +import xyz.wbsite.mcp.easy.annotation.Tool; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component +public class McpServerRegistrar { + + @Resource + private ApplicationContext applicationContext; + @Resource + private WebFluxSseServerTransportProvider transport; + + @PostConstruct + public void registerMcpServers() { + // 创建具有自定义配置的服务器 + McpSyncServer syncServer = McpServer.sync(transport) + .serverInfo("Mcp Server", "1.0.0") + .capabilities(McpSchema.ServerCapabilities.builder() + .resources(true, true) // 启用资源支持 + .tools(true) // 启用工具支持 + .prompts(true) // 启用提示支持 + .logging() // 启用日志支持 + .build()) + .build(); + // 查找方法级别的Tool注解 + String[] beanNames = applicationContext.getBeanDefinitionNames(); + for (String beanName : beanNames) { + // 跳过自身 Bean,避免循环依赖 + if (beanName.equals("mcpServerRegistrar")) { + continue; + } + Object bean = applicationContext.getBean(beanName); + for (Method method : bean.getClass().getMethods()) { + if (method.isAnnotationPresent(Tool.class)) { + Tool tool = method.getAnnotation(Tool.class); + // 处理参数 + ObjectNode schema = new ObjectNode(JsonNodeFactory.instance); + schema.put("type", "object"); + ArrayNode required = schema.putArray("required"); + Parameter[] parameters = method.getParameters(); + for (Parameter parameter : parameters) { + this.putProperties(schema, parameter); + required.add(parameter.getName()); + } + McpServerFeatures.SyncToolSpecification syncToolSpecification = buildSyncToolSpecification(bean, method, tool.value(), schema.toPrettyString()); + syncServer.addTool(syncToolSpecification); + } + } + } + // 发送日志通知 + syncServer.loggingNotification(McpSchema.LoggingMessageNotification.builder() + .level(McpSchema.LoggingLevel.INFO) + .logger("Mcp Server Log") + .data("The server has been initialized") + .build()); + } + + private void putProperties(ObjectNode schema, Parameter parameter) { + // 处理参数 + String typeName = jsonTypeMapper(parameter); + + ObjectNode properties = (ObjectNode) schema.get("properties"); + if (properties == null) { + properties = schema.putObject("properties"); + } + ObjectNode paramSchema = properties.putObject(parameter.getName()); + paramSchema.put("type", typeName); + if (parameter.isAnnotationPresent(P.class)) { + P p = parameter.getAnnotation(P.class); + paramSchema.put("description", p.value()); + } + } + + private String jsonTypeMapper(Parameter parameter) { + Class paramType = parameter.getType(); + Type genericType = parameter.getParameterizedType(); + + // 基础类型判断 + if (paramType.isPrimitive()) { + if (paramType == boolean.class) { + return "boolean"; + } else if (paramType == char.class) { + return "string"; + } else { + return "number"; + } + } else if (Number.class.isAssignableFrom(paramType)) { + return "number"; + } else if (paramType == String.class) { + return "string"; + } else if (paramType == Boolean.class) { + return "boolean"; + } + + // 复合类型判断 + if (paramType.isArray() || Collection.class.isAssignableFrom(paramType)) { + return "array"; + } else if (Map.class.isAssignableFrom(paramType)) { + return "object"; + } + + // 泛型类型处理 + if (genericType instanceof ParameterizedType) { + Type rawType = ((ParameterizedType) genericType).getRawType(); + if (rawType == List.class || rawType == Set.class) { + return "array"; + } + } + + // 默认视为对象 + return "object"; + } + + private McpServerFeatures.SyncToolSpecification buildSyncToolSpecification(Object instance, Method method, String toolDesc, String schema) { + // 定义Tool + McpSchema.Tool tool = new McpSchema.Tool( + method.getName(), + toolDesc, + schema + ); + // 定义同步工具 + return new McpServerFeatures.SyncToolSpecification( + tool, + (exchange, arguments) -> { + //执行函数 + try { + Parameter[] parameters = method.getParameters(); + Object[] argArr = new Object[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + argArr[i] = arguments.get(parameters[i].getName()); + } + Object obj = method.invoke(instance, argArr); + String str = obj == null ? "" : JSONUtil.toJsonStr(obj); + return new McpSchema.CallToolResult(Collections.singletonList(new McpSchema.TextContent(str)), false); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + ); + } +} \ No newline at end of file diff --git a/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/tools/WeatherService.java b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/tools/WeatherService.java new file mode 100644 index 0000000..f455a76 --- /dev/null +++ b/starter-mcp-server-app/src/main/java/xyz/wbsite/mcp/easy/tools/WeatherService.java @@ -0,0 +1,17 @@ +package xyz.wbsite.mcp.easy.tools; + +import org.springframework.stereotype.Service; +import xyz.wbsite.mcp.easy.annotation.P; +import xyz.wbsite.mcp.easy.annotation.Tool; + +/** + * 示例工具定义 + */ +@Service +public class WeatherService { + + @Tool("获取天气预报.") + public String getWeatherForecast(@P("天气预报所在城市") String location) { + return location + "天气晴,23℃~27℃"; + } +} diff --git a/starter-mcp-server-app/src/main/resources/application.properties b/starter-mcp-server-app/src/main/resources/application.properties new file mode 100644 index 0000000..2d76a14 --- /dev/null +++ b/starter-mcp-server-app/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 + +# spring.jackson.serialization.fail-on-empty-beans=false diff --git a/starter-mcp-server-basic/pom.xml b/starter-mcp-server-basic/pom.xml new file mode 100644 index 0000000..ed23283 --- /dev/null +++ b/starter-mcp-server-basic/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + xyz.wbsite + starter-mcp-server-basic + 0.1 + jar + + starter-mcp-server + Spring Boot MCP Server Demo + + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + + + 17 + 17 + 17 + UTF-8 + + + + + + central + Central Repository + default + https://maven.aliyun.com/repository/public + + + + + + central + Central Repository + https://maven.aliyun.com/repository/public + default + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + cn.hutool + hutool-all + 5.8.24 + + + \ No newline at end of file diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/BasicApplication.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/BasicApplication.java new file mode 100644 index 0000000..d802129 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/BasicApplication.java @@ -0,0 +1,18 @@ +package xyz.wbsite.mcp.basic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * MCP基础原理示例入口 + * 该方式适合理解mcp原理,开发较繁琐,需要自己解析工具,不适合生产环境下使用,请参考@link{McpServerApplication} + * + * @author wangbing + */ +@SpringBootApplication +public class BasicApplication { + + public static void main(String[] args) { + SpringApplication.run(BasicApplication.class, args); + } +} \ No newline at end of file diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/SseBroadcaster.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/SseBroadcaster.java new file mode 100644 index 0000000..5cbb4be --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/SseBroadcaster.java @@ -0,0 +1,132 @@ +package xyz.wbsite.mcp.basic; + +import cn.hutool.json.JSONUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; +import xyz.wbsite.mcp.basic.model.McpResponse; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * SSE广播器类 + * 用于管理和广播SSE事件给所有已连接的客户端 + * + * @author wangbing + */ +@Service // Manages the SSE emitters +public class SseBroadcaster { + + private static final Logger log = LoggerFactory.getLogger(SseBroadcaster.class); + + private final List emitters = new CopyOnWriteArrayList<>(); +// private final ObjectMapper objectMapper; + +// public SseBroadcaster(ObjectMapper objectMapper) { +// this.objectMapper = objectMapper; +// } + + /** + * 注册新的SSE发射器 + * + * @param emitter sse发射器 + */ + public void registerEmitter(SseEmitter emitter) { + // Add the emitter to the list + emitters.add(emitter); + log.info("New SSE emitter registered, total emitters: {}", emitters.size()); + + // Set up completion handlers to remove the emitter when the connection is closed + emitter.onCompletion(() -> { + emitters.remove(emitter); + log.info("SSE emitter completed, remaining emitters: {}", emitters.size()); + }); + + emitter.onTimeout(() -> { + emitters.remove(emitter); + log.info("SSE emitter timed out, remaining emitters: {}", emitters.size()); + }); + + emitter.onError((e) -> { + emitters.remove(emitter); + log.error("Error on SSE emitter: {}", e.getMessage(), e); + }); + } + + /** + * 将初始端点事件发送到特定发射器 + * + * @param emitter sse发射器 + */ + public void sendEndpointEvent(SseEmitter emitter) { + try { + emitter.send(SseEmitter.event() + .name("endpoint") + .data("/mcp/post")); + log.info("Sent endpoint event to SSE emitter"); + } catch (IOException e) { + log.error("Failed to send endpoint event: {}", e.getMessage(), e); + emitter.completeWithError(e); + } + } + + /** + * 由POST端点处理程序调用,通过SSE发回响应 + * + * @param response 响应. + */ + public void broadcastResponse(McpResponse response) { + if (emitters.isEmpty()) { + log.warn("No active SSE emitters to broadcast response (ID: {})\n", response.getId()); + return; + } + + // Responses are sent as events of type "message" + String jsonResponse = JSONUtil.toJsonStr(response); + + for (SseEmitter emitter : emitters) { + try { + emitter.send(SseEmitter.event() + .name("message") + .data(jsonResponse)); + log.debug("Successfully sent SSE message for Response ID: {}", response.getId()); + } catch (IOException e) { + log.error("Failed to send SSE message (Response ID: {}): {}", response.getId(), e.getMessage(), e); + // 考虑移除有故障的发射器 + emitter.completeWithError(e); + } + } + } + + /** + * Sends a simple notification (like log messages, tool updates) over SSE. + * This isn't used in the simple weather example but shows how non-response + * messages would be sent. + * + * @param notification An object representing the notification. + * @param eventName The SSE event name (e.g., "notifications/message"). + */ + public void broadcastNotification(Object notification, String eventName) { + if (emitters.isEmpty()) { + log.warn("No active SSE emitters to broadcast notification ({})\n", eventName); + return; + } + + String jsonNotification = JSONUtil.toJsonStr(notification); + + for (SseEmitter emitter : emitters) { + try { + emitter.send(SseEmitter.event() + .name(eventName) + .data(jsonNotification)); + log.debug("Successfully sent SSE notification ({})\n", eventName); + } catch (IOException e) { + log.error("Failed to send SSE notification ({}): {}", eventName, e.getMessage(), e); + emitter.completeWithError(e); + } + } + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/SseController.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/SseController.java new file mode 100644 index 0000000..cfa522a --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/SseController.java @@ -0,0 +1,35 @@ +package xyz.wbsite.mcp.basic; + +import jakarta.annotation.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +/** + * SSE控制器类 + * 用于处理SSE连接请求和事件发送 + * + * @author wangbing + */ +@RestController +@RequestMapping("/mcp/sse") +public class SseController { + + private static final Logger log = LoggerFactory.getLogger(SseController.class); + + @Resource + private SseBroadcaster broadcaster; + + @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public SseEmitter connectSse() { + log.info("Client requesting SSE connection..."); + SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); + broadcaster.registerEmitter(emitter); + broadcaster.sendEndpointEvent(emitter); + return emitter; + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/CallToolResult.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/CallToolResult.java new file mode 100644 index 0000000..cf8106d --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/CallToolResult.java @@ -0,0 +1,50 @@ +package xyz.wbsite.mcp.basic.model; + +import java.util.List; + +/** + * 调用工具的结果类 + * 用于封装工具调用后的返回数据和错误状态 + * + * @author wangbing + */ +public class CallToolResult extends Data { + + /** + * 工具调用返回的内容数据列表 + */ + private List content; + + /** + * 工具调用是否出错 + */ + private Boolean isError; + + public CallToolResult() { + } + + public CallToolResult(List content, Boolean isError) { + this.content = content; + this.isError = isError; + } + + public CallToolResult(List content) { + this(content, false); + } + + public List getContent() { + return content; + } + + public void setContent(List content) { + this.content = content; + } + + public Boolean getIsError() { + return isError; + } + + public void setIsError(Boolean isError) { + this.isError = isError; + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/Data.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/Data.java new file mode 100644 index 0000000..968ea3f --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/Data.java @@ -0,0 +1,18 @@ +package xyz.wbsite.mcp.basic.model; + +import java.io.Serial; +import java.io.Serializable; + +/** + * 可序列化基类. + * + * @author wangbing + * @version 0.0.1 + * @since 1.8 + */ +public class Data implements Serializable { + + @Serial + private static final long serialVersionUID = -1L; + +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/InitializeResult.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/InitializeResult.java new file mode 100644 index 0000000..e9d3c0d --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/InitializeResult.java @@ -0,0 +1,30 @@ +package xyz.wbsite.mcp.basic.model; + +/** + * 初始化结果类 + * 用于封装服务器初始化后的能力信息 + * + * @author wangbing + */ +public class InitializeResult extends Data { + + /** + * 服务器能力信息 + */ + private ServerCapabilities capabilities; + + public InitializeResult() { + } + + public InitializeResult(ServerCapabilities capabilities) { + this.capabilities = capabilities; + } + + public ServerCapabilities getCapabilities() { + return capabilities; + } + + public void setCapabilities(ServerCapabilities capabilities) { + this.capabilities = capabilities; + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/InputSchema.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/InputSchema.java new file mode 100644 index 0000000..452a12e --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/InputSchema.java @@ -0,0 +1,75 @@ +package xyz.wbsite.mcp.basic.model; + +import java.util.List; +import java.util.Map; + +/** + * 输入模式类 + * 用于定义工具输入参数的结构和验证规则 + * + * @author wangbing + */ +public class InputSchema extends Data { + + /** + * 输入模式的类型 + */ + private String type; + + /** + * 输入模式的属性定义 + */ + private Map properties; + + /** + * 输入模式的必填字段列表 + */ + private List required; + + /** + * 输入模式是否允许额外属性 + */ + private Boolean additionalProperties; + + public InputSchema() { + } + + public InputSchema(String type, Map properties, List required, Boolean additionalProperties) { + this.type = type; + this.properties = properties; + this.required = required; + this.additionalProperties = additionalProperties; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public List getRequired() { + return required; + } + + public void setRequired(List required) { + this.required = required; + } + + public Boolean getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Boolean additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ListToolsResult.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ListToolsResult.java new file mode 100644 index 0000000..ec6a326 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ListToolsResult.java @@ -0,0 +1,32 @@ +package xyz.wbsite.mcp.basic.model; + +import java.util.List; + +/** + * 工具列表结果类 + * 用于封装可用工具的列表信息 + * + * @author wangbing + */ +public class ListToolsResult extends Data { + + /** + * 工具列表 + */ + private List tools; + + public ListToolsResult() { + } + + public ListToolsResult(List tools) { + this.tools = tools; + } + + public List getTools() { + return tools; + } + + public void setTools(List tools) { + this.tools = tools; + } +} \ No newline at end of file diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpError.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpError.java new file mode 100644 index 0000000..73f4df4 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpError.java @@ -0,0 +1,36 @@ +package xyz.wbsite.mcp.basic.model; + +/** + * 错误信息类 + * 用于封装错误代码和错误消息 + * + * @author wangbing + */ +public class McpError extends Data { + private int code; + private String message; + + public McpError() { + } + + public McpError(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpRequest.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpRequest.java new file mode 100644 index 0000000..341c1c6 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpRequest.java @@ -0,0 +1,58 @@ +package xyz.wbsite.mcp.basic.model; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * MCP协议请求类 + * 用于封装JSON-RPC格式的请求数据 + * + * @author wangbing + */ +public class McpRequest extends Data { + private String jsonrpc; + private Long id; + private String method; + private JsonNode params; // Use JsonNode for flexible params + + public McpRequest() { + } + + public McpRequest(String jsonrpc, Long id, String method, JsonNode params) { + this.jsonrpc = jsonrpc; + this.id = id; + this.method = method; + this.params = params; + } + + public String getJsonrpc() { + return jsonrpc; + } + + public void setJsonrpc(String jsonrpc) { + this.jsonrpc = jsonrpc; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public JsonNode getParams() { + return params; + } + + public void setParams(JsonNode params) { + this.params = params; + } +} \ No newline at end of file diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpResponse.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpResponse.java new file mode 100644 index 0000000..b3ba8b0 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/McpResponse.java @@ -0,0 +1,65 @@ +package xyz.wbsite.mcp.basic.model; + +/** + * MCP协议响应类 + * 用于封装JSON-RPC格式的响应数据 + * 支持成功结果和错误信息的返回 + * + * @author wangbing + */ +public class McpResponse extends Data { + private String jsonrpc; + private Long id; + private Object result; // Can be ListToolsResult, CallToolResult, etc. + private McpError error; // Optional error field + + public McpResponse() { + } + + public McpResponse(String jsonrpc, Long id, Object result, McpError error) { + this.jsonrpc = jsonrpc; + this.id = id; + this.result = result; + this.error = error; + } + + public McpResponse(Long id, Object result) { + this("2.0", id, result, null); + } + + public McpResponse(Long id, McpError error) { + this("2.0", id, null, error); + } + + public String getJsonrpc() { + return jsonrpc; + } + + public void setJsonrpc(String jsonrpc) { + this.jsonrpc = jsonrpc; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + } + + public McpError getError() { + return error; + } + + public void setError(McpError error) { + this.error = error; + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/PostController.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/PostController.java new file mode 100644 index 0000000..e1cb8b6 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/PostController.java @@ -0,0 +1,114 @@ +package xyz.wbsite.mcp.basic.model; + +import jakarta.annotation.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import xyz.wbsite.mcp.basic.SseBroadcaster; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * 后控制器类 + * 用于处理MCP POST请求 + * + * @author wangbing + */ +@RestController +@RequestMapping("/mcp/post") +public class PostController { + + private static final Logger log = LoggerFactory.getLogger(PostController.class); + private static final String WEATHER_TOOL_NAME = "getWeatherForecast"; + private static final String FAKE_WEATHER_JSON = "{\"forecast\": \"sunny\"}"; + + @Resource + SseBroadcaster broadcaster; + + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity handleMcpPostRequest(@RequestBody McpRequest request) { + log.info("Received MCP POST Request: ID={}, Method={}", request.getId(), request.getMethod()); + + McpResponse mcpResponse = processRequest(request); + + if (mcpResponse != null) { + // Send the response back over the SSE channel + broadcaster.broadcastResponse(mcpResponse); + } else { + // 处理可能不会生成McpResponse对象的通知等情况 + // 在我们的例子中,'通知/初始化'落在这里。 + log.debug("No explicit response object generated for method '{}', assuming notification ack.", request.getMethod()); + } + // 立即返回HTTP 200 OK或202 Accepted以确认收到POST。 + // 实际结果通过SSE异步发送。 + // 200 OK可能更简单,因为客户希望得到一些响应体,即使是空的。 + // 202 Accepted明确表示处理正在其他地方进行。让我们用200。 + return ResponseEntity.ok().build(); + } + + private McpResponse processRequest(McpRequest request) { + switch (request.getMethod()) { + case "initialize": + log.info("Handling initialize request"); + InitializeResult initResult = new InitializeResult(new ServerCapabilities()); + return new McpResponse(request.getId(), initResult); + + case "notifications/initialized": + log.info("Received initialized notification"); + // 这是来自客户端的通知。MCP规范称通知 + // 没有回应。所以我们在这里返回null,POST处理程序 + // 将只返回HTTP OK。 + return null; + + case "tools/list": + log.info("Handling tools/list request"); + ToolSpecificationData weatherTool = new ToolSpecificationData( + WEATHER_TOOL_NAME, + "Gets the current weather forecast.", + new InputSchema( + "object", + Map.of("location", Map.of( + "type", "string", + "description", "Location to get the weather for") + ), + List.of("location"), + false) + ); + ListToolsResult listResult = new ListToolsResult(List.of(weatherTool)); + return new McpResponse(request.getId(), listResult); + + case "tools/call": + log.info("Handling tools/call request"); + if (request.getParams() != null && request.getParams().has("name")) { + String toolName = request.getParams().get("name").asText(); + if (WEATHER_TOOL_NAME.equals(toolName)) { + log.info("Executing tool: {}", toolName); + TextContentData textContent = new TextContentData(FAKE_WEATHER_JSON); + CallToolResult callResult = new CallToolResult(List.of(textContent)); + return new McpResponse(request.getId(), callResult); + } else { + log.warn("Unknown tool requested: {}", toolName); + return new McpResponse(request.getId(), new McpError(-32601, "Method not found: " + toolName)); + } + } else { + log.error("Invalid tools/call request: Missing 'name' in params"); + return new McpResponse(request.getId(), new McpError(-32602, "Invalid params for tools/call")); + } + + case "ping": + log.info("Handling ping request"); + return new McpResponse(request.getId(), Collections.emptyMap()); + + default: + log.warn("Unsupported MCP method: {}", request.getMethod()); + return new McpResponse(request.getId(), new McpError(-32601, "Method not found: " + request.getMethod())); + } + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ServerCapabilities.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ServerCapabilities.java new file mode 100644 index 0000000..1bc4ef6 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ServerCapabilities.java @@ -0,0 +1,15 @@ +package xyz.wbsite.mcp.basic.model; + +import java.io.Serial; + +/** + * 服务器能力类 + * 用于封装服务器支持的功能和特性 + * + * @author wangbing + */ +public class ServerCapabilities extends Data { + + @Serial + private static final long serialVersionUID = 1L; +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/TextContentData.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/TextContentData.java new file mode 100644 index 0000000..0054c45 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/TextContentData.java @@ -0,0 +1,44 @@ +package xyz.wbsite.mcp.basic.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 文本内容数据类 + * 用于封装文本类型的内容数据 + * + * @author wangbing + */ +public class TextContentData extends Data { + @JsonProperty("type") + private String type; + @JsonProperty("text") + private String text; + + public TextContentData() { + } + + public TextContentData(String type, String text) { + this.type = type; + this.text = text; + } + + public TextContentData(String text) { + this("text", text); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ToolSpecificationData.java b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ToolSpecificationData.java new file mode 100644 index 0000000..5dd5069 --- /dev/null +++ b/starter-mcp-server-basic/src/main/java/xyz/wbsite/mcp/basic/model/ToolSpecificationData.java @@ -0,0 +1,46 @@ +package xyz.wbsite.mcp.basic.model; + +/** + * 工具规格数据类 + * 用于封装工具的基本信息和输入规范 + * + * @author wangbing + */ +public class ToolSpecificationData extends Data { + private String name; + private String description; + private InputSchema inputSchema; + + public ToolSpecificationData() { + } + + public ToolSpecificationData(String name, String description, InputSchema inputSchema) { + this.name = name; + this.description = description; + this.inputSchema = inputSchema; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public InputSchema getInputSchema() { + return inputSchema; + } + + public void setInputSchema(InputSchema inputSchema) { + this.inputSchema = inputSchema; + } +} diff --git a/starter-mcp-server-basic/src/main/resources/application.properties b/starter-mcp-server-basic/src/main/resources/application.properties new file mode 100644 index 0000000..2d76a14 --- /dev/null +++ b/starter-mcp-server-basic/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 + +# spring.jackson.serialization.fail-on-empty-beans=false