DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill

上一篇:工具执行、审批与沙箱 · 系列目录 · 下一篇:任务与多 Agent 编排


🧱 骨架进度

上一版注册表里只有文件工具。这章沿用同一个 ToolRuntime,加入插件注册与释放、Skill 加载和 MCP 调用桥。模型与循环仍消费统一的工具说明和结果。完整版本在 lab/chapters/05。

一个文件工具写进宿主里很方便。需求继续加,可能要查内部订单、连浏览器、跑 Node 库,还要照某个团队的操作规范出报告。把所有代码、工具声明和操作步骤都塞进一个 Agent,升级和排错都会越来越难。

这份工程给出了 Java 插件、Node Bridge、MCP 和 Skill 几种入口。它们都能让 Agent 多做一些事,但接入的内容和生命周期各有区别。核对材料和生成报告会同时用到操作规范、查询接口和文件工具。

扩展入口

手上已有的东西 对应入口 实际新增什么
规定报告字段、材料目录和核对顺序的文档 Skill 可按需读取的工作说明
查询内部订单的 Java SDK Java Native 插件 宿主 JVM 内可执行的工具实现
一段依赖 Node 生态的脚本服务 Node Bridge 子进程和宿主间的 RPC 调用
已支持 MCP 的浏览器或数据服务 MCP 客户端 服务发现、工具列表和远程调用

把操作规范放 Skill,模型仍用已有文件工具做事。接 Java SDK,就得定义一个模型能选择的工具,再把参数传给 SDK。MCP 已经约定了发现和调用格式,宿主要维护连接和能力注册。

假设订单团队已经维护一套 Java SDK,负责按身份查订单、校验单据状态。插件可以把一项明确的查询包装成工具,继续调用 SDK,循环无需知道这些业务细节。若业务已提供稳定 HTTP 接口,也可以由其他语言的运行时调用。这里真正需要新写的,可能只是一个工具适配,而非整套 Agent 平台。

包装时也要检查返回内容是否足以判断业务。数量同为 10,一份以箱计,另一份以件计,模型只看到数字就可能误判一致。工具结果需要保留单位、单据状态、来源和必要的版本信息。schema 能描述字段格式,业务含义仍由提供工具的团队负责。这些清楚的接口,比绑定某一个模型更容易长期复用。

💡 概念

RPC 是"远处执行方法"的通信方式。调用方发方法名和参数,接收方执行后回结果。JSON-RPC 给请求 ID、method、params、result 等字段定了通用格式。

Skill 与按需加载

OpenAI 的 Skill 文档采用渐进加载。初始上下文提供名称和描述,选中后才读取完整 SKILL.md,还可以带脚本和参考资料。Build skills

模型处理编号核对时,只需知道有一份"项目报告规范";需要出报告时,再把字段要求读进来。读文件工具可以一直复用,整篇规范不必参与每次推理。描述写得太宽,会把无关任务也匹配过来;描述缺少触发条件,模型又可能不知道何时使用。

当前工程的 SkillTool.execute() 找到定义后,把正文包装成文本结果。加载路径如下:
#mermaid-svg-iQPsvnWRRgIgPv31{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-iQPsvnWRRgIgPv31 .error-icon{fill:#552222;}#mermaid-svg-iQPsvnWRRgIgPv31 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-iQPsvnWRRgIgPv31 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-iQPsvnWRRgIgPv31 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-iQPsvnWRRgIgPv31 .marker.cross{stroke:#333333;}#mermaid-svg-iQPsvnWRRgIgPv31 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-iQPsvnWRRgIgPv31 p{margin:0;}#mermaid-svg-iQPsvnWRRgIgPv31 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 .cluster-label text{fill:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 .cluster-label span{color:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 .cluster-label span p{background-color:transparent;}#mermaid-svg-iQPsvnWRRgIgPv31 .label text,#mermaid-svg-iQPsvnWRRgIgPv31 span{fill:#333;color:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 .node rect,#mermaid-svg-iQPsvnWRRgIgPv31 .node circle,#mermaid-svg-iQPsvnWRRgIgPv31 .node ellipse,#mermaid-svg-iQPsvnWRRgIgPv31 .node polygon,#mermaid-svg-iQPsvnWRRgIgPv31 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-iQPsvnWRRgIgPv31 .rough-node .label text,#mermaid-svg-iQPsvnWRRgIgPv31 .node .label text,#mermaid-svg-iQPsvnWRRgIgPv31 .image-shape .label,#mermaid-svg-iQPsvnWRRgIgPv31 .icon-shape .label{text-anchor:middle;}#mermaid-svg-iQPsvnWRRgIgPv31 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-iQPsvnWRRgIgPv31 .rough-node .label,#mermaid-svg-iQPsvnWRRgIgPv31 .node .label,#mermaid-svg-iQPsvnWRRgIgPv31 .image-shape .label,#mermaid-svg-iQPsvnWRRgIgPv31 .icon-shape .label{text-align:center;}#mermaid-svg-iQPsvnWRRgIgPv31 .node.clickable{cursor:pointer;}#mermaid-svg-iQPsvnWRRgIgPv31 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-iQPsvnWRRgIgPv31 .arrowheadPath{fill:#333333;}#mermaid-svg-iQPsvnWRRgIgPv31 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-iQPsvnWRRgIgPv31 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-iQPsvnWRRgIgPv31 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-iQPsvnWRRgIgPv31 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-iQPsvnWRRgIgPv31 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-iQPsvnWRRgIgPv31 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-iQPsvnWRRgIgPv31 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-iQPsvnWRRgIgPv31 .cluster text{fill:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 .cluster span{color:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-iQPsvnWRRgIgPv31 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-iQPsvnWRRgIgPv31 rect.text{fill:none;stroke-width:0;}#mermaid-svg-iQPsvnWRRgIgPv31 .icon-shape,#mermaid-svg-iQPsvnWRRgIgPv31 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-iQPsvnWRRgIgPv31 .icon-shape p,#mermaid-svg-iQPsvnWRRgIgPv31 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-iQPsvnWRRgIgPv31 .icon-shape .label rect,#mermaid-svg-iQPsvnWRRgIgPv31 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-iQPsvnWRRgIgPv31 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-iQPsvnWRRgIgPv31 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-iQPsvnWRRgIgPv31 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是
否
模型请求加载 Skill
SkillTool.execute:读取 name
skillService.get:按名称与 cwd 查找
找到定义
正文包装成 TextBlock
返回 SKILL_NOT_FOUND
结果进入后续模型请求
模型决定后续动作,实际工具另行执行

这里省略了缺少 name 的参数错误分支。查到规范后得到的是文本说明,查询接口和文件写入仍走各自工具。

正文返回的关键代码如下:

java 复制代码
SkillDefinition skill = def.get();
String body = "<skill name=\"" + skill.name() + "\" source=\"" + skill.source()
        + "\" path=\"" + skill.path().orElse("") + "\">\n"
        + skill.content()
        + "\n</skill>\nFollow the skill instructions above for the remainder of this task.";
List<ContentBlock> content = List.of(new TextBlock(body));
return CompletableFuture.completedFuture(ToolExecutionResult.ok(content));

这里没有直接执行一套 Java 规则。加载结果成为工具观察值,后续由模型按说明选择动作。说明是否被压缩保留、是否与其他提示冲突,也进入了第 03 篇的上下文问题。

操作规范和权限还要分别处理。Skill 可以要求"把结论写进报告",最终文件动作仍要走执行器和沙箱。配置说明里写一句允许访问目录,无法自动替换实际执行环境的限制。

同样,"报告必须包含两份材料来源"写在 Skill 中,表达的是工作要求。若来源缺失必须判失败,还需要程序检查最终产物。规范适合帮助模型组织工作,必填字段、金额计算和提交条件等确定性规则,可以继续由业务服务或校验代码执行。把操作经验整理进 Skill,有助于传递方法;并不意味着企业原有规则都应改成提示词。

MCP 的发现与调用

MCP 的工具协议定义了 tools/list 和 tools/call,工具带名称、描述和输入 schema,结果里可以有文本、图像及错误标记。协议也提醒客户端,工具注解的可信度取决于来源。MCP Tools 规范

宿主维护服务的连接句柄、工具描述和调用桥。工具描述进入模型请求,调用桥进入注册表。模型选中工具后,执行器沿注册表找到桥,桥再把请求发到 MCP 服务。结果转回统一工具类型,循环继续。
工具执行器 工具注册表 MCP 服务 MCP 连接管理 工具执行器 工具注册表 MCP 服务 MCP 连接管理 #mermaid-svg-Exg3RgWRw3j48PCb{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-Exg3RgWRw3j48PCb .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-Exg3RgWRw3j48PCb .error-icon{fill:#552222;}#mermaid-svg-Exg3RgWRw3j48PCb .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-Exg3RgWRw3j48PCb .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-Exg3RgWRw3j48PCb .marker{fill:#333333;stroke:#333333;}#mermaid-svg-Exg3RgWRw3j48PCb .marker.cross{stroke:#333333;}#mermaid-svg-Exg3RgWRw3j48PCb svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-Exg3RgWRw3j48PCb p{margin:0;}#mermaid-svg-Exg3RgWRw3j48PCb .actor{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-Exg3RgWRw3j48PCb text.actor>tspan{fill:black;stroke:none;}#mermaid-svg-Exg3RgWRw3j48PCb .actor-line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-Exg3RgWRw3j48PCb .innerArc{stroke-width:1.5;stroke-dasharray:none;}#mermaid-svg-Exg3RgWRw3j48PCb .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mermaid-svg-Exg3RgWRw3j48PCb .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mermaid-svg-Exg3RgWRw3j48PCb #arrowhead path{fill:#333;stroke:#333;}#mermaid-svg-Exg3RgWRw3j48PCb .sequenceNumber{fill:white;}#mermaid-svg-Exg3RgWRw3j48PCb #sequencenumber{fill:#333;}#mermaid-svg-Exg3RgWRw3j48PCb #crosshead path{fill:#333;stroke:#333;}#mermaid-svg-Exg3RgWRw3j48PCb .messageText{fill:#333;stroke:none;}#mermaid-svg-Exg3RgWRw3j48PCb .labelBox{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-Exg3RgWRw3j48PCb .labelText,#mermaid-svg-Exg3RgWRw3j48PCb .labelText>tspan{fill:black;stroke:none;}#mermaid-svg-Exg3RgWRw3j48PCb .loopText,#mermaid-svg-Exg3RgWRw3j48PCb .loopText>tspan{fill:black;stroke:none;}#mermaid-svg-Exg3RgWRw3j48PCb .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-Exg3RgWRw3j48PCb .note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-Exg3RgWRw3j48PCb .noteText,#mermaid-svg-Exg3RgWRw3j48PCb .noteText>tspan{fill:black;stroke:none;}#mermaid-svg-Exg3RgWRw3j48PCb .activation0{fill:#f4f4f4;stroke:#666;}#mermaid-svg-Exg3RgWRw3j48PCb .activation1{fill:#f4f4f4;stroke:#666;}#mermaid-svg-Exg3RgWRw3j48PCb .activation2{fill:#f4f4f4;stroke:#666;}#mermaid-svg-Exg3RgWRw3j48PCb .actorPopupMenu{position:absolute;}#mermaid-svg-Exg3RgWRw3j48PCb .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mermaid-svg-Exg3RgWRw3j48PCb .actor-man line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-Exg3RgWRw3j48PCb .actor-man circle,#mermaid-svg-Exg3RgWRw3j48PCb line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;stroke-width:2px;}#mermaid-svg-Exg3RgWRw3j48PCb :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 后续调用复用已注册工具 建立连接并请求 tools/list 工具名称、描述和参数规则 注册工具与调用桥 按模型返回的工具名查找 返回工具实现 经调用桥发送 tools/call 返回工具结果 断开时注销该服务的工具 关闭连接

连接成功、发现工具和执行成功是不同阶段。McpRuntime 管理接入生命周期,具体调用由注册的桥转发,不需要每次调用都重新发现工具。

当前 McpRuntime.connect() 会调用 bootstrap 建立连接并注册工具,核对连接是否成功,记录工具数量。断开时则注销工具并移除计数。看见工具列表说明发现阶段成功,实际调用还可能卡在参数、网络、认证或结果解码。

诊断可以分别留一份 tools/list 输出和一份固定参数的调用响应。如果固定参数也失败,改模型提示词通常绕不开连接问题。模型只在参数选择上出错时,才需要回到名称、描述和 schema。

