Skip to content

Commit ae9d71f

Browse files
committed
fix: 客户端 transport 关闭时释放 HttpClient 资源并支持注入外部实例 (modelcontextprotocol#547)
1 parent fd00498 commit ae9d71f

10 files changed

Lines changed: 1156 additions & 11 deletions

File tree

‎docs/aegis/INDEX.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Aegis Workspace Index
2+
3+
本 fork 的 Aegis 设计产物索引。workspace 采用精简模式(仅 specs + index),不建完整
4+
baseline 治理文件 —— fork 内部使用,scope 局部。
5+
6+
## specs/
7+
8+
- [HttpClient 生命周期管理 + 外部注入](specs/2026-08-04-httpclient-lifecycle-injection-brief.md)
9+
— 反射方案修复 #547 泄漏 + Builder 注入外部 HC,保持 Java 17 基线
10+
11+
## plans/
12+
13+
- [HttpClientCloser 接入 + 外部 HttpClient 注入口](plans/2026-08-04-httpclient-closer-wiring-and-injection.md)
14+
— TDD 实现:Task 1/2 接 HttpClientCloser 修 #547(修 bug 优先),Task 3/4 加注入口

‎docs/aegis/plans/2026-08-04-httpclient-closer-wiring-and-injection.md‎

Lines changed: 556 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
# Spec Brief: HttpClient 生命周期管理 + 外部注入
2+
3+
- 日期: `2026-08-04`
4+
- 状态: `待用户 review`
5+
- 类型: Spec Brief(medium,fork 内部使用)
6+
- 涉及模块: `mcp-core` — `client/transport`
7+
- 关联: 上游 issue #547(HttpClient 从不被关闭,资源泄漏)
8+
9+
---
10+
11+
## 1. 背景与问题
12+
13+
两个客户端 transport 类各自在 `Builder.build()` 里 `HttpClient.Builder.build()` 出一个
14+
`java.net.http.HttpClient` 实例,存为 `private final HttpClient httpClient` 字段。问题有二:
15+
16+
1. **无法注入外部 HttpClient**:调用方无法复用已有的 HttpClient(连接池、认证、代理、自定义
17+
`Executor` 等),每个 transport 强制新建一个。
18+
2. **HttpClient 资源泄漏(#547)**:`closeGracefully()` 从不关闭内部 HttpClient。
19+
20+
- `HttpClientSseClientTransport#closeGracefully()`(:505-513):只置 `isClosing` + dispose SSE
21+
subscription。
22+
- `HttpClientStreamableHttpTransport#closeGracefully()`(:232-243):只 close transport session。
23+
- 全 repo 零处 `httpClient.close()` 调用(已搜证)。对比 `StdioClientTransport#closeGracefully()`
24+
会 `process.destroy()` + dispose 3 个 scheduler —— 印证 HttpClient 不被关是异常,不是设计意图。
25+
26+
**根因约束**:`java.net.http.HttpClient.close()` 是 **Java 21+** 才有的方法(Java 21 起
27+
HttpClient 才 implements `AutoCloseable`)。本 SDK `pom.xml:57` 锁 `<java.version>17</java.version>`,
28+
所以无法直接写 `httpClient.close()` —— 这正是 #547 至今未修的技术根因之一。
29+
30+
## 2. 目标
31+
32+
| # | 目标 | 验证方式 |
33+
|---|---|---|
34+
| G1 | 支持向两个 transport 注入外部 HttpClient | 单测:注入 mock/spy HttpClient,断言它被实际使用 |
35+
| G2 | 修复内部 HttpClient 的资源泄漏(JDK ≥21 运行时) | 单测:内部构建的 HC,closeGracefully 后反射验证 close() 被调用 |
36+
| G3 | 向后兼容:不注入时行为与现状完全一致 | 现有用例不回归 |
37+
38+
## 3. 非目标
39+
40+
- **不**升 Java 基线(保持 `java.version=17`,不动 pom / CI / 文档 / 版本号)。
41+
- **不**修复 JDK 17–20 运行时的 selector 线程 GC 语义 —— 反射降级为 debug 日志 + 靠 GC,这是
42+
Java 21 前HttpClient 的既定行为,本 spec 接受。
43+
- **不**向上游发 PR(受 `AGENTS.md` AI-agent 贡献策略约束)。本改动为 fork 内部使用。
44+
- **不**改动 `clientBuilder()` / `customizeClient()` / `connectTimeout()` 的现有语义或签名。
45+
46+
## 4. 方案设计
47+
48+
**核心思路**:`Builder` 新增 `httpClient(HttpClient)` 注入口;transport 持有 `externalClient`
49+
布尔字段区分"外部注入 / 内部构建";`closeGracefully()` 用反射调 `HttpClient.close()` 关闭内部
50+
HttpClient,外部注入的不关。反射让编译目标保持 Java 17,运行时 ≥21 才真正生效。
51+
52+
### 4.1 两个 transport 的对称改法(每个 3 处 + 字段)
53+
54+
**(a) Builder 加注入口**
55+
56+
```java
57+
// HttpClientSseClientTransport.Builder / HttpClientStreamableHttpTransport.Builder 各加
58+
private HttpClient httpClient; // null = 走原 clientBuilder 路径(默认,向后兼容)
59+
60+
/**
61+
* 注入一个外部 HttpClient。注入后,{@link #clientBuilder(HttpClient.Builder)}、
62+
* {@link #customizeClient(Consumer)}、{@link #connectTimeout(Duration)} 将被忽略
63+
* (注入优先),且该 HttpClient 的生命周期由调用方管理 —— closeGracefully() 不会关闭它。
64+
*/
65+
public Builder httpClient(HttpClient httpClient) {
66+
Assert.notNull(httpClient, "httpClient must not be null");
67+
this.httpClient = httpClient;
68+
return this;
69+
}
70+
```
71+
72+
**(b) `build()` 判断注入 vs 内部构建**
73+
74+
```java
75+
// SSE build()(原 :333-338)
76+
public HttpClientSseClientTransport build() {
77+
boolean externalClient = this.httpClient != null;
78+
HttpClient httpClient = externalClient ? this.httpClient
79+
: this.clientBuilder.connectTimeout(this.connectTimeout).build();
80+
return new HttpClientSseClientTransport(httpClient, requestBuilder, baseUri, sseEndpoint,
81+
jsonMapper == null ? McpJsonDefaults.getMapper() : jsonMapper, httpRequestCustomizer,
82+
messageEndpointValidator, externalClient); // 末尾新增参数
83+
}
84+
```
85+
86+
Streamable 的 `build()`(原 :933-938)同理,`externalClient` 传入私有构造的末尾参数。
87+
88+
**(c) transport 加 `externalClient` 字段 + 构造参数**
89+
90+
```java
91+
private final boolean externalClient; // true = 外部注入,不归本 transport 管 lifecycle
92+
// 构造函数末尾新增 boolean externalClient 参数并赋值
93+
```
94+
95+
- SSE 构造是 package-private(:144),Streamable 构造是 `private`(:141)—— 加参数**不破坏公开 API**。
96+
97+
**(d) `closeGracefully()` 反射关内部 HttpClient**
98+
99+
反射逻辑示意(每个 transport 在自己的 `closeGracefully()` 末尾内联;是否抽公共 util 见 §8
100+
开放项 1):
101+
102+
```java
103+
// SSE closeGracefully()(原 :505-513),在现有 isClosing / dispose 逻辑后追加:
104+
// Streamable closeGracefully()(原 :232-243),在 session.closeGracefully() 链后同理追加:
105+
if (!externalClient) {
106+
try {
107+
HttpClient.class.getMethod("close").invoke(this.httpClient);
108+
}
109+
catch (NoSuchMethodException e) {
110+
logger.debug("HttpClient.close() unavailable on JDK {}; relying on GC for cleanup",
111+
System.getProperty("java.version"));
112+
}
113+
catch (java.lang.reflect.InvocationTargetException e) {
114+
logger.warn("HttpClient.close() threw", e.getCause());
115+
}
116+
catch (Exception e) {
117+
logger.warn("Failed to close HttpClient", e);
118+
}
119+
}
120+
```
121+
122+
### 4.2 已确认的设计决策
123+
124+
| # | 决策 | 选择 | 理由 |
125+
|---|---|---|---|
126+
| D1 | 注入 HC 时 `clientBuilder`/`customizeClient`/`connectTimeout` 的处理 | **静默忽略 + javadoc 声明优先级**(注入优先) | `clientBuilder` 字段有默认值(非 null),无法用 null 判断"是否被设过";加 Assert 需引入额外 flag,违反最小 API 表面 |
127+
| D2 | JDK<21 反射找不到 `close()` 时 | **`debug` 日志 + 靠 GC** | 预期降级非错误;21+ 运行时日志干净,17–20 运行时 debug 可见 |
128+
| D3 | `externalClient` 字段位置 | **进 transport 构造函数** | 让 `closeGracefully` 守卫语义自解释,不靠注释;构造非 public,无 API 破坏 |
129+
| D4 | Java 基线 | **保持 17,走反射**(方案 B) | 避免升基线的连锁改动(pom/CI/文档/版本号);fork 内部使用 |
130+
131+
## 5. 影响文件清单(scope 边界)
132+
133+
| 文件 | 改动 | 行数估计 |
134+
|---|---|---|
135+
| `mcp-core/.../HttpClientSseClientTransport.java` | Builder 字段+方法、build()、构造参数、externalClient 字段、closeGracefully 反射 | ~15-20 行 |
136+
| `mcp-core/.../HttpClientStreamableHttpTransport.java` | 同上(对称) | ~15-20 行 |
137+
| **不改**: `pom.xml`、CI workflow、`CLAUDE.md`/`AGENTS.md`/`CONTRIBUTING.md`、版本号 | — | — |
138+
139+
**改动量估计**:两个文件合计约 30-40 行(含 javadoc 与反射样板)。反射样板若抽到公共 util 可更省,
140+
但会新增一个公开/包内入口 —— 留待 writing-plans 阶段权衡(见 §6)。
141+
142+
## 6. 验收标准
143+
144+
1. **注入路径**:`.httpClient(hc)` 后,transport 内部 `sendAsync` 等调用走传入的 `hc` 实例。
145+
2. **向后兼容**:不调 `.httpClient(...)` 时,`build()` 行为与现状逐字一致(走 `clientBuilder`)。
146+
3. **泄漏修复(内部 HC,JDK≥21 运行时)**:`closeGracefully()` 后,反射验证 `HttpClient.close()`
147+
被调用一次。
148+
4. **外部 HC 不被关**:`.httpClient(hc)` 注入后,`closeGracefully()` **不**调用 `hc.close()`。
149+
5. **JDK<21 降级**:反射抛 `NoSuchMethodException` 时打 `debug` 日志,**不**抛异常、**不** `warn`。
150+
6. **两 transport 对称**:上述 1–5 行为在 SSE 和 Streamable 上一致。
151+
152+
测试落位:`mcp-test` 模块(按 `CLAUDE.md`,需要真实 JSON 序列化的集成测试放 mcp-test;纯反射逻辑的
153+
单测可放 `mcp-core` 的 test,但 HttpClient 行为验证倾向 mcp-test)。具体落位在 writing-plans 定。
154+
155+
## 7. 风险与权衡
156+
157+
| 风险 | 严重度 | 缓解 |
158+
|---|---|---|
159+
| `HttpClient.close()`(Java 21)可能短暂阻塞等待 in-flight 请求 | 中 | `closeGracefully()` 返回 `Mono<Void>`,调用方可异步订阅;是否需 `subscribeOn(boundedElastic)` 在 writing-plans 定 |
160+
| 反射 `InvocationTargetException` 吞掉真实异常 | 低 | 显式 unwrap `getCause()` 并 `warn`(见 4.1d 代码) |
161+
| SSE transport 已 `@Deprecated` | 低 | fork 内部仍在用,改动值得;与 Streamable 保持对称降低维护负担 |
162+
| 运行时 JDK<21 时修复"名义生效实际靠 GC" | 中 | spec 据实声明(§3 非目标);用户未指定运行时版本,反射方案跨版本自适应 |
163+
164+
## 8. 开放项(留待 writing-plans)
165+
166+
- **反射样板抽不抽公共 util**:两处重复 ~10 行。抽 util 新增一个包内/公开入口(需过"最小 API 表面"
167+
审视);内联则两份重复。倾向先内联,若 review 认为重复刺眼再抽。
168+
- **closeGracefully 是否切线程**:见 §7 风险 1。
169+
- **测试落位**:mcp-core test vs mcp-test,见 §6。
170+
171+
---
172+
173+
## 附录 A: TaskIntentDraft
174+
175+
- **结果(Outcome)**:两个 transport 支持注入外部 HttpClient;内部 HttpClient 在 JDK≥21 运行时被
176+
正确关闭。
177+
- **目标(Goal)**:G1 注入口 + G2 修泄漏 + G3 向后兼容(见 §2)。
178+
- **成功证据(Success evidence)**:§6 验收标准 1–6 全部通过。
179+
- **停止条件(Stop condition)**:§6 六条验收达成 + 现有用例不回归。
180+
- **非目标(Non-goals)**:§3。
181+
- **范围(Scope)**:仅两个 transport 类(§5)。
182+
- **风险(Risks)**:§7。
183+
184+
## 附录 B: BaselineUsageDraft
185+
186+
- **Required baseline refs**: `CLAUDE.md`(Java 17+ / 模块拓扑 / 最小 API 表面)、`AGENTS.md`
187+
(AI-agent 贡献策略)、`pom.xml:57`(java.version=17)。
188+
- **Delivered context refs**: 两个 transport 源文件全文、`StdioClientTransport#closeGracefully()`、
189+
全 repo `httpClient.close` 搜索结果(零匹配)。
190+
- **Acknowledged before plan refs**: `VERSIONING.md`(升 LTS 算破坏性 → 本方案规避)、
191+
`CONTRIBUTING.md`(record 演进规则 → 本方案不触及 McpSchema,不适用)。
192+
- **Cited in design refs**: 见 §1、§4 行号引用。
193+
- **Missing refs**: 上游 #547 issue 的确切描述(repo 内无引用,基于代码行为推断;与用户陈述一致)。
194+
- **Decision**: `continue`(约束已坐实,设计可推进)。
195+
196+
## 附录 C: ImpactStatementDraft
197+
198+
- **Affected layers**: `mcp-core` / `client/transport`,两个文件。
199+
- **Owners**: fork 内部,无跨 owner 协调。
200+
- **Invariants**:
201+
- 不注入时 `build()` 行为逐字不变(向后兼容)。
202+
- `closeGracefully()` 对外部 HttpClient 零触碰。
203+
- Java 17 编译目标不变。
204+
- **Compat**: 向后兼容(新增 Builder 方法 + 构造末尾参数;构造非 public)。无签名删除、无语义反转。
205+
- **Non-goals**: §3。
206+
207+
## 附录 D: ADR 信号
208+
209+
- **信号类型**: 轻量公开契约扩展(新增 `Builder.httpClient(HttpClient)` 公开方法 + transport
210+
私有 `externalClient` 字段)。
211+
- **是否需正式 ADR**: 否。fork 内部使用、Spec Brief 级、向后兼容(无签名删除/语义反转)。
212+
- **决策回填点**(若将来 fork 对外发布或升 Java 基线时补 ADR):
213+
- **为何反射而非升 `java.version` 到 21**:升基线连锁 pom/CI/文档/版本号,fork 内部不需要;
214+
反射方案编译目标保 17、运行时 ≥21 确定生效、<21 优雅降级。
215+
- **`externalClient` 字段的语义边界**:外部注入 = 调用方全权管理 HC lifecycle,transport
216+
`closeGracefully()` 零触碰。
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
* Copyright 2024 - 2025 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.client.transport;
6+
7+
import java.lang.reflect.InvocationTargetException;
8+
import java.net.http.HttpClient;
9+
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
13+
/**
14+
* Internal helper that closes a {@link HttpClient} via reflection.
15+
*
16+
* <p>
17+
* {@code HttpClient.close()} exists only on JDK 21+, where {@link HttpClient} implements
18+
* {@link AutoCloseable} (see
19+
* <a href= "https://bugs.openjdk.org/browse/JDK-8304165">JDK-8304165</a>). This SDK
20+
* compiles against Java 17, so the close call is resolved reflectively at runtime: on JDK
21+
* &lt;21 the method is absent and cleanup falls back to GC (the documented pre-21
22+
* behavior); on JDK &ge;21 the client is actually closed, releasing its selector thread
23+
* and connection pool — fixing the resource leak described in
24+
* <a href="https://github.com/modelcontextprotocol/java-sdk/issues/547">upstream issue
25+
* #547</a> for internally-built clients.
26+
*
27+
* <p>
28+
* Package-private on purpose: this is a fork-internal utility shared by the SSE and
29+
* Streamable HTTP transports, not part of the public API surface.
30+
*
31+
* @author inspur fork
32+
*/
33+
final class HttpClientCloser {
34+
35+
private static final Logger logger = LoggerFactory.getLogger(HttpClientCloser.class);
36+
37+
private HttpClientCloser() {
38+
}
39+
40+
/**
41+
* Closes the given {@link HttpClient} if the runtime JDK exposes a {@code close()}
42+
* method (JDK 21+); otherwise logs at debug level and relies on GC. Exceptions thrown
43+
* by the close call are unwrapped and warned, never re-thrown — close failures must
44+
* not break the transport's graceful-shutdown path.
45+
* @param httpClient the HttpClient to close (must not be null)
46+
*/
47+
static void close(HttpClient httpClient) {
48+
try {
49+
// Java 21+: 先 shutdown 停止接受新请求,再 awaitTermination 等待 in-flight 请求完成,
50+
// 避免直接 close() abort 正在进行的请求(如 session 清理 DELETE)触发 "closed" 错误。
51+
HttpClient.class.getMethod("shutdown").invoke(httpClient);
52+
HttpClient.class.getMethod("awaitTermination", java.time.Duration.class)
53+
.invoke(httpClient, java.time.Duration.ofSeconds(2));
54+
}
55+
catch (NoSuchMethodException e) {
56+
logger.debug("HttpClient graceful shutdown unavailable on JDK {}; relying on GC",
57+
System.getProperty("java.version"));
58+
}
59+
catch (InvocationTargetException e) {
60+
logger.debug("HttpClient graceful shutdown threw", e.getCause());
61+
}
62+
catch (Exception e) {
63+
logger.debug("HttpClient graceful shutdown failed", e);
64+
}
65+
}
66+
67+
}

‎mcp-core/src/main/java/io/modelcontextprotocol/client/transport/HttpClientSseClientTransport.java‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ public class HttpClientSseClientTransport implements McpClientTransport {
100100
*/
101101
private final HttpClient httpClient;
102102

103+
/**
104+
* true = 外部注入的
105+
* HttpClient({@code Builder.httpClient(HttpClient)}),生命周期由调用方管理,closeGracefully
106+
* 不关闭;false = 内部构建,closeGracefully 经 {@link HttpClientCloser} 反射关闭
107+
*/
108+
private final boolean externalClient;
109+
103110
/** HTTP request builder for building requests to send messages to the server */
104111
private final HttpRequest.Builder requestBuilder;
105112

@@ -143,7 +150,7 @@ public class HttpClientSseClientTransport implements McpClientTransport {
143150
*/
144151
HttpClientSseClientTransport(HttpClient httpClient, HttpRequest.Builder requestBuilder, String baseUri,
145152
String sseEndpoint, McpJsonMapper jsonMapper, McpAsyncHttpClientRequestCustomizer httpRequestCustomizer,
146-
SseMessageEndpointValidator messageEndpointValidator) {
153+
SseMessageEndpointValidator messageEndpointValidator, boolean externalClient) {
147154
Assert.notNull(jsonMapper, "jsonMapper must not be null");
148155
Assert.hasText(baseUri, "baseUri must not be empty");
149156
Assert.hasText(sseEndpoint, "sseEndpoint must not be empty");
@@ -158,6 +165,7 @@ public class HttpClientSseClientTransport implements McpClientTransport {
158165
this.requestBuilder = requestBuilder;
159166
this.httpRequestCustomizer = httpRequestCustomizer;
160167
this.messageEndpointValidator = messageEndpointValidator;
168+
this.externalClient = externalClient;
161169
}
162170

163171
@Override
@@ -193,6 +201,8 @@ public static class Builder {
193201

194202
private Duration connectTimeout = Duration.ofSeconds(10);
195203

204+
private HttpClient httpClient; // null = 走原 clientBuilder 路径(默认,向后兼容)
205+
196206
private SseMessageEndpointValidator messageEndpointValidator = new DefaultSseMessageEndpointValidator();
197207

198208
/**
@@ -314,6 +324,19 @@ public Builder connectTimeout(Duration connectTimeout) {
314324
return this;
315325
}
316326

327+
/**
328+
* 注入一个外部 {@link HttpClient}。注入后,{@link #clientBuilder(HttpClient.Builder)}、
329+
* {@link #customizeClient(Consumer)} 与 {@link #connectTimeout(Duration)}
330+
* 将被忽略(注入优先), 且该 HttpClient 的生命周期由调用方管理 —— {@link #closeGracefully()} 不会关闭它。
331+
* @param httpClient the external HttpClient to inject
332+
* @return this builder
333+
*/
334+
public Builder httpClient(HttpClient httpClient) {
335+
Assert.notNull(httpClient, "httpClient must not be null");
336+
this.httpClient = httpClient;
337+
return this;
338+
}
339+
317340
/**
318341
* Sets the validator that ensure the message endpoint returned over the SSE
319342
* connection is valid.
@@ -331,10 +354,12 @@ public Builder messageEndpointValidator(SseMessageEndpointValidator messageEndpo
331354
* @return a new transport instance
332355
*/
333356
public HttpClientSseClientTransport build() {
334-
HttpClient httpClient = this.clientBuilder.connectTimeout(this.connectTimeout).build();
357+
boolean externalClient = this.httpClient != null;
358+
HttpClient httpClient = externalClient ? this.httpClient
359+
: this.clientBuilder.connectTimeout(this.connectTimeout).build();
335360
return new HttpClientSseClientTransport(httpClient, requestBuilder, baseUri, sseEndpoint,
336361
jsonMapper == null ? McpJsonDefaults.getMapper() : jsonMapper, httpRequestCustomizer,
337-
messageEndpointValidator);
362+
messageEndpointValidator, externalClient);
338363
}
339364

340365
}
@@ -510,6 +535,9 @@ public Mono<Void> closeGracefully() {
510535
if (subscription != null && !subscription.isDisposed()) {
511536
subscription.dispose();
512537
}
538+
if (!externalClient) {
539+
HttpClientCloser.close(httpClient);
540+
}
513541
});
514542
}
515543

0 commit comments

Comments
 (0)