feat(mcp): 统一输出规范与错误码体系——schema_version 双跑信封 + 8 错误码收敛 + 工具只读声明 + 日志脱敏 (REQ-20260911-0011)

This commit is contained in:
xiaoqu
2026-09-11 22:48:14 +08:00
parent 5daecc8ae8
commit f2ac17731a
20 changed files with 1070 additions and 25 deletions
@@ -0,0 +1,35 @@
package me.iiv.agent.common;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class MaskingUtilTest {
@Test
void masksMobilePhoneKeepingHeadAndTail() {
assertEquals("{\"phone\":\"138****8000\"}",
MaskingUtil.maskPhones("{\"phone\":\"13800138000\"}"));
}
@Test
void masksMultiplePhonesInOneText() {
assertEquals("139****1111 或 137****2222",
MaskingUtil.maskPhones("13900001111 或 13700002222"));
}
@Test
void leavesNonPhoneDigitsUntouched() {
assertEquals("id=123456 rows=100", MaskingUtil.maskPhones("id=123456 rows=100"));
// 12 位、非 1[3-9] 号段不误伤
assertEquals("123456789012", MaskingUtil.maskPhones("123456789012"));
assertEquals("10800138000", MaskingUtil.maskPhones("10800138000"));
}
@Test
void nullAndEmptyPassThrough() {
assertNull(MaskingUtil.maskPhones(null));
assertEquals("", MaskingUtil.maskPhones(""));
}
}
@@ -0,0 +1,156 @@
package me.iiv.agent.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.common.AuditService;
import me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.AuthContextHolder;
import me.iiv.agent.security.ToolGuard;
import org.apache.ibatis.exceptions.PersistenceException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.definition.DefaultToolDefinition;
import org.springframework.ai.tool.definition.ToolDefinition;
import org.springframework.ai.tool.execution.ToolExecutionException;
import org.springframework.dao.DataAccessResourceFailureException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class GuardedToolCallbackTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Mock
ToolCallback delegate;
@Mock
ToolGuard toolGuard;
@Mock
AuditService auditService;
GuardedToolCallback callback;
ToolDefinition toolDefinition;
@BeforeEach
void setUp() {
toolDefinition = DefaultToolDefinition.builder()
.name("agent.count").description("d").inputSchema("{}").build();
when(delegate.getToolDefinition()).thenReturn(toolDefinition);
callback = new GuardedToolCallback(delegate, toolGuard, auditService);
AgentApiKey token = new AgentApiKey();
token.setId(42L);
AuthContextHolder.set(new AuthContext(token, null));
}
@AfterEach
void tearDown() {
AuthContextHolder.clear();
McpCallContextHolder.clear();
}
private static JsonNode errorOf(ToolCallException e) throws Exception {
return MAPPER.readTree(e.getMessage()).path("error");
}
@Test
void successResultPassesThroughUnchanged() {
when(toolGuard.isAllowed(42L, "agent.count")).thenReturn(true);
when(delegate.call("{}")).thenReturn("{\"count\":62}");
String result = callback.call("{}");
assertEquals("{\"count\":62}", result, "成功路径(v1 兼容面)不得被改写");
verify(auditService).record(any(), eq("agent.count"), eq("{}"), eq("success"),
org.mockito.ArgumentMatchers.isNull(), anyLong());
}
@Test
void missingAuthContextMapsToUnauthenticated() throws Exception {
AuthContextHolder.clear();
ToolCallException e = assertThrows(ToolCallException.class, () -> callback.call("{}"));
assertEquals(McpErrorCode.UNAUTHENTICATED, e.getCode());
assertEquals("UNAUTHENTICATED", errorOf(e).path("code").asText());
}
@Test
void scopeDeniedMapsToPermissionDenied() throws Exception {
when(toolGuard.isAllowed(42L, "agent.count")).thenReturn(false);
ToolCallException e = assertThrows(ToolCallException.class, () -> callback.call("{}"));
assertEquals(McpErrorCode.PERMISSION_DENIED, e.getCode());
JsonNode error = errorOf(e);
assertEquals("PERMISSION_DENIED", error.path("code").asText());
assertTrue(error.path("message").asText().contains("agent.count"));
assertFalse(error.path("request_id").asText().isBlank(), "错误负载必须带 request_id");
verify(auditService).record(any(), eq("agent.count"), eq("{}"), eq("denied"),
anyString(), anyLong());
}
@Test
void dataAccessFailureMapsToUpstreamUnavailableWithoutRawDetails() throws Exception {
when(toolGuard.isAllowed(42L, "agent.count")).thenReturn(true);
when(delegate.call("{}")).thenThrow(new ToolExecutionException(
toolDefinition,
new DataAccessResourceFailureException("connection to 192.168.1.181:3306 refused")));
ToolCallException e = assertThrows(ToolCallException.class, () -> callback.call("{}"));
assertEquals(McpErrorCode.UPSTREAM_UNAVAILABLE, e.getCode());
JsonNode error = errorOf(e);
assertFalse(error.path("message").asText().contains("192.168"), "不得泄露内部地址等细节");
}
@Test
void unexpectedExceptionMapsToDataIntegrityErrorWithoutRawDetails() throws Exception {
when(toolGuard.isAllowed(42L, "agent.count")).thenReturn(true);
when(delegate.call("{}")).thenThrow(new ToolExecutionException(
toolDefinition, new IllegalStateException("用户 13812345678 数据异常")));
ToolCallException e = assertThrows(ToolCallException.class, () -> callback.call("{}"));
assertEquals(McpErrorCode.DATA_INTEGRITY_ERROR, e.getCode());
JsonNode error = errorOf(e);
assertFalse(error.path("message").asText().contains("13812345678"), "裸异常信息不得透出");
assertEquals("工具执行失败,请携带 request_id 联系运维排查", error.path("message").asText());
}
@Test
void persistenceExceptionMapsToUpstreamUnavailable() throws Exception {
when(toolGuard.isAllowed(42L, "agent.count")).thenReturn(true);
when(delegate.call("{}")).thenThrow(new ToolExecutionException(
toolDefinition, new PersistenceException("sql failed")));
ToolCallException e = assertThrows(ToolCallException.class, () -> callback.call("{}"));
assertEquals(McpErrorCode.UPSTREAM_UNAVAILABLE, e.getCode());
}
@Test
void errorRequestIdComesFromCallContext() throws Exception {
McpCallContextHolder.setRequestId("req-fixed");
when(toolGuard.isAllowed(42L, "agent.count")).thenReturn(false);
ToolCallException e = assertThrows(ToolCallException.class, () -> callback.call("{}"));
assertEquals("req-fixed", errorOf(e).path("request_id").asText(),
"过滤器生成的 request_id 必须贯穿到错误负载");
}
}
@@ -0,0 +1,66 @@
package me.iiv.agent.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class McpEnvelopeTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@AfterEach
void tearDown() {
McpCallContextHolder.clear();
}
@Test
void absentHeaderDefaultsToLegacyVersion() {
assertEquals(1, McpEnvelope.parseSchemaVersion(null, "r1"));
assertEquals(1, McpEnvelope.parseSchemaVersion("", "r1"));
assertEquals(1, McpEnvelope.parseSchemaVersion(" ", "r1"));
assertEquals(1, McpEnvelope.parseSchemaVersion("1", "r1"));
assertEquals(2, McpEnvelope.parseSchemaVersion("2", "r1"));
assertEquals(2, McpEnvelope.parseSchemaVersion(" 2 ", "r1"));
}
@Test
void unsupportedVersionRejectedWithUnifiedCode() {
ToolCallException e = assertThrows(ToolCallException.class,
() -> McpEnvelope.parseSchemaVersion("3", "r1"));
assertEquals(McpErrorCode.SCHEMA_VERSION_UNSUPPORTED, e.getCode());
assertTrue(e.getMessage().contains("SCHEMA_VERSION_UNSUPPORTED"));
assertTrue(e.getMessage().contains("\"request_id\":\"r1\""));
}
@Test
void successEnvelopeCarriesVersionRequestIdAndData() throws Exception {
JsonNode data = MAPPER.readTree("{\"count\":62}");
JsonNode envelope = McpEnvelope.successEnvelope(data, "req-1");
assertEquals(2, envelope.path("schema_version").asInt());
assertEquals("req-1", envelope.path("request_id").asText());
assertEquals(62, envelope.path("data").path("count").asInt());
}
@Test
void errorPayloadIsStructuredJson() throws Exception {
String payload = McpEnvelope.errorPayload(McpErrorCode.PERMISSION_DENIED, "denied", "req-9");
JsonNode error = MAPPER.readTree(payload).path("error");
assertEquals("PERMISSION_DENIED", error.path("code").asText());
assertEquals("denied", error.path("message").asText());
assertEquals("req-9", error.path("request_id").asText());
}
@Test
void envelopeOutputSchemaCoversAllErrorCodes() {
JsonNode schema = McpEnvelope.envelopeOutputSchema();
assertEquals("object", schema.path("type").asText());
JsonNode codeEnum = schema.path("properties").path("error")
.path("properties").path("code").path("enum");
assertEquals(McpErrorCode.values().length, codeEnum.size());
}
}
@@ -0,0 +1,96 @@
package me.iiv.agent.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ToolCallEnvelopeRewriterTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static String callResultJson(boolean isError, String text) {
return "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":{\"isError\":" + isError
+ ",\"content\":[{\"type\":\"text\",\"text\":" + jsonQuote(text) + "}]}}";
}
private static String jsonQuote(String raw) {
try {
return MAPPER.writeValueAsString(raw);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static JsonNode resultOf(String body) throws Exception {
String data = null;
for (String line : body.split("\\n")) {
if (line.startsWith("data:")) {
data = line.substring(5);
}
}
return MAPPER.readTree(data == null ? body : data).path("result");
}
@Test
void successResultGetsStructuredContentEnvelope() throws Exception {
String body = "id:evt-1\nevent:message\ndata:" + callResultJson(false, "{\"count\":62}") + "\n\n";
String rewritten = ToolCallEnvelopeRewriter.rewrite(body, "req-1");
JsonNode result = resultOf(rewritten);
JsonNode envelope = result.path("structuredContent");
assertEquals(2, envelope.path("schema_version").asInt());
assertEquals("req-1", envelope.path("request_id").asText());
assertEquals(62, envelope.path("data").path("count").asInt());
// content text 保持原样(v1 兼容面不变)
assertEquals("{\"count\":62}", result.path("content").get(0).path("text").asText());
assertTrue(rewritten.startsWith("id:evt-1\nevent:message\n"), "SSE 元信息行需保留");
assertTrue(rewritten.endsWith("\n\n"), "事件末尾空行需保留");
}
@Test
void errorResultGetsUnifiedErrorEnvelope() throws Exception {
String errorPayload = McpEnvelope.errorPayload(McpErrorCode.PERMISSION_DENIED, "denied", "req-1");
String body = callResultJson(true, errorPayload);
String rewritten = ToolCallEnvelopeRewriter.rewrite(body, "req-1");
JsonNode envelope = resultOf(rewritten).path("structuredContent");
assertEquals("PERMISSION_DENIED", envelope.path("error").path("code").asText());
assertEquals("denied", envelope.path("error").path("message").asText());
assertFalse(envelope.has("data"));
}
@Test
void nonJsonErrorTextFallsBackToDataIntegrityError() throws Exception {
String body = callResultJson(true, "For input string: \"abc\"");
String rewritten = ToolCallEnvelopeRewriter.rewrite(body, "req-2");
JsonNode envelope = resultOf(rewritten).path("structuredContent");
assertEquals("DATA_INTEGRITY_ERROR", envelope.path("error").path("code").asText());
// 兜底错误不透出原始异常文本
assertFalse(envelope.path("error").path("message").asText().contains("abc"));
}
@Test
void plainJsonResponseIsAlsoEnveloped() throws Exception {
String body = callResultJson(false, "{\"count\":1}");
String rewritten = ToolCallEnvelopeRewriter.rewrite(body, "req-3");
assertEquals(1, resultOf(rewritten).path("structuredContent").path("data").path("count").asInt());
}
@Test
void nonToolCallPayloadsPassThroughUnchanged() {
String init = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2025-03-26\"}}";
assertEquals(init, ToolCallEnvelopeRewriter.rewrite(init, "req-4"));
String garbage = "not-json-not-sse";
assertEquals(garbage, ToolCallEnvelopeRewriter.rewrite(garbage, "req-4"));
}
}
@@ -85,4 +85,34 @@ class ToolsListResponseRewriterTest {
String garbage = "not-json-not-sse";
assertEquals(garbage, ToolsListResponseRewriter.rewrite(garbage, Set.of("a")));
}
@Test
void injectsReadOnlyAnnotationsIntoKeptTools() throws Exception {
String body = toolsJson("agent.count");
String rewritten = ToolsListResponseRewriter.rewrite(body, Set.of("agent.count"),
name -> java.util.Map.of("readOnlyHint", true, "idempotentHint", true,
"destructiveHint", false, "openWorldHint", false), false);
JsonNode tool = MAPPER.readTree(rewritten).path("result").path("tools").get(0);
JsonNode annotations = tool.path("annotations");
assertTrue(annotations.path("readOnlyHint").asBoolean());
assertTrue(annotations.path("idempotentHint").asBoolean());
assertEquals(false, annotations.path("destructiveHint").asBoolean());
}
@Test
void injectsEnvelopeOutputSchemaOnlyWhenV2Declared() throws Exception {
String body = toolsJson("agent.count");
String v2 = ToolsListResponseRewriter.rewrite(body, Set.of("agent.count"), null, true);
JsonNode schema = MAPPER.readTree(v2).path("result").path("tools").get(0).path("outputSchema");
assertEquals("object", schema.path("type").asText());
assertTrue(schema.path("properties").has("schema_version"));
assertTrue(schema.path("properties").has("request_id"));
String v1 = ToolsListResponseRewriter.rewrite(body, Set.of("agent.count"), null, false);
assertTrue(MAPPER.readTree(v1).path("result").path("tools").get(0)
.path("outputSchema").isMissingNode(), "默认版本不得出现 outputSchema");
}
}