文末 McpBridge 会实际完成 initialize、notifications/initialized、分页 tools/list 和 tools/call,并分别检查普通 JSON 响应与 POST 返回的 SSE。协商后的版本与会话 ID 会继续放进请求头;响应 ID 必须对应当前请求。MCP 生命周期、HTTP 传输

这份本地实现没有独立 GET 订阅和服务端主动请求处理,也没有 Node sidecar。遇到不支持的主动请求或非文本结果会明确报错,不能把"连通一个本地测试服务"扩大成"已兼容全部 MCP 能力"。

工具注册与关闭句柄

插件工具进宿主时,SpringPluginContext.registerTool() 会做包装和登记。下面截出注册后的部分:

java 复制代码
Runnable disposer = toolRegistry.register(adapted);
String qualifiedName = adapted.name();
AutoCloseable registration =
        new PluginToolRegistration(qualifiedName, disposer::run);
registrations.add(registration);
return registration;

register() 把工具放进注册表,并返回一个撤销动作。PluginToolRegistration 把名称和撤销动作一起保存,Context 再登记到 registrations。停用时,Context 根据这份清单注销插件注册的工具。

DeepSeek Harness 的 Cordis 也把注册纳入所属 Context 的可撤销效果:工具、监听器和其他贡献随所属插件释放。业务团队因而可以提供自己的查询能力,宿主继续管理通用循环和生命周期。Java 这里使用显式关闭句柄完成相应工作,资源归属仍要逐项落实。Cordis 注册与释放

工具还会加限定名,例如 plugin__time__now,避免两个插件都注册 now 时互相覆盖。模型调用和实际路由要使用同一个最终名称。

MCP 也有两层名称。例如模型选择 mcp__local__lookup,宿主用前缀定位 local 服务,真正发给服务端的 tools/call.params.name 仍是 lookup。把宿主限定名原样发过去,对端可能返回"未知工具";把前缀完全去掉再存注册表,又可能让两个服务的 lookup 互相覆盖。

系统提示段也用同样思路。插件提供一段说明,Context 保存移除句柄。Hook、订阅、连接等资源都能登记关闭动作。注册时保存对应的注销句柄,停用时就能按资源归属清理,避免遗漏工具、提示段或订阅。

这里返回的"句柄"本质上是一份能执行清理动作的对象。假设插件注册了 plugin__project__number,注册表返回一个删除该条目的动作。Context 把动作保存下来,停用时调用它,注册表就不再接受新的同名查找。

若 configure 注册完工具后又抛异常,没有保存这个动作,界面可能显示启动失败,模型却仍能调用残留工具。文末自检会故意在注册之后抛异常,并核对工具数量回到启动前。

启动、回滚与停用

JavaPluginRuntimeManager.start() 在加载和 configure 期间捕获异常,失败会回滚 Context,并卸载已加载对象。启动、回滚和停用可以放在一张图里对照:
#mermaid-svg-F5ieFRKH54hezWt9{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-F5ieFRKH54hezWt9 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-F5ieFRKH54hezWt9 .error-icon{fill:#552222;}#mermaid-svg-F5ieFRKH54hezWt9 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-F5ieFRKH54hezWt9 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-F5ieFRKH54hezWt9 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-F5ieFRKH54hezWt9 .marker.cross{stroke:#333333;}#mermaid-svg-F5ieFRKH54hezWt9 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-F5ieFRKH54hezWt9 p{margin:0;}#mermaid-svg-F5ieFRKH54hezWt9 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-F5ieFRKH54hezWt9 .cluster-label text{fill:#333;}#mermaid-svg-F5ieFRKH54hezWt9 .cluster-label span{color:#333;}#mermaid-svg-F5ieFRKH54hezWt9 .cluster-label span p{background-color:transparent;}#mermaid-svg-F5ieFRKH54hezWt9 .label text,#mermaid-svg-F5ieFRKH54hezWt9 span{fill:#333;color:#333;}#mermaid-svg-F5ieFRKH54hezWt9 .node rect,#mermaid-svg-F5ieFRKH54hezWt9 .node circle,#mermaid-svg-F5ieFRKH54hezWt9 .node ellipse,#mermaid-svg-F5ieFRKH54hezWt9 .node polygon,#mermaid-svg-F5ieFRKH54hezWt9 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-F5ieFRKH54hezWt9 .rough-node .label text,#mermaid-svg-F5ieFRKH54hezWt9 .node .label text,#mermaid-svg-F5ieFRKH54hezWt9 .image-shape .label,#mermaid-svg-F5ieFRKH54hezWt9 .icon-shape .label{text-anchor:middle;}#mermaid-svg-F5ieFRKH54hezWt9 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-F5ieFRKH54hezWt9 .rough-node .label,#mermaid-svg-F5ieFRKH54hezWt9 .node .label,#mermaid-svg-F5ieFRKH54hezWt9 .image-shape .label,#mermaid-svg-F5ieFRKH54hezWt9 .icon-shape .label{text-align:center;}#mermaid-svg-F5ieFRKH54hezWt9 .node.clickable{cursor:pointer;}#mermaid-svg-F5ieFRKH54hezWt9 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-F5ieFRKH54hezWt9 .arrowheadPath{fill:#333333;}#mermaid-svg-F5ieFRKH54hezWt9 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-F5ieFRKH54hezWt9 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-F5ieFRKH54hezWt9 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-F5ieFRKH54hezWt9 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-F5ieFRKH54hezWt9 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-F5ieFRKH54hezWt9 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-F5ieFRKH54hezWt9 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-F5ieFRKH54hezWt9 .cluster text{fill:#333;}#mermaid-svg-F5ieFRKH54hezWt9 .cluster span{color:#333;}#mermaid-svg-F5ieFRKH54hezWt9 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-F5ieFRKH54hezWt9 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-F5ieFRKH54hezWt9 rect.text{fill:none;stroke-width:0;}#mermaid-svg-F5ieFRKH54hezWt9 .icon-shape,#mermaid-svg-F5ieFRKH54hezWt9 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-F5ieFRKH54hezWt9 .icon-shape p,#mermaid-svg-F5ieFRKH54hezWt9 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-F5ieFRKH54hezWt9 .icon-shape .label rect,#mermaid-svg-F5ieFRKH54hezWt9 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-F5ieFRKH54hezWt9 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-F5ieFRKH54hezWt9 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-F5ieFRKH54hezWt9 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是
否
加载或配置异常
stop 或热重载
start:创建 SpringPluginContext
加载插件并执行 configure
登记工具、提示段与释放句柄
启动是否完成
登记运行实例,插件进入 ACTIVE
关闭 Context,回滚已登记资源
关闭 Context,逆序释放登记项
卸载已加载对象与类加载资源

图展示新插件正常启动、失败回滚和停用的主要路径,省略重复启动处理。只有 Context 已登记的资源才会进入它的清理清单。

Context 的关闭循环如下:

java 复制代码
Exception firstFailure = null;
for (int index = ordered.size() - 1; index >= 0; index--) {
    try {
        ordered.get(index).close();
    } catch (Exception e) {
        if (firstFailure == null) firstFailure = e;
    }
}
if (firstFailure != null) {
    throw firstFailure;
}

这是原方法的关闭循环。逆序释放可以照顾依赖次序,比如后注册的工具可能用到前面建立的连接。某个关闭动作失败,程序仍尝试释放其余项,最后再抛出记录的错误。

例如插件为查询服务打开连接,又注册了工具;工具注册失败时,连接也应关闭。反过来,停用插件可能是因为查询能力需要下线,除了撤掉新调用入口,还要处理已经开始的调用。Context 只能清理登记过的资源,插件自建的线程或连接需要主动登记释放动作。

URLClassLoader 帮助加载插件类和依赖,资源回收和权限隔离还要另看。插件在宿主 JVM 里能调用哪些 Java API,取决于整个进程获得的权限。类加载器关闭之后,如果某个线程还持有插件对象,相关资源也可能继续占着。

🧭 拓展

插件 SPI 的参数类型也必须由宿主与插件共同识别。文末 JAR 入口只把 public 的 Capabilities.Plugin、Scope、TextAction 暴露给插件,用字符串传参数。插件不直接依赖宿主的包私有记录类型。类名相同但加载器或可见性不合适,仍可能在运行时出现访问错误;只在宿主里 new 一个插件对象,测不到这个问题。

热重载还多出"旧调用正在跑"的时间窗口。工具从注册表撤掉,能阻止新的查找,已有调用是否继续需要按执行方式确定。停用验收不能只看状态标签变成 stopped。

Node Bridge

Node 插件通过独立 sidecar 通信。宿主使用 stdin/stdout 传 JSON-RPC,一旦脚本顺手向 stdout 打一行普通调试文字,协议解析就可能被污染。诊断日志应走 stderr,协议数据单独保留。

进程活着、工具可发现、调用能返回、停用能退出,是四个观察点。调用中断连时,执行器应生成能沿调用 ID 查到的错误。若动作已写远端,恢复连接后的重试还要核对业务状态。

sidecar 使用独立进程,文件访问、网络权限和资源限额仍需单独配置。运行身份、启动参数、挂载目录和输出上限决定了它的访问范围与资源开销。

工具接口兼容

字段从 projectId 改为 projectCode,Java 编译可以通过,旧会话里还可能留着早先的工具调用。读历史、压缩、重新执行或重试时,宿主需要决定旧参数是否仍受支持。保留兼容入口或使用新的工具名,都比静默改语义容易排查。

工具说明变化也会改变模型选择。一次插件升级若同时改了工具名、字段和提示词,失败归因会变难。第 07 篇会用固定任务分别量测协议兼容和模型行为变化。

报告场景可以由 Java 插件查内部编号,Skill 提供报告规范,MCP 服务负责外部检索。它们的结果都回到同一份会话。若查询和核对需要不同的上下文或运行身份,就需要设计独立的任务执行与结果交接。

扩展调用链

假设新增一份名为 report-spec 的报告规范,同时接入查询编号的 Java 插件。两者最终都会返回工具结果,但结果产生的方式不同。

在 SkillTool.execute() 中,参数里的 name 用来查规范定义。原方法的入口判断是:

java 复制代码
Map<String, Object> argMap = args instanceof Map ? (Map<String, Object>) args : Map.of();
String name = argMap.get("name") == null ? "" : String.valueOf(argMap.get("name")).trim();
if (name.isEmpty()) {
    return CompletableFuture.completedFuture(
            ToolExecutionResult.fail("name parameter is required", "MISSING_PARAM"));
}

第一行尝试按键值表读取参数,第二行取出 name 并清理两侧空白。缺少名称会直接返回一个已经完成的失败结果,不会继续查找规范。CompletableFuture.completedFuture() 在这里没有启动后台工作,只是把现成结果放进统一的异步返回类型。

名称有效时,代码调用 skillService.get(name, cwd),找到的正文被包装成 TextBlock。这一条路径交付的是说明文字。后续查询编号、写报告,仍要由模型选择其他工具完成。调试"规范加载了但报告没生成",就要看规范返回之后的模型请求和工具选择。

Java 插件的入口则在 SpringPluginContext.registerTool()。它把插件提供的 ToolDefinition 包装为宿主可用的工具,交给 toolRegistry.register();注册表保存了实际能力,模型请求里的工具列表保存了能力描述。出现"模型能看见工具但调用失败",需要对照这两处最终名称是否一致。

停用时可以继续追 JavaPluginRuntimeManager 到 Context 的 close():注册时收集的关闭句柄会被逆序调用。若只删工具描述,注册表或连接仍可能留着;若插件自己创建的线程没有登记清理,Context 也不会凭空知道它存在。注册和释放必须能对应起来。

MCP 接入的工具则从 McpRuntime.connect() 注册、从 disconnect() 注销。调用失败时分两段查:连接后能否列出工具,以及固定参数能否调用成功。规范加载、工具注册、远程调用和资源释放,在源码中各有入口,故障也应当落到对应位置。

完整代码

已有注册表继续使用,只新增扩展入口。自检真实编译一个插件 JAR,检查失败回滚和资源清理;MCP 服务在本地启动,完成握手、发现、调用和会话关闭。

阶段目录:lab/chapters/05。下列文件各自完整,按相对路径保存到同一目录即可编译。

运行

bash 复制代码
cd lab/chapters/05
bash run.sh --check
bash run.sh

