diff --git a/README.md b/README.md index 1ec435e..3d12432 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,10 @@ > Hi there 👋 我是阿朗, 一名 Java 开发者,热衷于分享一些通俗易懂的技术文章。 分享几句鸡汤,长寿在于生活规律;成功在于坚持不懈。 做好的事情,而不是好做的事情。 +## AI 开发 + +- [MCP Streamable HTTP 协议入门与 100 行代码实现](https://wdbyte.com/spring-mcp-server-manual/) + ## ⏳ Java 开发 - [如何破解滑动验证码?](https://www.wdbyte.com/java/img-verification/) @@ -69,6 +73,9 @@ - [Java 集合框架](https://www.wdbyte.com/java/collection/) - [Java 中使用 List ](https://www.wdbyte.com/java/list/) +### 代码测试 +- [Java 断言 Assert 使用教程与最佳实践](https://www.wdbyte.com/java/assert/) + ## 😃Java I/O 教程 - [Java 创建和写入文件](https://www.wdbyte.com/java/io/file-create-write/) diff --git a/core-java-modules/core-java-22/pom.xml b/core-java-modules/core-java-22/pom.xml new file mode 100644 index 0000000..4fc6401 --- /dev/null +++ b/core-java-modules/core-java-22/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.wdbyte.core-java-modules + core-java-22 + 1.0.0-SNAPSHOT + + 22 + 22 + UTF-8 + + \ No newline at end of file diff --git a/core-java-modules/core-java-22/src/main/java/com/wdbyte/Main.java b/core-java-modules/core-java-22/src/main/java/com/wdbyte/Main.java new file mode 100644 index 0000000..cbe7f6f --- /dev/null +++ b/core-java-modules/core-java-22/src/main/java/com/wdbyte/Main.java @@ -0,0 +1,21 @@ +package com.wdbyte; + +/** + * @author www.wdbyte.com + * @date 2025/04/28 + */ +//TIP To Run code, press or +// click the icon in the gutter. +public class Main { + public static void main(String[] args) { + //TIP Press with your caret at the highlighted text + // to see how IntelliJ IDEA suggests fixing it. + System.out.printf("Hello and welcome!"); + + for (int i = 1; i <= 5; i++) { + //TIP Press to start debugging your code. We have set one breakpoint + // for you, but you can always add more by pressing . + System.out.println("i = " + i); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index 2ae8b99..132cc2e 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -35,11 +35,6 @@ org.junit.jupiter junit-jupiter - - org.projectlombok - lombok - 1.18.22 - \ No newline at end of file diff --git a/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Lambda.java b/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Lambda.java index 357f967..cbd5029 100644 --- a/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Lambda.java +++ b/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Lambda.java @@ -1,9 +1,5 @@ package com.wdbyte; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; import org.junit.jupiter.api.Test; import java.util.*; @@ -70,13 +66,33 @@ public void functionLambdaTest() { } - @Getter - @Setter - @ToString - @AllArgsConstructor static class User { private String name; private Integer age; + + public User() { + } + + public User(String name, Integer age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } } public static List userList = new ArrayList(); diff --git a/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Optional.java b/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Optional.java index ec3fa57..fc080a8 100644 --- a/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Optional.java +++ b/core-java-modules/core-java-8/src/main/java/com/wdbyte/Jdk8Optional.java @@ -2,8 +2,6 @@ import java.util.Optional; - -import lombok.Data; import org.junit.jupiter.api.Test; /** @@ -182,23 +180,44 @@ public void optionalTest() { /** * 计算机 */ -@Data class Computer { private Optional soundCard; + + public Optional getSoundCard() { + return soundCard; + } + + public void setSoundCard(Optional soundCard) { + this.soundCard = soundCard; + } } /** * 声卡 */ -@Data class SoundCard { private Optional usb; + + public Optional getUsb() { + return usb; + } + + public void setUsb(Optional usb) { + this.usb = usb; + } } /** * USB */ -@Data class Usb { private String version; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } } diff --git a/core-java-modules/core-java-base/README.md b/core-java-modules/core-java-base/README.md index 0071ce6..5b2d151 100644 --- a/core-java-modules/core-java-base/README.md +++ b/core-java-modules/core-java-base/README.md @@ -22,4 +22,5 @@ - [Java 枚举](https://www.wdbyte.com/java/enum/) - [Java 注释](*https://www.wdbyte.com/java/comment/*) - [Java 集合框架](https://www.wdbyte.com/java/collection/) -- [Java 中使用 List ](https://www.wdbyte.com/java/list/) \ No newline at end of file +- [Java 中使用 List ](https://www.wdbyte.com/java/list/) +- [Java 断言 Assert 使用教程与最佳实践](https://www.wdbyte.com/java/assert/) \ No newline at end of file diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo1.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo1.java new file mode 100644 index 0000000..50490a5 --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo1.java @@ -0,0 +1,29 @@ +package com.wdbyte.assert1; + +import java.util.Arrays; +import java.util.List; + +/** + * @author www.wdbyte.com + * @date 2024/04/22 + */ +public class AssertDemo1 { + public static void main(String[] args) { + + List list = Arrays.asList("1", "2"); + boolean result = list.remove("x"); + //assert result; + assert result : "移除失败"; + System.out.println(calc(100, 10)); + + // 手动开启断言 + //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); + //System.out.println(calc(100, 0)); + } + + public static int calc(int a, int b) { + assert b != 0 : "除数不能为0"; + return a / b; + + } +} diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo2.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo2.java new file mode 100644 index 0000000..735c2bb --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo2.java @@ -0,0 +1,24 @@ +package com.wdbyte.assert1; + +import java.util.Arrays; +import java.util.List; + +import static com.google.common.base.Verify.*; + +/** + * @author www.wdbyte.com + * @date 2024/04/22 + */ +public class AssertDemo2 { + public static void main(String[] args) { + int x = 100; + verifyNotNull(x != 0); + System.out.println(calc(100, 10)); + System.out.println(calc(100, 0)); + } + + public static int calc(int a, int b) { + verify(b != 0, "除数不能为0"); + return a / b; + } +} diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo3.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo3.java new file mode 100644 index 0000000..09e2272 --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo3.java @@ -0,0 +1,20 @@ +package com.wdbyte.assert1; + +import java.util.Arrays; +import java.util.List; + +/** + * @author www.wdbyte.com + * @date 2024/04/22 + */ +public class AssertDemo3 { + static final boolean asserts = false; // 设置为 false 来消除断言 + + public static void main(String[] args) { + List list = Arrays.asList("1", "2"); + boolean result = list.remove("x"); + if (asserts) { + assert result : "移除失败"; + } + } +} diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo4.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo4.java new file mode 100644 index 0000000..565de43 --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo4.java @@ -0,0 +1,25 @@ +package com.wdbyte.assert1; + +import java.util.Arrays; +import java.util.List; + +/** + * @author www.wdbyte.com + * @date 2024/04/22 + */ +public class AssertDemo4 { + + static { + boolean assertsEnabled = false; + assert assertsEnabled = true; // 故意产生副作用!!! + if (!assertsEnabled) { + throw new RuntimeException("必须启用断言!!!"); + } + } + + public static void main(String[] args) { + List list = Arrays.asList("1", "2"); + boolean result = list.remove("x"); + assert result : "移除失败"; + } +} diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo5.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo5.java new file mode 100644 index 0000000..4c37dde --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/AssertDemo5.java @@ -0,0 +1,25 @@ +package com.wdbyte.assert1; + +import java.util.Arrays; +import java.util.List; + +import com.google.common.base.Preconditions; +import com.google.common.base.Verify; +import org.apache.commons.lang3.Validate; +import org.junit.jupiter.api.Assertions; + +/** + * @author www.wdbyte.com + * @date 2024/04/22 + */ +public class AssertDemo5 { + + public static void main(String[] args) { + List list = Arrays.asList("1", "2"); + boolean result = list.remove("x"); + Assertions.assertTrue(result); + Preconditions.checkNotNull("","msg"); + Validate.isTrue(list.isEmpty(),"msg"); + Verify.verify(list.isEmpty(),"msg"); + } +} diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/InitializationDemo.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/InitializationDemo.java new file mode 100644 index 0000000..cfebe99 --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/assert1/InitializationDemo.java @@ -0,0 +1,28 @@ +package com.wdbyte.assert1; + +public class InitializationDemo { + + static { + init(); + } + + static void init() { + System.out.println("Static initialization block called"); + // 假设这里有一个重要的初始化逻辑 + // 这个方法错误地在静态初始化之前被调用了 + assert isProperlyInitialized() : "System not properly initialized"; + } + + static boolean isProperlyInitialized() { + // 这里返回 false 模拟系统未被正确初始化 + return false; + } + + public InitializationDemo() { + System.out.println("Constructor called"); + } + + public static void main(String[] args) { + new InitializationDemo(); + } +} diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest.java index 54032e0..582a6f3 100644 --- a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest.java +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest.java @@ -8,7 +8,7 @@ import java.util.stream.Collectors; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/10/19 */ public class ArrayListTest { diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest2.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest2.java index 357e0f2..f18c9b1 100644 --- a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest2.java +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest2.java @@ -6,7 +6,7 @@ import java.util.Vector; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/10/19 */ public class ArrayListTest2 { diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest3.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest3.java index 02b189f..a88fd7a 100644 --- a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest3.java +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest3.java @@ -9,7 +9,7 @@ import com.google.common.collect.Lists; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/10/19 */ public class ArrayListTest3 { diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest4.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest4.java index d49f5b2..93d09e4 100644 --- a/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest4.java +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/collection/ArrayListTest4.java @@ -12,7 +12,7 @@ import com.google.common.collect.Lists; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/10/19 */ public class ArrayListTest4 { diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/enum2/WeekdayTest.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/enum2/WeekdayTest.java index 6d83265..30e6fd8 100644 --- a/core-java-modules/core-java-base/src/main/java/com/wdbyte/enum2/WeekdayTest.java +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/enum2/WeekdayTest.java @@ -11,7 +11,6 @@ public static void main(String[] args) { System.out.println("Today is Monday."); } - Weekday[] weekdays = Weekday.values(); for (Weekday weekday : weekdays) { System.out.println(weekday); diff --git a/core-java-modules/core-java-base/src/main/java/com/wdbyte/thread/CompletableFutureTest.java b/core-java-modules/core-java-base/src/main/java/com/wdbyte/thread/CompletableFutureTest.java new file mode 100644 index 0000000..7887015 --- /dev/null +++ b/core-java-modules/core-java-base/src/main/java/com/wdbyte/thread/CompletableFutureTest.java @@ -0,0 +1,74 @@ +package com.wdbyte.thread; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; + +import org.junit.jupiter.api.Test; + +/** + * @author www.wdbyte.com + * @date 2023/11/01 + */ +public class CompletableFutureTest { + + /** + * 异步执行程序后,对正常响应和异常响应进行处理 + */ + @Test + public void completableFutureTest1() { + CompletableFuture completableFuture1 = CompletableFuture.supplyAsync(() -> { + sleep(2000); + System.out.println("do....."); + return 1; + }); + + completableFuture1.thenAccept(res -> { + System.out.println("收到结果:" + res + ); + }); + + System.out.println("等待"); + sleep(10 * 1000); + } + @Test + public void completableFutureTest2() { + CompletableFuture completableFuture2 = CompletableFuture.supplyAsync(() -> { + sleep(2000); + System.out.println("do2....."); + return 10 / 0; + }); + completableFuture2.exceptionally(except -> { + System.out.println("发生异常:" + except.getMessage()); + return 0; + }); + + System.out.println("等待"); + sleep(10 * 1000); + } + + @Test + public void completableFutureTest3() { + CompletableFuture completableFuture1 = CompletableFuture.supplyAsync(() -> { + sleep(2000); + System.out.println("do....."); + return 1; + }); + + completableFuture1.thenAccept(res -> { + System.out.println("收到结果:" + res + ); + }); + + System.out.println("等待"); + sleep(10 * 1000); + } + + void sleep(long millis){ + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/EnumMapTest.java b/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/EnumMapTest.java index 4646e7d..1370449 100644 --- a/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/EnumMapTest.java +++ b/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/EnumMapTest.java @@ -3,7 +3,7 @@ import java.util.EnumMap; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/10/20 */ public class EnumMapTest { diff --git a/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/JavaArrays.java b/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/JavaArrays.java index 47da76b..144cdcb 100644 --- a/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/JavaArrays.java +++ b/core-java-modules/core-java-collect/src/main/java/com/wdbyte/collection/JavaArrays.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; /** - * @author niulang + * @author www.wdbyte.com * @date 2024/03/04 */ public class JavaArrays { diff --git a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileAppendDemo.java b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileAppendDemo.java index 6d43afb..53879c8 100644 --- a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileAppendDemo.java +++ b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileAppendDemo.java @@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/12/12 */ public class FileAppendDemo { diff --git a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileCreateAndWriteDemo.java b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileCreateAndWriteDemo.java index 4f4dddd..158942d 100644 --- a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileCreateAndWriteDemo.java +++ b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileCreateAndWriteDemo.java @@ -14,7 +14,7 @@ import org.junit.jupiter.api.Test; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/11/06 */ public class FileCreateAndWriteDemo { diff --git a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileDelete.java b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileDelete.java index 5882f01..f865382 100644 --- a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileDelete.java +++ b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileDelete.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/12/18 */ public class FileDelete { diff --git a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileReadDemo.java b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileReadDemo.java index 87e35b2..276e0e8 100644 --- a/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileReadDemo.java +++ b/core-java-modules/core-java-io/src/main/java/com/wdbyte/io/file/FileReadDemo.java @@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; /** - * @author niulang + * @author www.wdbyte.com * @date 2023/11/08 */ public class FileReadDemo { diff --git a/pom.xml b/pom.xml index 0e2c7f6..b55b3df 100644 --- a/pom.xml +++ b/pom.xml @@ -45,10 +45,5 @@ commons-lang3 ${commons-lang3.version} - - org.projectlombok - lombok - ${lombok.version} - diff --git a/spring-ai/spring-mcp-server-manual/.mvn/wrapper/maven-wrapper.properties b/spring-ai/spring-mcp-server-manual/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8dea6c2 --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip diff --git a/spring-ai/spring-mcp-server-manual/README.md b/spring-ai/spring-mcp-server-manual/README.md new file mode 100644 index 0000000..af5c1b2 --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/README.md @@ -0,0 +1,26 @@ +这个基于 Spring Boot 和 Fastjson 的 MCP(Model Context Protocol)服务实现,是一个遵循 JSON-RPC 2.0 规范的轻量级工具服务端,旨在为大语言模型(LLM)提供标准化的外部能力接口 36。 + +以下是该实现的核心架构与技术特点介绍: + +### 1. 核心协议架构 +该实现采用了 MCP 的 Streamable HTTP 传输机制,通过单一的 HTTP POST 端点(/mcp)处理所有交互逻辑 26。 + +消息格式:所有请求和响应均严格遵循 JSON-RPC 2.0 结构,包含 jsonrpc、id、method 和 params 字段 6。 +生命周期管理:手动实现了 MCP 协议定义的完整链路,包括初始化握手(initialize)、初始化完成通知(notifications/initialized)、工具发现(tools/list)以及工具执行(tools/call) 56。 +### 2. Java 21 技术优化 +利用 Java 21 的现代语法特性极大简化了协议模版代码: + +Record 记录类:使用 record 定义 JsonRpcRequest、Tool 和 ToolCallResult 等数据模型。这消除了 Getter/Setter 等样板代码,确保了消息对象的不可变性,并自动支持 JSON 序列化。 +Switch 表达式:在控制器中使用增强的 switch 表达式处理 method 分发。这种方式比传统的 if-else 更具读性,且利用 yield 关键字实现了逻辑的紧凑闭环。 +文本块(Text Blocks):利用 """ 语法定义工具的 JSON Schema。这使得复杂的输入参数描述(如 inputSchema)在代码中能以原始 JSON 格式直观呈现,便于维护 5。 +### 3. 工具定义与执行逻辑 +该服务模拟了一个名为 getWeather 的城市天气查询工具: + +工具发现:在 tools/list 阶段,服务端会返回该工具的名称、描述以及基于 JSON Schema 的参数定义(要求必填 city 字符串),以便 LLM 理解如何调用该工具 56。 +参数解析:通过 Fastjson 的 JSONObject 直接处理动态参数。在 tools/call 触发时,程序会从 arguments 映射中提取城市名称,并返回标准化的内容结构。 +响应规范:响应体封装在 content 数组中,并包含 isError 标识,这符合 MCP 对工具执行结果的标准化要求 6。 +### 4. 最佳实践体现 +轻量化:不依赖于复杂的 MCP 官方 SDK,仅通过 Spring Boot 基础框架和 Fastjson 实现,适合快速集成到现有生产微服务中 2。 +无状态处理:服务设计为无状态,符合 MCP Streamable HTTP 的简化模式,便于水平扩展。 +错误处理基础:虽然为简易版,但结构上预留了 isError 字段,允许在工具内部出错时让 LLM 感知并尝试自我修正 6。 +这种实现方式展示了如何通过极简的代码量构建符合开放协议标准的 AI 插件系统,降低了 LLM 与私有数据源及外部工具对接的复杂度 13。 \ No newline at end of file diff --git a/spring-ai/spring-mcp-server-manual/mvnw b/spring-ai/spring-mcp-server-manual/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/spring-ai/spring-mcp-server-manual/mvnw.cmd b/spring-ai/spring-mcp-server-manual/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/spring-ai/spring-mcp-server-manual/pom.xml b/spring-ai/spring-mcp-server-manual/pom.xml new file mode 100644 index 0000000..1e9f19e --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.1 + + + com.wdbyte.ai.mcp.manual + spring-mcp-server-manual + 0.0.1-SNAPSHOT + spring-mcp-server-manual + spring-mcp-server-manual + + 21 + + + + org.springframework.boot + spring-boot-starter-webmvc + + + + com.alibaba.fastjson2 + fastjson2 + 2.0.60 + compile + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-ai/spring-mcp-server-manual/src/main/java/com/wdbyte/ai/mcp/manual/McpWeatherController.java b/spring-ai/spring-mcp-server-manual/src/main/java/com/wdbyte/ai/mcp/manual/McpWeatherController.java new file mode 100644 index 0000000..76f2cb8 --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/src/main/java/com/wdbyte/ai/mcp/manual/McpWeatherController.java @@ -0,0 +1,119 @@ +package com.wdbyte.ai.mcp.manual; + +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.alibaba.fastjson2.JSONWriter.Feature; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/mcp") +public class McpWeatherController { + + private static final Logger log = LoggerFactory.getLogger(McpWeatherController.class); + + // 1. 静态化工具定义,使 tools/list 极其简洁 + private static final List AVAILABLE_TOOLS = List.of( + new Tool("getWeather", "获取指定城市的天气预报", + JSONObject.parseObject(""" + { + "type": "object", + "properties": { "city": { "type": "string", "description": "城市名" } }, + "required": ["city"], + "additionalProperties": false + } + """)) + ); + + @PostMapping(consumes = "application/json", produces = "application/json") + public ResponseEntity handleMcpRequest(@RequestBody JsonRpcRequest request) { + Object id = request.id(); + + var response = switch (request.method()) { + case "initialize" -> ok(id, new InitializeResult()); + case "notifications/initialized" -> accepted(); + case "ping" -> ok(id, Map.of()); + case "tools/list" -> ok(id, Map.of("tools", AVAILABLE_TOOLS)); + case "tools/call" -> handleToolCall(id, request.params()); + default -> ResponseEntity.notFound().build(); + }; + log.info("\nrequest: {}\nresponse: {}", JSON.toJSONString(request), JSON.toJSONString(response.getBody())); + return response; + } + + /** + * 优雅处理工具调用:直接通过 JSONObject 转换,无需 String 二次中转 + */ + private ResponseEntity handleToolCall(Object id, JSONObject params) { + if (params == null) return badRequest(); + + var callParams = params.toJavaObject(ToolCallParams.class); + + // 使用 switch 处理多工具扩展性更好 + return switch (callParams.name()) { + case "getWeather" -> { + String city = String.valueOf(callParams.arguments().getOrDefault("city", "未知城市")); + yield ok(id, new ToolCallResult(city + "今日雷暴雨,建议居家")); + } + default -> badRequest(); + }; + } + + // --- 辅助方法 --- + private static ResponseEntity ok(Object id, Object result) { + return ResponseEntity.ok(new JsonRpcResponse(id, result)); + } + + private static ResponseEntity accepted() { + return ResponseEntity.status(202).build(); + } + + private static ResponseEntity badRequest() { + return ResponseEntity.badRequest().build(); + } + + // --- MCP 协议 Records (Java 21) --- + + // 将 params 定义为 JSONObject,方便后续 toJavaObject 转换 + public record JsonRpcRequest(String jsonrpc, Object id, String method, JSONObject params) {} + + public record JsonRpcResponse(String jsonrpc, Object id, Object result) { + public JsonRpcResponse(Object id, Object result) { + this("2.0", id, result); + } + } + + // 初始化结果模型 + public record InitializeResult(String protocolVersion, Capabilities capabilities, ServerInfo serverInfo) { + public InitializeResult() { + this("2025-06-18", new Capabilities(new Tools(false)), new ServerInfo("mcp-weather-server", "1.0.0")); + } + } + + public record ServerInfo(String name, String version) {} + public record Capabilities(Tools tools) {} + public record Tools(boolean listChanged) {} + + // 工具定义模型 + public record Tool(String name, String description, Object inputSchema) {} + + // 工具调用参数模型 + public record ToolCallParams(String name, Map arguments) {} + + // 响应内容模型 + public record Content(String type, String text) { + public Content(String text) { this("text", text); } + } + + public record ToolCallResult(List content, boolean isError) { + public ToolCallResult(String text) { + this(List.of(new Content(text)), false); + } + } +} diff --git a/spring-ai/spring-mcp-server-manual/src/main/java/com/wdbyte/ai/mcp/manual/SpringMcpServerManualApplication.java b/spring-ai/spring-mcp-server-manual/src/main/java/com/wdbyte/ai/mcp/manual/SpringMcpServerManualApplication.java new file mode 100644 index 0000000..48f4ffe --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/src/main/java/com/wdbyte/ai/mcp/manual/SpringMcpServerManualApplication.java @@ -0,0 +1,13 @@ +package com.wdbyte.ai.mcp.manual; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringMcpServerManualApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringMcpServerManualApplication.class, args); + } + +} diff --git a/spring-ai/spring-mcp-server-manual/src/main/resources/application.properties b/spring-ai/spring-mcp-server-manual/src/main/resources/application.properties new file mode 100644 index 0000000..bbc9400 --- /dev/null +++ b/spring-ai/spring-mcp-server-manual/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=spring-mcp-server-manual diff --git a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Cat.java b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Cat.java index 5492a46..be544cd 100644 --- a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Cat.java +++ b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Cat.java @@ -1,15 +1,12 @@ package com.wdbyte.jackson; import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; -import lombok.Data; /** * @author https://www.wdbyte.com * @date 2022/07/17 */ -@Data public class Cat { @JsonSetter(value = "catName") @@ -21,4 +18,24 @@ public class Cat { public String getName() { return name; } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Cat() { + } + + public Cat(String name, Integer age) { + this.name = name; + this.age = age; + } } diff --git a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Order.java b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Order.java index 6318eb3..38eb08d 100644 --- a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Order.java +++ b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Order.java @@ -1,24 +1,15 @@ package com.wdbyte.jackson; -import java.time.LocalDateTime; -import java.util.Date; - import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.ToString; + +import java.time.LocalDateTime; +import java.util.Date; /** * @author https://www.wdbyte.com * @date 2022/07/17 */ -//@Data -@AllArgsConstructor -@NoArgsConstructor -@ToString public class Order { @JsonSetter(value = "orderId") @@ -54,4 +45,22 @@ public LocalDateTime getUpdateTime() { public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } + + @Override + public String toString() { + return "Order{" + + "id=" + id + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } + + public Order() { + } + + public Order(Integer id, Date createTime, LocalDateTime updateTime) { + this.id = id; + this.createTime = createTime; + this.updateTime = updateTime; + } } diff --git a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Person.java b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Person.java index 3bc1210..b1f2a72 100644 --- a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Person.java +++ b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Person.java @@ -2,16 +2,55 @@ import java.util.List; -import lombok.Data; - /** * @author https://www.wdbyte.com * @date 2022/07/16 */ -@Data public class Person { private String name; private Integer age; private List skillList; + + @Override + public String toString() { + return "Person{" + + "name='" + name + '\'' + + ", age=" + age + + ", skillList=" + skillList + + '}'; + } + + public Person(String name, Integer age, List skillList) { + this.name = name; + this.age = age; + this.skillList = skillList; + } + + public Person() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public List getSkillList() { + return skillList; + } + + public void setSkillList(List skillList) { + this.skillList = skillList; + } } diff --git a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Student.java b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Student.java index 377253d..f5baec4 100644 --- a/tool-java-jackson/src/main/java/com/wdbyte/jackson/Student.java +++ b/tool-java-jackson/src/main/java/com/wdbyte/jackson/Student.java @@ -1,36 +1,20 @@ package com.wdbyte.jackson; -import java.util.HashMap; -import java.util.Map; - import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.google.common.collect.Maps; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; + +import java.util.HashMap; +import java.util.Map; /** * @author https://www.wdbyte.com * @date 2022/07/17 */ -@ToString -@AllArgsConstructor -@NoArgsConstructor public class Student { - @Getter - @Setter private String name; - @Getter - @Setter private Integer age; - @Getter - @Setter private Map diyMap = new HashMap<>(); @JsonAnyGetter @@ -45,4 +29,55 @@ public void otherField(String key, String value) { this.diyMap.put(key, value); } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Map getDiyMap() { + return diyMap; + } + + public void setDiyMap(Map diyMap) { + this.diyMap = diyMap; + } + + public Map getInitMap() { + return initMap; + } + + public void setInitMap(Map initMap) { + this.initMap = initMap; + } + + public Student() { + } + + public Student(String name, Integer age, Map diyMap, Map initMap) { + this.name = name; + this.age = age; + this.diyMap = diyMap; + this.initMap = initMap; + } + + @Override + public String toString() { + return "Student{" + + "name='" + name + '\'' + + ", age=" + age + + ", diyMap=" + diyMap + + ", initMap=" + initMap + + '}'; + } }