本机自检结果:PASS chapter-05: 39 checks。检查为累计范围,包含前面阶段的关键行为。

写入需要显式批准,例如:

bash 复制代码
bash run.sh --allow-write 'call:fs_write:{"path":"report.md","text":"项目编号 HARNESS-42"}'

加载规范可用 bash run.sh 'call:plugin__skills__load:{"name":"report-spec"}'。它只返回说明,不会自行写报告。

🧪 本地测试

默认使用进程内 FixtureModel,不访问真实模型。设置 LLM_BASE_URL、LLM_DEFAULT_MODEL、LLM_API_KEY 后,普通运行切换到 ChatAdapter;--check 仍使用本机固定响应。

文件

文件 用途
src/main/java/MiniAgent.java 本章入口
src/main/java/Harness.java 沿用的完整文件
src/main/java/ChatAdapter.java 沿用的完整文件
src/main/java/FileHistory.java 沿用的完整文件
src/main/java/ContextView.java 沿用的完整文件
src/main/java/ClientView.java 沿用的完整文件
src/main/java/ToolRuntime.java 沿用的完整文件
src/main/java/Capabilities.java 本章新增或修改
src/main/java/McpBridge.java 本章新增或修改
src/main/java/LocalTools.java 沿用的完整文件
src/main/java/FixtureModel.java 沿用的完整文件
src/main/java/Checks.java 本地自检
pom.xml 沿用的完整文件
run.sh 沿用的完整文件

代码

新增文件、沿用文件和自检文件分别标明,下面保留全部代码。

src/main/java/MiniAgent.java

入口把模型、历史与工具接起来。观察 try-with-resources 中换了哪个实现,能对照出本章增加的运行规则。

java 复制代码
import java.nio.file.*;
import java.util.*;

public final class MiniAgent {
    public static void main(String[] args) throws Exception {
        List<String> flags = Arrays.asList(args);
        if (flags.contains("--check")) {
            Checks.run();
            return;
        }
        Path root = Path.of("workspace").toAbsolutePath();
        Files.createDirectories(root);
        if (!Files.exists(root.resolve("brief.txt")))
            Files.writeString(root.resolve("brief.txt"), "项目编号 HARNESS-42");
        String question =
                flags.stream()
                        .filter(value -> !value.startsWith("--"))
                        .findFirst()
                        .orElse("read:brief.txt");
        try (Resources resources = resources(root, flags.contains("--allow-write"));
                History history = new FileHistory(Path.of("data/session.jsonl"), 12_000)) {
            System.out.println(
                    new Harness(model(), history, resources.tools, new ClientView()).run(question));
        }
    }

    static Model model() {
        String base = System.getenv("LLM_BASE_URL");
        if (base == null || base.isBlank()) return new FixtureModel();
        String model = System.getenv().getOrDefault("LLM_DEFAULT_MODEL", "deepseek-chat");
        String key = System.getenv().getOrDefault("LLM_API_KEY", "");
        if (key.isBlank()) throw new IllegalArgumentException("真实渠道必须提供 LLM_API_KEY");
        return new ChatAdapter(base, model, key);
    }

    static final class Resources implements AutoCloseable {
        final ToolRuntime tools;
        final Capabilities capabilities;

        Resources(Path root, boolean allowWrite) throws Exception {
            Files.createDirectories(root);
            tools = new ToolRuntime(call -> !call.name().equals("fs_write") || allowWrite, 2000);
            tools.registerFiles(root);
            capabilities = new Capabilities(tools);
            Path skill = root.resolve("skills/report-spec");
            Files.createDirectories(skill);
            if (!Files.exists(skill.resolve("SKILL.md")))
                Files.writeString(skill.resolve("SKILL.md"), "报告必须包含项目编号、两份材料来源和不一致项。");
            capabilities.registerSkills(root.resolve("skills"));
            capabilities.start(
                    "project",
                    scope ->
                            scope.registerText(
                                    "number",
                                    "返回测试项目编号",
                                    "{\"type\":\"object\"}",
                                    true,
                                    json -> "HARNESS-42"));
        }

        public void close() throws Exception {
            try {
                capabilities.close();
            } finally {
                tools.close();
            }
        }
    }

    static Resources resources(Path root, boolean allowWrite) throws Exception {
        return new Resources(root, allowWrite);
    }
}

沿用文件:src/main/java/Harness.java

Model、History、Tools 是三个替换点。run() 追加用户消息,保存 assistant 调用,核对工具结果数量与 ID,再进入下一次模型请求。未确认的旧调用只补成 UNKNOWN_OUTCOME,不会自动重放。

java 复制代码
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.*;
import java.util.function.Consumer;

// 内部类型不依赖某一家模型的字段名,HTTP 转换集中在 ChatAdapter。
sealed interface Content permits TextBlock, ImageBlock {}

record TextBlock(String text) implements Content {}

record ImageBlock(String url) implements Content {}

record Call(String id, String name, ObjectNode args) {}

record Message(
        String role, List<Content> content, String reasoning, List<Call> calls, String callId) {
    Message {
        content = List.copyOf(content);
        calls = List.copyOf(calls);
    }

    static Message user(String text) {
        return new Message("user", List.of(new TextBlock(text)), "", List.of(), "");
    }

    static Message answer(String text) {
        return new Message("assistant", List.of(new TextBlock(text)), "", List.of(), "");
    }

    String text() {
        StringBuilder result = new StringBuilder();
        for (Content item : content) {
            if (item instanceof TextBlock text) result.append(text.text());
        }
        return result.toString();
    }
}

record Reply(Message message, String finish) {}

record ToolSpec(String name, String description, ObjectNode schema) {}

record ToolResult(String callId, boolean error, List<Content> content) {
    static ToolResult text(String id, boolean error, String text) {
        return new ToolResult(id, error, List.of(new TextBlock(text)));
    }

    Message message() {
        return new Message("tool", content, "", List.of(), callId);
    }
}

record RunEvent(String type, String callId, String text, boolean error) {
    RunEvent(String type, String callId, String text) {
        this(type, callId, text, false);
    }
}

interface Model {
    Reply next(List<Message> messages, List<ToolSpec> tools) throws Exception;
}

interface History extends AutoCloseable {
    void append(Message message) throws Exception;

    List<Message> messages();

    default List<Message> forModel() {
        return messages();
    }

    default void close() throws Exception {}
}

final class MemoryHistory implements History {
    private final List<Message> messages = new ArrayList<>();

    public void append(Message message) {
        messages.add(message);
    }

    public List<Message> messages() {
        return List.copyOf(messages);
    }
}

interface Tools extends AutoCloseable {
    List<ToolSpec> specs();

    List<ToolResult> execute(List<Call> calls) throws Exception;

    default void close() throws Exception {}
}

public final class Harness {
    private final Model model;
    private final History history;
    private final Tools tools;
    private final Consumer<RunEvent> events;

    public Harness(Model model, History history, Tools tools, Consumer<RunEvent> events) {
        this.model = model;
        this.history = history;
        this.tools = tools;
        this.events = events;
    }

    public String run(String question) throws Exception {
        // 断在工具执行与结果落库之间时,恢复只能确认"未知",不能猜成功。
        recoverPending();
        history.append(Message.user(question));
        for (int step = 1; step <= 8; step++) {
            events.accept(new RunEvent("step", "", "step=" + step));
            Reply reply = model.next(history.forModel(), tools.specs());
            if (!"assistant".equals(reply.message().role())) {
                throw new IllegalStateException("模型返回的角色不是 assistant");
            }
            // 截断或错误时不能拿半份参数执行工具。
            if (!Set.of("stop", "tool_calls").contains(reply.finish())) {
                throw new IllegalStateException("MODEL_FINISH: " + reply.finish());
            }
            Message assistant = reply.message();
            Set<String> ids = new HashSet<>();
            for (Call call : assistant.calls()) {
                if (call.id().isBlank() || !ids.add(call.id())) {
                    throw new IllegalStateException("调用 ID 缺失或重复");
                }
            }
            // assistant 的调用必须排在 tool 结果之前,上游靠调用 ID 配对。
            history.append(assistant);
            if (assistant.calls().isEmpty()) {
                if (assistant.text().isBlank()) throw new IllegalStateException("模型返回空答案");
                return assistant.text();
            }
            for (Call call : assistant.calls()) {
                events.accept(new RunEvent("tool_start", call.id(), call.name()));
            }
            List<ToolResult> results = tools.execute(assistant.calls());
            if (results.size() != assistant.calls().size()) {
                throw new IllegalStateException("工具结果数量与调用不一致");
            }
            for (int i = 0; i < results.size(); i++) {
                ToolResult result = results.get(i);
                if (!result.callId().equals(assistant.calls().get(i).id())) {
                    throw new IllegalStateException("工具结果顺序或 ID 不匹配");
                }
                history.append(result.message());
                events.accept(
                        new RunEvent(
                                "tool_result",
                                result.callId(),
                                result.message().text(),
                                result.error()));
            }
            // 下一步重新从 History 构造请求,不需要用户再输入"继续"。
        }
        throw new IllegalStateException("MAX_STEPS: 超过 8 步");
    }

    private void recoverPending() throws Exception {
        // 只补齐未确认结果,不重放旧工具;写操作可能已在进程退出前发生。
        Map<String, Call> pending = new LinkedHashMap<>();
        for (Message message : history.messages()) {
            for (Call call : message.calls()) pending.put(call.id(), call);
            if ("tool".equals(message.role())) pending.remove(message.callId());
        }
        for (Call call : pending.values()) {
            history.append(
                    ToolResult.text(call.id(), true, "UNKNOWN_OUTCOME: 上次执行中断,核对外部状态后决定是否重试")
                            .message());
        }
    }
}

沿用文件:src/main/java/ChatAdapter.java

encode() 把内部消息变成出站字段,decode() 从响应中恢复调用。CallAssembler 单独检查交错分片和结束原因;实际 HTTP 路径仍为非流式,不把组装器测试扩大成网络 SSE 已接入。

java 复制代码
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;

import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;

public final class ChatAdapter implements Model {
    static final ObjectMapper JSON = new ObjectMapper();
    private final URI endpoint;
    private final String model;
    private final String key;
    private final HttpClient client =
            HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();

    public ChatAdapter(String base, String model, String key) {
        this.endpoint = URI.create(base.replaceAll("/+$", "") + "/chat/completions");
        this.model = model;
        this.key = key;
    }

    public Reply next(List<Message> messages, List<ToolSpec> tools) throws Exception {
        ObjectNode body = encode(messages, tools);
        body.put("model", model).put("stream", false);
        HttpRequest request =
                HttpRequest.newBuilder(endpoint)
                        .timeout(Duration.ofSeconds(30))
                        .header("Content-Type", "application/json")
                        .header("Authorization", "Bearer " + key)
                        .POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)))
                        .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() / 100 != 2) {
            throw new IllegalStateException("MODEL_HTTP_" + response.statusCode());
        }
        return decode(JSON.readTree(response.body()));
    }

    static ObjectNode encode(List<Message> messages, List<ToolSpec> specs) {
        ObjectNode root = JSON.createObjectNode();
        ArrayNode array = root.putArray("messages");
        // 这是出站边界:内部对象中存在,不代表 JSON 中已经有对应字段。
        for (Message message : messages) {
            ObjectNode item = array.addObject().put("role", message.role());
            StringBuilder text = new StringBuilder();
            for (Content content : message.content()) {
                if (content instanceof TextBlock block) text.append(block.text());
                // 未支持的类型明确报错,不能悄悄丢掉图片后继续请求。
                else throw new IllegalArgumentException("UNSUPPORTED_CONTENT: 本地适配器仅支持文本");
            }
            item.put("content", text.toString());
            if (!message.reasoning().isBlank()) item.put("reasoning_content", message.reasoning());
            if ("tool".equals(message.role())) item.put("tool_call_id", message.callId());
            if (!message.calls().isEmpty()) {
                ArrayNode calls = item.putArray("tool_calls");
                for (Call call : message.calls()) {
                    ObjectNode node =
                            calls.addObject().put("id", call.id()).put("type", "function");
                    node.putObject("function")
                            .put("name", call.name())
                            .put("arguments", call.args().toString());
                }
            }
        }
        ArrayNode tools = root.putArray("tools");
        for (ToolSpec spec : specs) {
            ObjectNode node = tools.addObject().put("type", "function");
            node.putObject("function")
                    .put("name", spec.name())
                    .put("description", spec.description())
                    .set("parameters", spec.schema());
        }
        return root;
    }

    static Reply decode(JsonNode response) throws Exception {
        JsonNode choice = response.path("choices").path(0);
        JsonNode message = choice.path("message");
        if (!"assistant".equals(message.path("role").asText())) {
            throw new IllegalArgumentException("BAD_RESPONSE: 缺少 assistant");
        }
        List<Call> calls = new ArrayList<>();
        for (JsonNode call : message.path("tool_calls")) {
            JsonNode function = call.path("function");
            JsonNode args = JSON.readTree(function.path("arguments").asText("{}"));
            if (args == null || !args.isObject())
                throw new IllegalArgumentException("参数必须为 JSON 对象");
            calls.add(
                    new Call(
                            call.path("id").asText(),
                            function.path("name").asText(),
                            (ObjectNode) args));
        }
        return new Reply(
                new Message(
                        "assistant",
                        List.of(new TextBlock(message.path("content").asText(""))),
                        message.path("reasoning_content").asText(""),
                        calls,
                        ""),
                choice.path("finish_reason").asText());
    }

    // SSE 网络读取尚未接入;此组装器用于固定分片的本地测试。
    static final class CallAssembler {
        // 两个工具的分片可能交错到达,索引不同就写入不同的累计器。
        private final Map<Integer, Partial> pending = new TreeMap<>();

        private static final class Partial {
            String id = "";
            final StringBuilder name = new StringBuilder();
            final StringBuilder args = new StringBuilder();
        }

        void accept(JsonNode delta) {
            for (JsonNode call : delta.path("tool_calls")) {
                if (!call.path("index").isInt() || call.path("index").asInt() < 0)
                    throw new IllegalArgumentException("调用索引必须是非负整数");
                Partial part =
                        pending.computeIfAbsent(
                                call.path("index").asInt(), ignored -> new Partial());
                if (call.hasNonNull("id")) {
                    String id = call.path("id").asText();
                    if (!part.id.isEmpty() && !part.id.equals(id))
                        throw new IllegalArgumentException("同一索引出现不同调用 ID");
                    part.id = id;
                }
                part.name.append(call.path("function").path("name").asText(""));
                part.args.append(call.path("function").path("arguments").asText(""));
            }
        }

        List<Call> finish(String reason) throws Exception {
            if (!"tool_calls".equals(reason)) throw new IllegalStateException("调用未完整结束: " + reason);
            List<Call> result = new ArrayList<>();
            for (Partial part : pending.values()) {
                JsonNode args = JSON.readTree(part.args.toString());
                if (part.id.isBlank() || part.name.isEmpty() || args == null || !args.isObject()) {
                    throw new IllegalArgumentException("工具调用不完整");
                }
                result.add(new Call(part.id, part.name.toString(), (ObjectNode) args));
            }
            return List.copyOf(result);
        }
    }
}

沿用文件:src/main/java/FileHistory.java

commit() 写入一个 JSON 行,等待 force 返回,才更新内存视图。重启时按序重建,损坏事件直接报错。Replace 使用显式事件 ID,避免多次压缩后把新序号与旧消息位置混淆。

java 复制代码
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;

import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

public final class FileHistory implements History {
    private record Stamped(long seq, Message message) {}

    private final List<Stamped> view = new ArrayList<>();
    private final FileChannel channel;
    private final FileLock lock;
    private final int maxChars;
    private long sequence;
    private boolean healthy = true;

    public FileHistory(Path path, int maxChars) throws Exception {
        this.maxChars = maxChars;
        Files.createDirectories(path.toAbsolutePath().getParent());
        channel =
                FileChannel.open(
                        path,
                        StandardOpenOption.CREATE,
                        StandardOpenOption.READ,
                        StandardOpenOption.WRITE);
        FileLock acquired = null;
        try {
            // 同一日志只允许一个本地写入者;它不是跨节点任务认领协议。
            acquired = channel.tryLock();
            if (acquired == null) throw new IllegalStateException("SESSION_BUSY");
            int line = 0;
            for (String record : Files.readAllLines(path, StandardCharsets.UTF_8)) {
                line++;
                if (record.isBlank()) throw new IllegalStateException("空事件行: " + line);
                JsonNode event = ChatAdapter.JSON.readTree(record);
                if (event.path("seq").asLong() != sequence + 1)
                    throw new IllegalStateException("事件序号不连续: " + line);
                apply(event);
                sequence++;
            }
            lock = acquired;
        } catch (Exception error) {
            if (acquired != null) acquired.release();
            channel.close();
            throw error;
        }
    }

    public synchronized void append(Message message) throws Exception {
        ObjectNode event =
                ChatAdapter.JSON.createObjectNode().put("seq", sequence + 1).put("op", "append");
        event.set("message", encode(message));
        commit(event);
    }

    public synchronized List<Message> messages() {
        return view.stream().map(Stamped::message).toList();
    }

    public synchronized List<Message> forModel() {
        return ContextView.trim(messages(), maxChars);
    }

    public synchronized void compactPrefix(int keepLastGroups, String summary) throws Exception {
        if (keepLastGroups < 1 || summary.isBlank())
            throw new IllegalArgumentException("需要保留组数和非空摘要");
        List<List<Message>> groups = ContextView.groups(messages());
        int removeCount =
                groups.subList(0, Math.max(0, groups.size() - keepLastGroups)).stream()
                        .mapToInt(List::size)
                        .sum();
        if (removeCount == 0) return;
        ObjectNode event =
                ChatAdapter.JSON.createObjectNode().put("seq", sequence + 1).put("op", "replace");
        // 显式记录被替换的事件 ID,多次压缩后也不用猜旧区间的位置。
        ArrayNode removed = event.putArray("remove");
        for (Stamped item : view.subList(0, removeCount)) removed.add(item.seq());
        event.set(
                "message",
                encode(new Message("system", List.of(new TextBlock(summary)), "", List.of(), "")));
        commit(event);
    }

    private void commit(ObjectNode event) throws Exception {
        if (!healthy) throw new IllegalStateException("会话写入失败后禁止继续追加");
        try {
            byte[] data = (event.toString() + "\n").getBytes(StandardCharsets.UTF_8);
            // 每次追加一个完整 JSON 行;失败后封住写入口,保留损坏现场。
            channel.position(channel.size());
            ByteBuffer buffer = ByteBuffer.wrap(data);
            while (buffer.hasRemaining()) channel.write(buffer);
            channel.force(true); // 本地版本同步确认后,才更新内存并返回。
            apply(event);
            sequence++;
        } catch (Exception error) {
            healthy = false;
            throw error;
        }
    }

    private void apply(JsonNode event) throws Exception {
        Message message = decode(event.path("message"));
        Stamped stamped = new Stamped(event.path("seq").asLong(), message);
        if ("append".equals(event.path("op").asText())) view.add(stamped);
        else if ("replace".equals(event.path("op").asText())) {
            Set<Long> removed = new HashSet<>();
            for (JsonNode id : event.path("remove")) removed.add(id.asLong());
            if (removed.isEmpty()
                    || !view.stream().map(Stamped::seq).toList().containsAll(removed)) {
                throw new IllegalStateException("替换引用了不存在的事件");
            }
            view.removeIf(item -> removed.contains(item.seq()));
            view.add(0, stamped);
        } else throw new IllegalStateException("未知事件操作");
    }

    static ObjectNode encode(Message message) {
        ObjectNode node =
                ChatAdapter.JSON
                        .createObjectNode()
                        .put("role", message.role())
                        .put("reasoning", message.reasoning())
                        .put("callId", message.callId());
        ArrayNode content = node.putArray("content");
        for (Content block : message.content()) {
            if (block instanceof TextBlock text)
                content.addObject().put("kind", "text").put("value", text.text());
            else if (block instanceof ImageBlock image)
                content.addObject().put("kind", "image").put("value", image.url());
        }
        ArrayNode calls = node.putArray("calls");
        for (Call call : message.calls())
            calls.addObject()
                    .put("id", call.id())
                    .put("name", call.name())
                    .set("args", call.args());
        return node;
    }

    static Message decode(JsonNode node) throws Exception {
        List<Content> content = new ArrayList<>();
        for (JsonNode block : node.path("content")) {
            switch (block.path("kind").asText()) {
                case "text" -> content.add(new TextBlock(block.path("value").asText()));
                case "image" -> content.add(new ImageBlock(block.path("value").asText()));
                default -> throw new IllegalStateException("未知内容块");
            }
        }
        List<Call> calls = new ArrayList<>();
        for (JsonNode call : node.path("calls")) {
            if (!call.path("args").isObject()) throw new IllegalStateException("事件中的参数不是对象");
            calls.add(
                    new Call(
                            call.path("id").asText(),
                            call.path("name").asText(),
                            (ObjectNode) call.path("args")));
        }
        return new Message(
                node.path("role").asText(),
                content,
                node.path("reasoning").asText(),
                calls,
                node.path("callId").asText());
    }

    public synchronized void close() throws Exception {
        try {
            lock.release();
        } finally {
            channel.close();
        }
    }
}

沿用文件:src/main/java/ContextView.java

groups() 把 assistant 调用及其全部结果作为一个整体。trim() 从末尾选择完整组,并保护最新一轮用户输入;最新一轮放不下就报错。这里的预算按字符估算,尚未计入完整模型请求的 Token 成本。

java 复制代码
import java.util.*;

public final class ContextView {
    static List<List<Message>> groups(List<Message> messages) {
        List<List<Message>> result = new ArrayList<>();
        for (int i = 0; i < messages.size(); i++) {
            Message message = messages.get(i);
            if ("tool".equals(message.role()))
                throw new IllegalStateException("ORPHAN_TOOL_RESULT");
            List<Message> group = new ArrayList<>();
            group.add(message);
            if (!message.calls().isEmpty()) {
                Set<String> pending = new HashSet<>();
                for (Call call : message.calls()) {
                    if (!pending.add(call.id()))
                        throw new IllegalStateException("DUPLICATE_CALL_ID");
                }
                // 一条 assistant 调用及其全部 tool 结果作为不可拆分的一组。
                while (!pending.isEmpty()) {
                    if (++i >= messages.size())
                        throw new IllegalStateException("MISSING_TOOL_RESULT");
                    Message tool = messages.get(i);
                    if (!"tool".equals(tool.role()) || !pending.remove(tool.callId())) {
                        throw new IllegalStateException("TOOL_PAIR_MISMATCH");
                    }
                    group.add(tool);
                }
            }
            result.add(List.copyOf(group));
        }
        return result;
    }

    static int size(List<Message> messages) {
        int result = 0;
        for (Message message : messages) {
            result += message.text().length() + message.reasoning().length() + 32;
            for (Call call : message.calls())
                result +=
                        call.id().length() + call.name().length() + call.args().toString().length();
            for (Content content : message.content())
                if (content instanceof ImageBlock image) result += image.url().length();
        }
        return result;
    }

    static List<Message> trim(List<Message> messages, int maxChars) {
        if (maxChars <= 0) throw new IllegalArgumentException("预算必须大于零");
        List<List<Message>> groups = groups(messages);
        int currentTurn = 0;
        for (int i = 0; i < messages.size(); i++) {
            if ("user".equals(messages.get(i).role())) currentTurn = i;
        }
        // 本地以字符数做可观察的预算;这不是模型的精确 Token 计量。
        // 最新一轮放不下就失败,不能把本轮用户要求裁掉后继续执行。
        if (size(messages.subList(currentTurn, messages.size())) > maxChars) {
            throw new IllegalStateException("CURRENT_TURN_TOO_LARGE");
        }
        LinkedList<Message> kept = new LinkedList<>();
        int used = 0;
        for (int i = groups.size() - 1; i >= 0; i--) {
            List<Message> group = groups.get(i);
            int cost = size(group);
            if (used + cost > maxChars) {
                if (kept.isEmpty()) throw new IllegalStateException("LATEST_GROUP_TOO_LARGE");
                break;
            }
            kept.addAll(0, group);
            used += cost;
        }
        return List.copyOf(kept);
    }
}

沿用文件:src/main/java/ClientView.java

工具卡用 callId 作为键。重复或迟到的 start 不覆盖已完成结果;tool_result 根据 error 字段显示 completed 或 failed。它是客户端状态投影,不能代替服务端的执行记录。

java 复制代码
import java.util.*;
import java.util.function.Consumer;

public final class ClientView implements Consumer<RunEvent> {
    private final Map<String, String> cards = new LinkedHashMap<>();

    public synchronized void accept(RunEvent event) {
        if ("tool_start".equals(event.type())) cards.putIfAbsent(event.callId(), "running");
        if ("tool_result".equals(event.type()))
            cards.put(event.callId(), (event.error() ? "failed: " : "completed: ") + event.text());
        System.out.println(event.type() + " " + event.callId() + " " + event.text());
    }

    public synchronized Map<String, String> cards() {
        return Map.copyOf(cards);
    }
}

沿用文件:src/main/java/ToolRuntime.java

register() 保存工具说明与执行函数,返回只释放本次注册的关闭句柄。execute() 按模式分组,串行组形成屏障;group() 管理截止时间并按原顺序返回结果。审批拒绝没有进入实际动作,超时则不保证底层动作已停止。

java 复制代码
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Predicate;

public final class ToolRuntime implements Tools {
    enum Mode {
        PARALLEL,
        SERIAL
    }

    @FunctionalInterface
    interface Action {
        String run(Call call) throws Exception;
    }

    private record Tool(ToolSpec spec, Mode mode, Action action) {}

    private record Timed(ToolResult result, long finishedAt) {}

    private final Map<String, Tool> registry = new LinkedHashMap<>();
    private final ExecutorService workers = Executors.newFixedThreadPool(2);
    private final Predicate<Call> approval;
    private final long timeoutNanos;

    public ToolRuntime(Predicate<Call> approval, long timeoutMillis) {
        if (timeoutMillis <= 0) throw new IllegalArgumentException("超时必须大于零");
        this.approval = approval;
        this.timeoutNanos = TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
    }

    synchronized AutoCloseable register(ToolSpec spec, Mode mode, Action action) {
        if (registry.containsKey(spec.name()))
            throw new IllegalArgumentException("工具重名: " + spec.name());
        Tool tool = new Tool(spec, mode, action);
        registry.put(spec.name(), tool);
        java.util.concurrent.atomic.AtomicBoolean registered =
                new java.util.concurrent.atomic.AtomicBoolean(true);
        return () -> {
            synchronized (this) {
                // 旧句柄重复关闭时,不能删除后来注册的同名工具。
                if (registered.compareAndSet(true, false) && registry.get(spec.name()) == tool) {
                    registry.remove(spec.name());
                }
            }
        };
    }

    public synchronized List<ToolSpec> specs() {
        return registry.values().stream().map(Tool::spec).toList();
    }

    private synchronized Tool lookup(String name) {
        return registry.get(name);
    }

    public List<ToolResult> execute(List<Call> calls) throws Exception {
        List<ToolResult> results = new ArrayList<>();
        int offset = 0;
        while (offset < calls.size()) {
            int end = offset + 1;
            Tool first = lookup(calls.get(offset).name());
            if (first != null && first.mode() == Mode.PARALLEL) {
                while (end < calls.size()) {
                    Tool next = lookup(calls.get(end).name());
                    if (next == null || next.mode() != Mode.PARALLEL) break;
                    end++;
                }
            }
            // 前一组全部形成结果后才派发下一组,SERIAL 写入形成执行屏障。
            results.addAll(group(calls.subList(offset, end)));
            offset = end;
        }
        return List.copyOf(results);
    }

    private List<ToolResult> group(List<Call> calls) throws Exception {
        List<Future<Timed>> futures = new ArrayList<>();
        List<Long> deadlines = new ArrayList<>();
        for (Call call : calls) {
            // 截止时间从提交开始算,线程池排队也消耗这份预算。
            long start = System.nanoTime();
            Tool tool = lookup(call.name());
            ToolResult denied =
                    tool == null
                            ? ToolResult.text(call.id(), true, "UNKNOWN_TOOL")
                            : !approval.test(call)
                                    ? ToolResult.text(call.id(), true, "APPROVAL_DENIED")
                                    : null;
            if (denied != null)
                futures.add(CompletableFuture.completedFuture(new Timed(denied, start)));
            else
                futures.add(
                        workers.submit(
                                () -> {
                                    ToolResult result;
                                    try {
                                        result =
                                                ToolResult.text(
                                                        call.id(), false, tool.action().run(call));
                                    } catch (Exception error) {
                                        result =
                                                ToolResult.text(
                                                        call.id(),
                                                        true,
                                                        "TOOL_ERROR: " + error.getMessage());
                                    }
                                    return new Timed(result, System.nanoTime());
                                }));
            deadlines.add(start + timeoutNanos);
        }
        List<ToolResult> results = new ArrayList<>();
        for (int i = 0; i < calls.size(); i++) {
            Future<Timed> future = futures.get(i);
            try {
                Timed timed =
                        future.isDone()
                                ? future.get()
                                : future.get(
                                        Math.max(1, deadlines.get(i) - System.nanoTime()),
                                        TimeUnit.NANOSECONDS);
                results.add(
                        timed.finishedAt() <= deadlines.get(i)
                                ? timed.result()
                                : ToolResult.text(calls.get(i).id(), true, "TOOL_TIMEOUT"));
            } catch (TimeoutException error) {
                // interrupt 是取消请求,外部写入或忽略中断的代码仍可能继续。
                future.cancel(true);
                results.add(ToolResult.text(calls.get(i).id(), true, "TOOL_TIMEOUT"));
            }
        }
        // 按调用顺序返回;后台完成顺序不会改变工具结果在会话中的顺序。
        return results;
    }

    void registerFiles(Path directory) throws Exception {
        Path root = directory.toRealPath();
        register(
                LocalTools.fileSpec("fs_read", false),
                Mode.PARALLEL,
                call -> {
                    Path target = root.resolve(LocalTools.required(call, "path")).toRealPath();
                    if (!target.startsWith(root) || !Files.isRegularFile(target))
                        throw new IllegalArgumentException("PATH_DENIED");
                    if (Files.size(target) > 65_536)
                        throw new IllegalArgumentException("FILE_TOO_LARGE");
                    return Files.readString(target);
                });
        register(
                LocalTools.fileSpec("fs_write", true),
                Mode.SERIAL,
                call -> {
                    Path target = root.resolve(LocalTools.required(call, "path")).normalize();
                    Path parent = target.getParent().toRealPath();
                    if (!target.startsWith(root) || !parent.startsWith(root))
                        throw new IllegalArgumentException("PATH_DENIED");
                    String text = LocalTools.required(call, "text");
                    if (text.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 65_536)
                        throw new IllegalArgumentException("FILE_TOO_LARGE");
                    // NOFOLLOW_LINKS 只约束最终文件;这不是操作系统级沙箱。
                    Files.writeString(
                            target,
                            text,
                            StandardOpenOption.CREATE,
                            StandardOpenOption.WRITE,
                            StandardOpenOption.TRUNCATE_EXISTING,
                            LinkOption.NOFOLLOW_LINKS);
                    return "written: " + root.relativize(target);
                });
    }

    public void close() throws Exception {
        workers.shutdownNow();
        if (!workers.awaitTermination(3, TimeUnit.SECONDS))
            throw new IllegalStateException("工具线程尚未退出");
    }
}

src/main/java/Capabilities.java

Scope 收集注册与释放动作,configure 抛异常时回滚,停用时逆序清理。JAR 通过 ServiceLoader 提供 public 插件接口;Skill 的名称和首行简介进入工具描述,正文在调用时读取。这里未解析完整 Skill 元数据规范。

java 复制代码
import java.net.URLClassLoader;
import java.nio.file.*;
import java.util.*;

public final class Capabilities implements AutoCloseable {
    @FunctionalInterface
    public interface Plugin {
        void configure(Scope scope) throws Exception;
    }

    @FunctionalInterface
    public interface TextAction {
        String run(String argumentsJson) throws Exception;
    }

    public static final class Scope implements AutoCloseable {
        private final String prefix;
        private final ToolRuntime runtime;
        private final List<AutoCloseable> resources = new ArrayList<>();

        Scope(String name, ToolRuntime runtime) {
            this.prefix = "plugin__" + name + "__";
            this.runtime = runtime;
        }

        public void register(ToolSpec spec, ToolRuntime.Mode mode, ToolRuntime.Action action) {
            ToolSpec qualified =
                    new ToolSpec(prefix + spec.name(), spec.description(), spec.schema());
            resources.add(runtime.register(qualified, mode, action));
        }

        public void own(AutoCloseable resource) {
            resources.add(resource);
        }

        public void registerText(
                String name,
                String description,
                String schemaJson,
                boolean parallel,
                TextAction action)
                throws Exception {
            var schema = ChatAdapter.JSON.readTree(schemaJson);
            if (!schema.isObject()) throw new IllegalArgumentException("schema 必须是对象");
            register(
                    new ToolSpec(
                            name,
                            description,
                            (com.fasterxml.jackson.databind.node.ObjectNode) schema),
                    parallel ? ToolRuntime.Mode.PARALLEL : ToolRuntime.Mode.SERIAL,
                    call -> action.run(call.args().toString()));
        }

        public void close() throws Exception {
            Exception failure = null;
            for (int i = resources.size() - 1; i >= 0; i--) {
                try {
                    resources.get(i).close();
                } catch (Exception error) {
                    if (failure == null) failure = error;
                    else failure.addSuppressed(error);
                }
            }
            resources.clear();
            if (failure != null) throw failure;
        }
    }

    private final ToolRuntime runtime;
    private final Map<String, Scope> active = new LinkedHashMap<>();

    public Capabilities(ToolRuntime runtime) {
        this.runtime = runtime;
    }

    public synchronized void start(String name, Plugin plugin) throws Exception {
        start(name, plugin, null);
    }

    private void start(String name, Plugin plugin, AutoCloseable loader) throws Exception {
        if (!name.matches("[a-zA-Z0-9_-]+") || active.containsKey(name)) {
            if (loader != null) loader.close();
            throw new IllegalArgumentException("插件名非法或已经运行");
        }
        Scope scope = new Scope(name, runtime);
        if (loader != null) scope.own(loader);
        try {
            plugin.configure(scope);
            active.put(name, scope);
        } catch (Exception error) {
            try {
                scope.close();
            } catch (Exception cleanup) {
                error.addSuppressed(cleanup);
            }
            throw error;
        }
    }

    public synchronized void startJar(String name, Path jar) throws Exception {
        URLClassLoader loader =
                new URLClassLoader(
                        new java.net.URL[] {jar.toUri().toURL()}, Plugin.class.getClassLoader());
        Plugin plugin;
        try {
            plugin =
                    ServiceLoader.load(Plugin.class, loader)
                            .findFirst()
                            .orElseThrow(() -> new IllegalArgumentException("JAR 未声明 Plugin 服务实现"));
        } catch (Throwable error) {
            loader.close();
            throw error;
        }
        start(name, plugin, loader);
    }

    public synchronized void stop(String name) throws Exception {
        Scope scope = active.remove(name);
        if (scope != null) scope.close();
    }

    public void registerSkills(Path directory) throws Exception {
        Path root = directory.toRealPath();
        List<String> catalog = new ArrayList<>();
        try (var directories = Files.list(root)) {
            for (Path child : directories.sorted().toList()) {
                if (!Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) continue;
                Path file = child.resolve("SKILL.md");
                if (!Files.isRegularFile(file) || !file.toRealPath().startsWith(root)) continue;
                try (var text = Files.newBufferedReader(file)) {
                    String description = text.readLine();
                    catalog.add(
                            child.getFileName()
                                    + ": "
                                    + (description == null
                                            ? ""
                                            : description.substring(
                                                    0, Math.min(160, description.length()))));
                }
            }
        }
        start(
                "skills",
                scope -> {
                    var schema = ChatAdapter.JSON.createObjectNode().put("type", "object");
                    schema.putObject("properties").putObject("name").put("type", "string");
                    schema.putArray("required").add("name");
                    scope.register(
                            new ToolSpec(
                                    "load",
                                    "按需加载规范,可用名称与简介: " + String.join("; ", catalog),
                                    schema),
                            ToolRuntime.Mode.PARALLEL,
                            call -> {
                                String name = LocalTools.required(call, "name");
                                if (!name.matches("[a-zA-Z0-9_-]+"))
                                    throw new IllegalArgumentException("INVALID_SKILL_NAME");
                                Path path = root.resolve(name).resolve("SKILL.md").toRealPath();
                                if (!path.startsWith(root) || Files.size(path) > 65_536)
                                    throw new IllegalArgumentException("INVALID_SKILL_PATH");
                                return "<skill name=\""
                                        + name
                                        + "\">\n"
                                        + Files.readString(path)
                                        + "\n</skill>";
                            });
                });
    }

    public synchronized void close() throws Exception {
        Exception failure = null;
        List<String> names = new ArrayList<>(active.keySet());
        Collections.reverse(names);
        for (String name : names) {
            try {
                stop(name);
            } catch (Exception error) {
                if (failure == null) failure = error;
                else failure.addSuppressed(error);
            }
        }
        if (failure != null) throw failure;
    }
}

src/main/java/McpBridge.java

连接阶段进行版本协商、初始化通知和工具发现。调用桥还原对端工具名,保留请求与响应 ID,检查 JSON 和 POST SSE 两类响应。没有独立 GET 订阅、服务端主动请求处理或 Node sidecar。

java 复制代码
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;

import java.io.*;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;

// 支持请求响应式 Streamable HTTP;不建立独立 GET 订阅,也不声明 sampling 等能力。
public final class McpBridge implements AutoCloseable {
    private static final String VERSION = "2025-06-18";
    private final URI endpoint;
    private final HttpClient client =
            HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
    private final ExecutorService reader =
            Executors.newSingleThreadExecutor(
                    task -> {
                        Thread thread = new Thread(task, "mcp-response-reader");
                        thread.setDaemon(true);
                        return thread;
                    });
    private final List<AutoCloseable> registrations = new ArrayList<>();
    private String sessionId = "";
    private long requestId;
    private boolean initialized;

    public McpBridge(URI endpoint) {
        this.endpoint = endpoint;
    }

    public void connect(ToolRuntime runtime, String serverName) throws Exception {
        if (!serverName.matches("[a-zA-Z0-9_-]+") || initialized)
            throw new IllegalArgumentException("无效连接状态");
        try {
            ObjectNode params = ChatAdapter.JSON.createObjectNode().put("protocolVersion", VERSION);
            params.putObject("capabilities");
            params.putObject("clientInfo").put("name", "notes-harness").put("version", "1.0");
            JsonNode hello = rpc("initialize", params);
            if (!VERSION.equals(hello.path("protocolVersion").asText())
                    || !hello.path("capabilities").has("tools")) {
                throw new IllegalStateException("MCP 协议版本或工具能力不匹配");
            }
            // initialize 响应通过后,通知服务端进入操作阶段。
            initialized = true;
            ObjectNode notification =
                    ChatAdapter.JSON
                            .createObjectNode()
                            .put("jsonrpc", "2.0")
                            .put("method", "notifications/initialized");
            HttpResponse<InputStream> ack = post(notification);
            try (InputStream ignored = ack.body()) {
                if (ack.statusCode() != 202) throw new IllegalStateException("MCP 初始化通知未接受");
            }
            String cursor = "";
            Set<String> seen = new HashSet<>();
            do {
                ObjectNode listParams = ChatAdapter.JSON.createObjectNode();
                if (!cursor.isEmpty()) listParams.put("cursor", cursor);
                JsonNode page = rpc("tools/list", listParams);
                for (JsonNode tool : page.path("tools")) {
                    String remote = tool.path("name").asText();
                    if (remote.isBlank() || !tool.path("inputSchema").isObject())
                        throw new IllegalArgumentException("MCP 工具定义无效");
                    ToolSpec spec =
                            new ToolSpec(
                                    "mcp__" + serverName + "__" + remote,
                                    tool.path("description").asText(),
                                    (ObjectNode) tool.path("inputSchema"));
                    registrations.add(
                            runtime.register(
                                    spec,
                                    ToolRuntime.Mode.SERIAL,
                                    call -> {
                                        ObjectNode input =
                                                ChatAdapter.JSON
                                                        .createObjectNode()
                                                        .put("name", remote);
                                        input.set("arguments", call.args());
                                        JsonNode result = rpc("tools/call", input);
                                        if (result.path("isError").asBoolean())
                                            throw new IllegalStateException(
                                                    "MCP_TOOL_ERROR: " + result);
                                        StringBuilder text = new StringBuilder();
                                        for (JsonNode block : result.path("content")) {
                                            if (!"text".equals(block.path("type").asText()))
                                                throw new IllegalArgumentException("不支持的 MCP 结果类型");
                                            text.append(block.path("text").asText());
                                        }
                                        return text.toString();
                                    }));
                }
                cursor = page.path("nextCursor").asText("");
                if (!cursor.isEmpty() && !seen.add(cursor))
                    throw new IllegalStateException("MCP 分页游标重复");
            } while (!cursor.isEmpty());
        } catch (Exception error) {
            try {
                close();
            } catch (Exception cleanup) {
                error.addSuppressed(cleanup);
            }
            throw error;
        }
    }

    private HttpResponse<InputStream> post(ObjectNode request) throws Exception {
        HttpRequest.Builder builder =
                HttpRequest.newBuilder(endpoint)
                        .timeout(Duration.ofSeconds(8))
                        .header("Content-Type", "application/json")
                        .header("Accept", "application/json, text/event-stream");
        if (initialized) builder.header("MCP-Protocol-Version", VERSION);
        if (!sessionId.isEmpty()) builder.header("Mcp-Session-Id", sessionId);
        return client.send(
                builder.POST(HttpRequest.BodyPublishers.ofString(request.toString())).build(),
                HttpResponse.BodyHandlers.ofInputStream());
    }

    private synchronized JsonNode rpc(String method, ObjectNode params) throws Exception {
        long id = ++requestId;
        ObjectNode request =
                ChatAdapter.JSON
                        .createObjectNode()
                        .put("jsonrpc", "2.0")
                        .put("id", id)
                        .put("method", method);
        request.set("params", params);
        HttpResponse<InputStream> response = post(request);
        try (InputStream input = response.body()) {
            if (response.statusCode() / 100 != 2)
                throw new IllegalStateException("MCP_HTTP_" + response.statusCode());
            sessionId = response.headers().firstValue("Mcp-Session-Id").orElse(sessionId);
            boolean sse =
                    response.headers()
                            .firstValue("Content-Type")
                            .orElse("")
                            .startsWith("text/event-stream");
            // HTTP 头到达不等于响应体读完,读取任务也需要自己的期限。
            Future<JsonNode> future = reader.submit(() -> readResponse(input, sse, id));
            JsonNode value;
            try {
                value = future.get(8, TimeUnit.SECONDS);
            } finally {
                if (!future.isDone()) future.cancel(true);
            }
            if (!"2.0".equals(value.path("jsonrpc").asText()) || value.path("id").asLong(-1) != id)
                throw new IllegalStateException("MCP 响应 ID 不匹配");
            if (value.has("error"))
                throw new IllegalStateException("MCP_RPC_ERROR: " + value.path("error"));
            if (!value.has("result")) throw new IllegalStateException("MCP 响应缺少 result");
            return value.get("result");
        }
    }

    private JsonNode readResponse(InputStream input, boolean sse, long id) throws Exception {
        if (!sse) {
            byte[] bytes = input.readNBytes(1_048_577);
            if (bytes.length > 1_048_576) throw new IllegalStateException("MCP 响应过大");
            return ChatAdapter.JSON.readTree(bytes);
        }
        BufferedReader lines =
                new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        StringBuilder data = new StringBuilder();
        String line;
        int size = 0;
        while ((line = lines.readLine()) != null) {
            size += line.length();
            if (size > 1_048_576) throw new IllegalStateException("MCP 流响应过大");
            if (line.startsWith("data:"))
                data.append(line.substring(5).stripLeading()).append('\n');
            if (line.isEmpty() && !data.isEmpty()) {
                JsonNode message = ChatAdapter.JSON.readTree(data.toString());
                data.setLength(0);
                if (message.path("id").asLong(-1) == id && !message.has("method")) return message;
                if (message.has("method") && message.has("id"))
                    throw new IllegalStateException("不支持服务端主动请求");
            }
        }
        throw new IllegalStateException("MCP 流缺少匹配响应");
    }

    public void close() throws Exception {
        Exception failure = null;
        for (int i = registrations.size() - 1; i >= 0; i--) {
            try {
                registrations.get(i).close();
            } catch (Exception error) {
                if (failure == null) failure = error;
                else failure.addSuppressed(error);
            }
        }
        registrations.clear();
        try {
            if (!sessionId.isEmpty()) {
                HttpRequest request =
                        HttpRequest.newBuilder(endpoint)
                                .timeout(Duration.ofSeconds(3))
                                .header("Mcp-Session-Id", sessionId)
                                .header("MCP-Protocol-Version", VERSION)
                                .DELETE()
                                .build();
                int status =
                        client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();
                if (status / 100 != 2 && status != 405)
                    throw new IllegalStateException("MCP 会话关闭失败: " + status);
            }
        } catch (Exception error) {
            if (failure == null) failure = error;
            else failure.addSuppressed(error);
        } finally {
            reader.shutdownNow();
            initialized = false;
            sessionId = "";
        }
        if (failure != null) throw failure;
    }
}

沿用文件:src/main/java/LocalTools.java

直接读取器保留了工作区真实路径检查。第 04 章以后仍复用这里的文件 schema 与参数校验,但实际派发已经交给 ToolRuntime。

java 复制代码
import java.nio.file.*;
import java.util.*;

// 第 02、03 章只有读工具;第 04 章用 ToolRuntime 替换这个直接执行器。
public final class LocalTools implements Tools {
    private final Path workspace;

    public LocalTools(Path workspace) throws Exception {
        this.workspace = workspace.toRealPath();
    }

    static ToolSpec fileSpec(String name, boolean write) {
        var schema = ChatAdapter.JSON.createObjectNode().put("type", "object");
        var properties = schema.putObject("properties");
        properties.putObject("path").put("type", "string");
        var required = schema.putArray("required").add("path");
        if (write) {
            properties.putObject("text").put("type", "string");
            required.add("text");
        }
        schema.put("additionalProperties", false);
        return new ToolSpec(name, write ? "写入工作区文本文件" : "读取工作区文本文件", schema);
    }

    public List<ToolSpec> specs() {
        return List.of(fileSpec("fs_read", false));
    }

    public List<ToolResult> execute(List<Call> calls) {
        List<ToolResult> results = new ArrayList<>();
        for (Call call : calls) {
            try {
                if (!"fs_read".equals(call.name()))
                    throw new IllegalArgumentException("UNKNOWN_TOOL");
                Path target = workspace.resolve(required(call, "path")).toRealPath();
                if (!target.startsWith(workspace))
                    throw new IllegalArgumentException("PATH_DENIED");
                if (!Files.isRegularFile(target) || Files.size(target) > 65_536) {
                    throw new IllegalArgumentException("INVALID_FILE");
                }
                results.add(ToolResult.text(call.id(), false, Files.readString(target)));
            } catch (Exception error) {
                results.add(
                        ToolResult.text(
                                call.id(),
                                true,
                                error.getClass().getSimpleName() + ": " + error.getMessage()));
            }
        }
        return List.copyOf(results);
    }

    static String required(Call call, String field) {
        var value = call.args().path(field);
        if (!value.isTextual() || value.asText().isBlank())
            throw new IllegalArgumentException("缺少参数: " + field);
        return value.asText();
    }
}

沿用文件:src/main/java/FixtureModel.java

这是固定响应模型。read:brief.txt 产生读文件调用,工具结果回来后原样形成答案;call:工具名:参数JSON 用于指定一次本地调用。它用于重复检查运行规则,不模拟真实模型的规划水平。

java 复制代码
import java.util.*;

// 固定决策只检查运行时链路,不据此评价真实模型的规划能力。
public final class FixtureModel implements Model {
    public Reply next(List<Message> messages, List<ToolSpec> tools) {
        int lastUser = -1;
        for (int i = 0; i < messages.size(); i++)
            if ("user".equals(messages.get(i).role())) lastUser = i;
        Message last = messages.get(messages.size() - 1);
        if ("tool".equals(last.role())) return new Reply(Message.answer(last.text()), "stop");
        String question = messages.get(lastUser).text();
        String name;
        com.fasterxml.jackson.databind.node.ObjectNode args;
        if (question.startsWith("read:")) {
            name = "fs_read";
            args = ChatAdapter.JSON.createObjectNode().put("path", question.substring(5).trim());
        } else if (question.startsWith("call:")) {
            String[] parts = question.split(":", 3);
            try {
                name = parts[1];
                args =
                        (com.fasterxml.jackson.databind.node.ObjectNode)
                                ChatAdapter.JSON.readTree(parts[2]);
            } catch (Exception error) {
                throw new IllegalArgumentException("格式应为 call:工具名:参数JSON", error);
            }
        } else throw new IllegalArgumentException("固定模型接受 read:文件名 或 call:工具名:参数JSON");
        Call call = new Call("call_" + messages.size(), name, args);
        Message reply = new Message("assistant", List.of(), "需要读取文件中的编号", List.of(call), "");
        return new Reply(reply, "tool_calls");
    }
}

本地测试:src/main/java/Checks.java

自检使用临时目录和本机固定响应服务。真实 HTTP、插件 JAR、MCP JSON/SSE、拒绝写入和失败级联都由断言检查,运行后清理临时文件;不读取真实模型密钥来替代这些固定测试。

java 复制代码
import com.sun.net.httpserver.*;

import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public final class Checks {

    interface Attempt {
        void run() throws Exception;
    }

    private static int assertions;

    static void check(boolean value, String message) {
        assertions++;
        if (!value) throw new AssertionError(message);
    }

    static void fails(Attempt attempt, String message) throws Exception {
        try {
            attempt.run();
        } catch (Exception expected) {
            assertions++;
            return;
        }
        throw new AssertionError(message);
    }

    static Call call(String id, String name, String json) throws Exception {
        return new Call(
                id,
                name,
                (com.fasterxml.jackson.databind.node.ObjectNode) ChatAdapter.JSON.readTree(json));
    }

    static ToolSpec emptySpec(String name) {
        return new ToolSpec(name, name, ChatAdapter.JSON.createObjectNode().put("type", "object"));
    }

    static void send(HttpExchange exchange, int status, String type, String text) throws Exception {
        byte[] body = text.getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set("Content-Type", type);
        exchange.sendResponseHeaders(status, body.length);
        exchange.getResponseBody().write(body);
        exchange.close();
    }

    public static void run() throws Exception {
        Path root = Files.createTempDirectory("harness-check-");
        try {
            protocol(root);
            history(root);
            runtime(root);
            capabilities(root);
            System.out.println("PASS chapter-05: " + assertions + " checks");
        } finally {
            try (var paths = Files.walk(root)) {
                for (Path path : paths.sorted(Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(path);
            }
        }
    }

    static void protocol(Path root) throws Exception {
        Call one = call("c1", "fs_read", "{\"path\":\"brief.txt\"}");
        Message assistant = new Message("assistant", List.of(), "保留这段推理状态", List.of(one), "");
        var payload =
                ChatAdapter.encode(
                        List.of(assistant, ToolResult.text("c1", false, "HARNESS-42").message()),
                        List.of());
        check(
                payload.path("messages")
                        .path(0)
                        .path("reasoning_content")
                        .asText()
                        .equals("保留这段推理状态"),
                "思考字段回写");
        check(
                payload.path("messages").path(1).path("tool_call_id").asText().equals("c1"),
                "工具结果配对");
        Message image =
                new Message(
                        "tool",
                        List.of(new TextBlock("编号"), new ImageBlock("memory:test")),
                        "",
                        List.of(),
                        "c1");
        fails(() -> ChatAdapter.encode(List.of(image), List.of()), "不支持的图片不能静默丢失");
        ChatAdapter.CallAssembler assembler = new ChatAdapter.CallAssembler();
        assembler.accept(
                ChatAdapter.JSON.readTree(
                        "{\"tool_calls\":[{\"index\":0,\"id\":\"c1\",\"function\":{\"name\":\"fs_read\",\"arguments\":\"{\\\"pa\"}}]}"));
        assembler.accept(
                ChatAdapter.JSON.readTree(
                        "{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"th\\\":\\\"brief.txt\\\"}\"}}]}"));
        check(
                assembler
                        .finish("tool_calls")
                        .get(0)
                        .args()
                        .path("path")
                        .asText()
                        .equals("brief.txt"),
                "分片拼成完整参数");
        fails(() -> assembler.finish("length"), "截断不能当作完整工具调用");
        AtomicBoolean executed = new AtomicBoolean();
        Tools spy =
                new Tools() {
                    public List<ToolSpec> specs() {
                        return List.of();
                    }

                    public List<ToolResult> execute(List<Call> calls) {
                        executed.set(true);
                        return List.of();
                    }
                };
        fails(
                () ->
                        new Harness(
                                        (m, t) -> new Reply(assistant, "length"),
                                        new MemoryHistory(),
                                        spy,
                                        e -> {})
                                .run("read:brief.txt"),
                "截断应结束本步");
        check(!executed.get(), "截断分支不能派发工具");
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        AtomicInteger requests = new AtomicInteger();
        AtomicBoolean secondRequestValid = new AtomicBoolean();
        server.createContext(
                "/v1/chat/completions",
                exchange -> {
                    try {
                        var request = ChatAdapter.JSON.readTree(exchange.getRequestBody());
                        var messages = request.path("messages");
                        requests.incrementAndGet();
                        boolean toolResult =
                                "tool"
                                        .equals(
                                                messages.path(messages.size() - 1)
                                                        .path("role")
                                                        .asText());
                        String response;
                        if (toolResult) {
                            secondRequestValid.set(
                                    messages.path(1)
                                                    .path("reasoning_content")
                                                    .asText()
                                                    .equals("保留推理")
                                            && messages.path(2)
                                                    .path("tool_call_id")
                                                    .asText()
                                                    .equals("http-call")
                                            && messages.path(2)
                                                    .path("content")
                                                    .asText()
                                                    .contains("HARNESS-42"));
                            response =
                                    "{\"choices\":[{\"finish_reason\":\"stop\",\"message\":{\"role\":\"assistant\",\"content\":\"HARNESS-42\"}}]}";
                        } else {
                            response =
                                    "{\"choices\":[{\"finish_reason\":\"tool_calls\",\"message\":{\"role\":\"assistant\",\"reasoning_content\":\"保留推理\",\"tool_calls\":[{\"id\":\"http-call\",\"function\":{\"name\":\"fs_read\",\"arguments\":\"{\\\"path\\\":\\\"brief.txt\\\"}\"}}]}}]}";
                        }
                        send(exchange, 200, "application/json", response);
                    } catch (Exception error) {
                        exchange.close();
                    }
                });
        server.start();
        try {
            Files.writeString(root.resolve("brief.txt"), "项目编号 HARNESS-42");
            Model model =
                    new ChatAdapter(
                            "http://127.0.0.1:" + server.getAddress().getPort() + "/v1",
                            "fixture",
                            "local-key");
            String answer =
                    new Harness(model, new MemoryHistory(), new LocalTools(root), e -> {})
                            .run("read:brief.txt");
            check(
                    answer.equals("HARNESS-42") && requests.get() == 2 && secondRequestValid.get(),
                    "真实 HTTP 的两次请求和字段回填");
        } finally {
            server.stop(0);
        }
    }

    static void history(Path root) throws Exception {
        Path log = root.resolve("session.jsonl");
        try (FileHistory history = new FileHistory(log, 12_000)) {
            new Harness(new FixtureModel(), history, new LocalTools(root), e -> {})
                    .run("read:brief.txt");
            fails(
                    () -> {
                        try (FileHistory ignored = new FileHistory(log, 12_000)) {}
                    },
                    "禁止并发打开同一会话");
        }
        try (FileHistory history = new FileHistory(log, 12_000)) {
            check(
                    history.messages().size() == 4
                            && history.messages().get(1).reasoning().contains("读取"),
                    "重启后恢复消息和思考字段");
            history.compactPrefix(2, "已读 brief.txt,项目编号 HARNESS-42");
            check(history.messages().get(0).text().contains("HARNESS-42"), "摘要进入消息视图");
            history.append(Message.user("新的问题"));
            history.append(Message.answer("新的答案"));
            history.compactPrefix(2, "仍保留项目编号 HARNESS-42");
            check(history.messages().size() == 3, "多次替换使用显式事件 ID");
        }
        check(
                Files.readString(log).contains("\"op\":\"replace\"")
                        && Files.readString(log).contains("fs_read"),
                "旧事件仍在日志中");
        try (FileHistory history = new FileHistory(log, 12_000)) {
            check(history.messages().size() == 3, "替换后的视图可重建");
        }
        Call call = call("g1", "fs_read", "{\"path\":\"brief.txt\"}");
        List<Message> messages =
                List.of(
                        Message.user("旧问题"),
                        new Message("assistant", List.of(), "", List.of(call), ""),
                        ToolResult.text("g1", false, "很长的工具结果").message(),
                        Message.answer("旧答案"),
                        Message.user("新问题"));
        List<Message> clipped =
                ContextView.trim(messages, ContextView.size(messages.subList(3, 5)));
        check(clipped.size() == 2 && ContextView.groups(clipped).size() == 2, "裁剪不会只留下孤立的工具结果");
        fails(() -> ContextView.trim(List.of(Message.user("太大".repeat(200))), 50), "最新一轮过大时明确失败");
        ClientView view = new ClientView();
        view.accept(new RunEvent("tool_start", "same", "fs_read"));
        view.accept(new RunEvent("tool_start", "same", "fs_read"));
        view.accept(new RunEvent("tool_result", "same", "HARNESS-42"));
        view.accept(new RunEvent("tool_start", "same", "迟到的开始通知"));
        check(
                view.cards().size() == 1 && view.cards().get("same").startsWith("completed"),
                "重复或迟到开始通知不新增卡片、不回退终态");
        Path pending = root.resolve("pending.jsonl");
        try (FileHistory history = new FileHistory(pending, 12_000)) {
            history.append(Message.user("上次写入"));
            history.append(
                    new Message(
                            "assistant",
                            List.of(),
                            "",
                            List.of(
                                    call(
                                            "old-write",
                                            "fs_write",
                                            "{\"path\":\"old.txt\",\"text\":\"不能重放\"}")),
                            ""));
        }
        try (FileHistory history = new FileHistory(pending, 12_000)) {
            new Harness(new FixtureModel(), history, new LocalTools(root), e -> {})
                    .run("read:brief.txt");
            check(
                    history.messages().stream().anyMatch(m -> m.text().contains("UNKNOWN_OUTCOME")),
                    "未确认动作补成未知结果");
            check(!Files.exists(root.resolve("old.txt")), "恢复会话没有重放旧写入");
        }
        Path damaged = root.resolve("damaged.jsonl");
        Files.writeString(damaged, "{\"seq\":1");
        fails(
                () -> {
                    try (FileHistory ignored = new FileHistory(damaged, 12_000)) {}
                },
                "损坏尾行不能静默跳过");
    }

    static void runtime(Path root) throws Exception {
        Call write = call("write", "fs_write", "{\"path\":\"denied.md\",\"text\":\"报告\"}");
        try (ToolRuntime tools = new ToolRuntime(call -> !call.name().equals("fs_write"), 1000)) {
            tools.registerFiles(root);
            ToolSpec reusable = emptySpec("reused");
            ToolRuntime.Action action = call -> "ok";
            AutoCloseable old = tools.register(reusable, ToolRuntime.Mode.PARALLEL, action);
            old.close();
            AutoCloseable newer = tools.register(reusable, ToolRuntime.Mode.PARALLEL, action);
            old.close();
            check(
                    tools.specs().stream().anyMatch(spec -> spec.name().equals("reused")),
                    "旧关闭句柄不能删除重新注册的同名工具");
            newer.close();
            check(
                    tools.execute(List.of(write)).get(0).error()
                            && !Files.exists(root.resolve("denied.md")),
                    "拒绝写入没有文件副作用");
            CountDownLatch bFinished = new CountDownLatch(1);
            tools.register(
                    emptySpec("a"),
                    ToolRuntime.Mode.PARALLEL,
                    call -> {
                        bFinished.await();
                        Thread.sleep(20);
                        return "A";
                    });
            tools.register(
                    emptySpec("b"),
                    ToolRuntime.Mode.PARALLEL,
                    call -> {
                        bFinished.countDown();
                        return "B";
                    });
            var results = tools.execute(List.of(call("a1", "a", "{}"), call("b1", "b", "{}")));
            check(
                    results.get(0).callId().equals("a1") && results.get(1).callId().equals("b1"),
                    "完成顺序不改变回填顺序");
            Path outside = Files.createTempFile("outside-notes-", ".txt");
            try {
                Files.writeString(outside, "不应读到");
                Files.createSymbolicLink(root.resolve("escape.txt"), outside);
                check(
                        tools.execute(
                                        List.of(
                                                call(
                                                        "escape",
                                                        "fs_read",
                                                        "{\"path\":\"escape.txt\"}")))
                                .get(0)
                                .error(),
                        "符号链接越界被拒");
            } finally {
                Files.deleteIfExists(root.resolve("escape.txt"));
                Files.deleteIfExists(outside);
            }
        }
        AtomicBoolean externalEffect = new AtomicBoolean();
        List<ToolResult> timed;
        try (ToolRuntime tools = new ToolRuntime(call -> true, 25)) {
            tools.register(
                    emptySpec("slow"),
                    ToolRuntime.Mode.PARALLEL,
                    call -> {
                        long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(150);
                        while (System.nanoTime() < end) {
                            try {
                                Thread.sleep(5);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        externalEffect.set(true);
                        return "late";
                    });
            timed = tools.execute(List.of(call("slow1", "slow", "{}")));
            check(
                    timed.get(0).error() && timed.get(0).message().text().equals("TOOL_TIMEOUT"),
                    "超时生成终态失败");
        }
        check(externalEffect.get() && timed.get(0).error(), "底层迟到动作可能发生,但不能覆盖超时结果");
        try (ToolRuntime tools = new ToolRuntime(call -> true, 1000)) {
            tools.registerFiles(root);
            var results =
                    tools.execute(
                            List.of(
                                    call(
                                            "w",
                                            "fs_write",
                                            "{\"path\":\"ordered.txt\",\"text\":\"new\"}"),
                                    call("r", "fs_read", "{\"path\":\"ordered.txt\"}")));
            check(results.get(1).message().text().equals("new"), "串行写入形成后续读取屏障");
        }
    }

    static void capabilities(Path root) throws Exception {
        try (ToolRuntime tools = new ToolRuntime(call -> true, 2000);
                Capabilities host = new Capabilities(tools)) {
            int baseline = tools.specs().size();
            fails(
                    () ->
                            host.start(
                                    "broken",
                                    scope -> {
                                        scope.register(
                                                emptySpec("temporary"),
                                                ToolRuntime.Mode.PARALLEL,
                                                call -> "x");
                                        throw new IllegalStateException("configure failure");
                                    }),
                    "插件启动失败");
            check(tools.specs().size() == baseline, "启动失败回滚已注册工具");
            List<String> order = new ArrayList<>();
            host.start(
                    "order",
                    scope -> {
                        scope.own(() -> order.add("first"));
                        scope.own(() -> order.add("second"));
                    });
            host.stop("order");
            check(order.equals(List.of("second", "first")), "资源逆序释放");
            Path skills = root.resolve("skills/report-spec");
            Files.createDirectories(skills);
            Files.writeString(skills.resolve("SKILL.md"), "报告必须包含材料来源与编号");
            host.registerSkills(root.resolve("skills"));
            check(
                    tools.specs().stream()
                            .filter(spec -> spec.name().equals("plugin__skills__load"))
                            .findFirst()
                            .orElseThrow()
                            .description()
                            .contains("report-spec"),
                    "Skill 名称和简介进入模型可见元数据");
            ToolResult skill =
                    tools.execute(
                                    List.of(
                                            call(
                                                    "skill",
                                                    "plugin__skills__load",
                                                    "{\"name\":\"report-spec\"}")))
                            .get(0);
            check(
                    skill.message().text().contains("材料来源")
                            && !Files.exists(root.resolve("report-from-skill.md")),
                    "Skill 返回说明,没有自行生成报告");
            Path pluginDir = root.resolve("external-plugin");
            Files.createDirectories(pluginDir);
            String code =
                    "public class NumberPlugin implements Capabilities.Plugin { public void"
                        + " configure(Capabilities.Scope scope) throws Exception {"
                        + " scope.registerText(\"number\",\"查询编号\",\"{\\\"type\\\":\\\"object\\\"}\",true,args"
                        + " -> \"HARNESS-42\"); } }";
            Path source = pluginDir.resolve("NumberPlugin.java");
            Files.writeString(source, code);
            int compiled =
                    javax.tools.ToolProvider.getSystemJavaCompiler()
                            .run(
                                    null,
                                    null,
                                    null,
                                    "-classpath",
                                    System.getProperty("java.class.path"),
                                    "-d",
                                    pluginDir.toString(),
                                    source.toString());
            check(compiled == 0, "独立插件编译");
            Path jar = pluginDir.resolve("number.jar");
            try (var output = new java.util.jar.JarOutputStream(Files.newOutputStream(jar))) {
                output.putNextEntry(new java.util.jar.JarEntry("NumberPlugin.class"));
                output.write(Files.readAllBytes(pluginDir.resolve("NumberPlugin.class")));
                output.closeEntry();
                output.putNextEntry(
                        new java.util.jar.JarEntry("META-INF/services/Capabilities$Plugin"));
                output.write("NumberPlugin\n".getBytes(StandardCharsets.UTF_8));
                output.closeEntry();
            }
            host.startJar("jar", jar);
            check(
                    tools.execute(List.of(call("jar1", "plugin__jar__number", "{}")))
                            .get(0)
                            .message()
                            .text()
                            .equals("HARNESS-42"),
                    "JAR 中的 SPI 插件真实调用");
            host.stop("jar");
            check(
                    tools.specs().stream().noneMatch(t -> t.name().equals("plugin__jar__number")),
                    "插件停用注销工具");
            for (boolean sse : List.of(false, true)) {
                AtomicBoolean initialized = new AtomicBoolean(), closed = new AtomicBoolean();
                HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
                server.createContext(
                        "/mcp",
                        exchange -> {
                            try {
                                if ("DELETE".equals(exchange.getRequestMethod())) {
                                    closed.set(true);
                                    send(exchange, 200, "application/json", "{}");
                                    return;
                                }
                                var request = ChatAdapter.JSON.readTree(exchange.getRequestBody());
                                String method = request.path("method").asText();
                                if (method.equals("notifications/initialized")) {
                                    initialized.set(true);
                                    exchange.sendResponseHeaders(202, -1);
                                    exchange.close();
                                    return;
                                }
                                var response =
                                        ChatAdapter.JSON.createObjectNode().put("jsonrpc", "2.0");
                                response.set("id", request.get("id"));
                                var result = response.putObject("result");
                                if (method.equals("initialize")) {
                                    result.put("protocolVersion", "2025-06-18");
                                    result.putObject("capabilities").putObject("tools");
                                    exchange.getResponseHeaders()
                                            .set("Mcp-Session-Id", "local-session");
                                } else {
                                    if (!initialized.get()
                                            || !"2025-06-18"
                                                    .equals(
                                                            exchange.getRequestHeaders()
                                                                    .getFirst(
                                                                            "MCP-Protocol-Version"))
                                            || !"local-session"
                                                    .equals(
                                                            exchange.getRequestHeaders()
                                                                    .getFirst("Mcp-Session-Id")))
                                        throw new IllegalStateException("握手或头部缺失");
                                    if (method.equals("tools/list")) {
                                        var descriptor =
                                                result.putArray("tools")
                                                        .addObject()
                                                        .put("name", "lookup")
                                                        .put("description", "查询编号");
                                        descriptor.putObject("inputSchema").put("type", "object");
                                    } else if (method.equals("tools/call"))
                                        result.putArray("content")
                                                .addObject()
                                                .put("type", "text")
                                                .put("text", "HARNESS-42");
                                    else throw new IllegalStateException("未知方法");
                                }
                                String body =
                                        sse && method.equals("tools/call")
                                                ? "data:"
                                                      + " {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\n\n"
                                                      + "data: "
                                                        + response
                                                        + "\n\n"
                                                : response.toString();
                                send(
                                        exchange,
                                        200,
                                        sse && method.equals("tools/call")
                                                ? "text/event-stream"
                                                : "application/json",
                                        body);
                            } catch (Exception error) {
                                exchange.close();
                            }
                        });
                server.start();
                try {
                    try (McpBridge bridge =
                            new McpBridge(
                                    URI.create(
                                            "http://127.0.0.1:"
                                                    + server.getAddress().getPort()
                                                    + "/mcp"))) {
                        bridge.connect(tools, "local");
                        ToolResult value =
                                tools.execute(List.of(call("mcp1", "mcp__local__lookup", "{}")))
                                        .get(0);
                        check(
                                !value.error() && value.message().text().equals("HARNESS-42"),
                                "MCP 握手、发现和调用: sse=" + sse);
                    }
                    check(
                            closed.get()
                                    && tools.specs().stream()
                                            .noneMatch(t -> t.name().startsWith("mcp__local__")),
                            "MCP 注销和会话关闭");
                } finally {
                    server.stop(0);
                }
            }
        }
    }
}

沿用文件:pom.xml

xml 复制代码
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>notes</groupId>
    <artifactId>mini-agent</artifactId>
    <version>1.0</version>
    <properties>
        <maven.compiler.release>17</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.17.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.13.0</version>
            </plugin>
        </plugins>
    </build>
</project>

沿用文件:run.sh

bash 复制代码
#!/usr/bin/env bash
set -euo pipefail
PROJECT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
cd "$PROJECT_DIR"
if [[ "$(uname -s)" == "Darwin" ]]; then
    export JAVA_HOME="$(/usr/libexec/java_home -v 17)"
fi
if [[ -n "${JAVA_HOME:-}" ]]; then
    export PATH="$JAVA_HOME/bin:$PATH"
fi
mvn -q compile dependency:copy-dependencies -DincludeScope=runtime
exec java -cp 'target/classes:target/dependency/*' MiniAgent "$@"

代码说明

Capabilities 管注册与释放,McpBridge 管协议会话与调用转换。Skill 返回文本说明,模型继续选择工具;MCP 返回的结果也要转换成内部工具结果。Checks 中真正生成并加载 JAR,避免只在宿主 classpath 内 new 对象而漏掉加载器边界。

代码位置 输入与状态变化 检查点
Capabilities.startJar() 加载 JAR,按服务声明找到 Plugin,调用 configure。 Checks 临时生成的 JAR 来自另一加载器,可以暴露宿主可见性问题。
Scope.registerText() / close() 注册返回关闭句柄;回滚与停用按逆序释放。 configure 注册一项后抛错,这项工具不会残留在 tools.specs()。
registerSkills() 名称与首行简介进入工具描述,调用后才读取正文。 只看工具列表时没有整篇规范;加载规范本身不写报告。
McpBridge.connect() 完成 initialize、通知与工具发现,把远端工具注册到本地。 宿主使用 mcp__local__lookup,对端 tools/call 收到的仍是 lookup。
rpc() / readResponse() 保留会话头,核对响应 ID,解析 JSON 或 POST SSE。 同一份工具结果可以经两种传输返回,仍由 Harness 统一回填。

扩展入口增加后,单份历史会逐渐装入不同来源的材料。第 06 章拆出独立任务与历史,用依赖关系交接必要结果。


上一篇:工具执行、审批与沙箱 · 系列目录 · 下一篇:任务与多 Agent 编排

相关推荐
YIAN1 小时前
我踩完 DeepAgents 记忆模块的坑,才搞懂长期记忆和摘要不是一回事
前端·javascript·agent
2395730491 小时前
从 GUI 彻底转向 CLI:我用 .NET + Avalonia + NativeAOT 打造了 Agent 终端托管工具 Octopus
开源·.net·agent·avalonia·ai coding
唐老板2 小时前
Spring AI 2.0 只支持 Boot 4
java
YIAN2 小时前
用 Deep Agents 复现一个深度调研助手:从主 Agent、子 Agent 到 Skill
javascript·agent
IT规划师4 小时前
热点速递 | MCP 省 token,不是少接工具,是把工具变成文件
agent·ai编程
琳少_4 小时前
java程序设计笔记
java·开发语言·数据库·笔记
AI-Frontiers5 小时前
讲透企业级本体落地!从六要素建模到图谱、知识库与数字员工全链路实战
agent
小荷才露尖尖角,早有蜻蜓立上头6 小时前
SpringBoot 定时任务
java·spring boot·后端
阿里云云原生6 小时前
AgentTeams 1.2.8:全新工作台与新官网,一键开启团队协作
agent