Skip to content

Commit d462b00

Browse files
authored
OSPP2: Add a stateless MCP tools entry to Agent Gateway (#7424)
* feat(agent-gateway): add a stateless MCP tools entry * test(agent-gateway): clarify and cover strict MCP Accept policy * test(agent-gateway): document and verify MCP entry contract * fix(agent-gateway): address MCP entry review feedback --------- Co-authored-by: BobSong-dev <bobsongdev@gmail.com>
1 parent 88c655e commit d462b00

50 files changed

Lines changed: 4929 additions & 33 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎RELEASE-NOTES.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66

77
### Behavior Changes
88

9+
- Agent Gateway adds opt-in tools-only MCP rules with `trafficType: "mcp"`.
10+
Enabling the plugin does not grant MCP access: deployments must supply a trusted
11+
`AgentMcpSecurityResolver` and explicitly register and authorize tools. Without
12+
a trusted identity adapter, MCP requests are denied with HTTP 401. Existing LLM
13+
forwarding and independently configured legacy MCP endpoints remain unchanged.
914
- Custom registration retry tasks should call `FailbackRegistryRepository.retry(key)`.
1015
The legacy `accept(key)` followed by `remove(key)` remains available for compatibility,
1116
but can discard a newer registration failure arriving between those calls.

‎shenyu-admin/src/main/java/org/apache/shenyu/admin/validation/validator/AgentGatewayRuleHandleValidator.java‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import com.google.gson.JsonParser;
2424
import org.apache.commons.lang3.StringUtils;
2525
import org.apache.shenyu.admin.exception.ShenyuAdminException;
26+
import org.apache.shenyu.common.dto.AgentGatewayMcpConfig;
2627

2728
import java.util.Objects;
2829
import java.util.Set;
@@ -36,7 +37,7 @@ public final class AgentGatewayRuleHandleValidator {
3637

3738
private static final String RESPONSE_REQUEST_ID = "responseRequestId";
3839

39-
private static final Set<String> SUPPORTED_FIELDS = Set.of(TRAFFIC_TYPE, RESPONSE_REQUEST_ID);
40+
private static final Set<String> SUPPORTED_FIELDS = Set.of(TRAFFIC_TYPE, RESPONSE_REQUEST_ID, "mcp");
4041

4142
private AgentGatewayRuleHandleValidator() {
4243
}
@@ -62,19 +63,28 @@ public static void validate(final String handle) {
6263
final JsonObject object = element.getAsJsonObject();
6364
for (String field : object.keySet()) {
6465
if (!SUPPORTED_FIELDS.contains(field)) {
65-
throw new ShenyuAdminException("agentGateway rule handle contains an unknown field; supported fields: trafficType, responseRequestId");
66+
throw new ShenyuAdminException("agentGateway rule handle contains an unknown field; supported fields: trafficType, responseRequestId, mcp");
6667
}
6768
}
6869
final JsonElement trafficType = object.get(TRAFFIC_TYPE);
6970
if (Objects.isNull(trafficType) || !trafficType.isJsonPrimitive() || !trafficType.getAsJsonPrimitive().isString()
70-
|| !"LLM".equals(trafficType.getAsString())) {
71-
throw new ShenyuAdminException("agentGateway trafficType must be LLM");
71+
|| !Set.of("LLM", "mcp").contains(trafficType.getAsString())) {
72+
throw new ShenyuAdminException("agentGateway trafficType must be LLM or mcp");
7273
}
7374
if (object.has(RESPONSE_REQUEST_ID)) {
7475
final JsonElement responseRequestId = object.get(RESPONSE_REQUEST_ID);
7576
if (!responseRequestId.isJsonPrimitive() || !responseRequestId.getAsJsonPrimitive().isBoolean()) {
7677
throw new ShenyuAdminException("agentGateway responseRequestId must be a boolean");
7778
}
7879
}
80+
if ("mcp".equals(trafficType.getAsString())) {
81+
try {
82+
AgentGatewayMcpConfig.parse(object.get("mcp"), true);
83+
} catch (IllegalArgumentException error) {
84+
throw new ShenyuAdminException("agentGateway " + error.getMessage());
85+
}
86+
} else if (object.has("mcp")) {
87+
throw new ShenyuAdminException("agentGateway mcp configuration requires trafficType mcp");
88+
}
7989
}
8090
}

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/service/RuleServiceTest.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,26 @@ public void testAgentGatewayUpdateRejectsUnknownHandleFieldBeforeWrite() {
243243
verify(ruleEventPublisher, never()).onUpdated(any(), any(), any(), any());
244244
}
245245

246+
@Test
247+
public void testAgentGatewayMcpRejectsNestedUnknownFieldBeforeWrite() {
248+
mockAgentGatewayPlugin();
249+
RuleDTO ruleDTO = buildRuleDTO("");
250+
ruleDTO.setHandle("{\"trafficType\":\"mcp\",\"mcp\":{\"future\":true}}");
251+
assertThrows(ShenyuAdminException.class, () -> ruleService.createOrUpdate(ruleDTO));
252+
verify(ruleMapper, never()).insertSelective(any());
253+
verify(ruleEventPublisher, never()).onCreated(any(), any());
254+
}
255+
256+
@Test
257+
public void testAgentGatewayMcpAcceptsExplicitConfiguration() {
258+
mockAgentGatewayPlugin();
259+
RuleDTO ruleDTO = buildRuleDTO("");
260+
ruleDTO.setHandle("{\"trafficType\":\"mcp\",\"mcp\":{\"allowedTools\":[\"read\"]}}");
261+
given(ruleMapper.insertSelective(any())).willReturn(1);
262+
assertEquals(1, ruleService.createOrUpdate(ruleDTO));
263+
verify(ruleEventPublisher).onCreated(any(), any());
264+
}
265+
246266
@Test
247267
public void testAgentGatewayCreateAcceptsValidHandle() {
248268
mockAgentGatewayPlugin();

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/validation/validator/AgentGatewayRuleHandleValidatorTest.java‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ public final class AgentGatewayRuleHandleValidatorTest {
3434
public void testValidHandles() {
3535
assertDoesNotThrow(() -> AgentGatewayRuleHandleValidator.validate("{\"trafficType\":\"LLM\"}"));
3636
assertDoesNotThrow(() -> AgentGatewayRuleHandleValidator.validate("{\"trafficType\":\"LLM\",\"responseRequestId\":false}"));
37+
assertDoesNotThrow(() -> AgentGatewayRuleHandleValidator.validate("{\"trafficType\":\"mcp\",\"mcp\":{}}"));
38+
assertDoesNotThrow(() -> AgentGatewayRuleHandleValidator.validate("{\"trafficType\":\"mcp\",\"mcp\":{\"allowedTools\":[\"read\"],\"responseMode\":\"sse\"}}"));
3739
}
3840

3941
@ParameterizedTest
@@ -47,7 +49,13 @@ public void testValidHandles() {
4749
"{\"trafficType\":true}",
4850
"{\"trafficType\":\"LLM\",\"responseRequestId\":\"true\"}",
4951
"{\"trafficType\":\"LLM\",\"responseRequestId\":null}",
50-
"{\"trafficType\":\"LLM\",\"extra\":42}"
52+
"{\"trafficType\":\"LLM\",\"extra\":42}",
53+
"{\"trafficType\":\"mcp\"}",
54+
"{\"trafficType\":\"mcp\",\"mcp\":null}",
55+
"{\"trafficType\":\"mcp\",\"mcp\":{\"future\":true}}",
56+
"{\"trafficType\":\"mcp\",\"mcp\":{\"timeoutMs\":0}}",
57+
"{\"trafficType\":\"mcp\",\"mcp\":{\"allowedTools\":[\"*\"]}}",
58+
"{\"trafficType\":\"LLM\",\"mcp\":{}}"
5159
})
5260
public void testInvalidHandles(final String handle) {
5361
assertThrows(ShenyuAdminException.class, () -> AgentGatewayRuleHandleValidator.validate(handle));
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.common.dto;
19+
20+
import com.google.gson.JsonElement;
21+
import com.google.gson.JsonObject;
22+
23+
import java.net.URI;
24+
import java.net.URISyntaxException;
25+
import java.util.HashSet;
26+
import java.util.Objects;
27+
import java.util.Set;
28+
29+
/**
30+
* Shared immutable MCP rule configuration for Admin and the gateway.
31+
*/
32+
public final class AgentGatewayMcpConfig {
33+
34+
private static final Set<String> FIELDS = Set.of("allowedTools", "allowedOrigins", "responseMode", "timeoutMs", "maxRequestBytes", "maxResponseBytes");
35+
36+
private final Set<String> allowedTools;
37+
38+
private final Set<String> allowedOrigins;
39+
40+
private final String responseMode;
41+
42+
private final int timeoutMs;
43+
44+
private final int maxRequestBytes;
45+
46+
private final int maxResponseBytes;
47+
48+
private AgentGatewayMcpConfig(final JsonObject object) {
49+
allowedTools = strings(object, "allowedTools", false);
50+
allowedOrigins = strings(object, "allowedOrigins", true);
51+
responseMode = text(object, "responseMode", "json");
52+
if (!Set.of("json", "sse").contains(responseMode)) {
53+
throw invalid("responseMode", "must be json or sse");
54+
}
55+
timeoutMs = integer(object, "timeoutMs", 30000, 100, 120000);
56+
maxRequestBytes = integer(object, "maxRequestBytes", 262144, 1024, 1048576);
57+
maxResponseBytes = integer(object, "maxResponseBytes", 1048576, 1024, 4194304);
58+
}
59+
60+
/**
61+
* Validate known values consistently while allowing a strict Admin boundary.
62+
*
63+
* @param element MCP configuration object
64+
* @param rejectUnknown whether to reject unknown configuration fields
65+
* @return immutable configuration snapshot
66+
*/
67+
public static AgentGatewayMcpConfig parse(final JsonElement element, final boolean rejectUnknown) {
68+
if (Objects.isNull(element) || !element.isJsonObject()) {
69+
throw new IllegalArgumentException("mcp must be an object");
70+
}
71+
JsonObject object = element.getAsJsonObject();
72+
if (rejectUnknown) {
73+
for (String field : object.keySet()) {
74+
if (!FIELDS.contains(field)) {
75+
throw new IllegalArgumentException("mcp contains an unknown field");
76+
}
77+
}
78+
}
79+
return new AgentGatewayMcpConfig(object);
80+
}
81+
82+
public Set<String> getAllowedTools() {
83+
return allowedTools;
84+
}
85+
86+
public Set<String> getAllowedOrigins() {
87+
return allowedOrigins;
88+
}
89+
90+
public String getResponseMode() {
91+
return responseMode;
92+
}
93+
94+
public int getTimeoutMs() {
95+
return timeoutMs;
96+
}
97+
98+
public int getMaxRequestBytes() {
99+
return maxRequestBytes;
100+
}
101+
102+
public int getMaxResponseBytes() {
103+
return maxResponseBytes;
104+
}
105+
106+
private Set<String> strings(final JsonObject object, final String field, final boolean origins) {
107+
if (!object.has(field)) {
108+
return Set.of();
109+
}
110+
JsonElement element = object.get(field);
111+
if (!element.isJsonArray()) {
112+
throw invalid(field, "must be an array");
113+
}
114+
Set<String> result = new HashSet<>();
115+
for (JsonElement entry : element.getAsJsonArray()) {
116+
if (!entry.isJsonPrimitive() || !entry.getAsJsonPrimitive().isString()) {
117+
throw invalid(field, "must contain strings");
118+
}
119+
String value = entry.getAsString();
120+
if (value.isBlank() || "*".equals(value) || !value.equals(value.trim()) || !result.add(value)) {
121+
throw invalid(field, "must contain unique explicit nonblank values");
122+
}
123+
if (origins && !isOrigin(value)) {
124+
throw invalid(field, "must contain exact HTTP origins without paths or credentials");
125+
}
126+
}
127+
return Set.copyOf(result);
128+
}
129+
130+
private boolean isOrigin(final String value) {
131+
try {
132+
URI origin = new URI(value);
133+
return Objects.nonNull(origin.getScheme()) && Set.of("http", "https").contains(origin.getScheme()) && Objects.nonNull(origin.getHost())
134+
&& Objects.isNull(origin.getRawUserInfo()) && Objects.isNull(origin.getRawQuery()) && Objects.isNull(origin.getRawFragment())
135+
&& (Objects.isNull(origin.getRawPath()) || origin.getRawPath().isEmpty())
136+
&& origin.getPort() >= -1 && origin.getPort() <= 65535;
137+
} catch (URISyntaxException error) {
138+
return false;
139+
}
140+
}
141+
142+
private String text(final JsonObject object, final String field, final String defaultValue) {
143+
if (!object.has(field)) {
144+
return defaultValue;
145+
}
146+
JsonElement value = object.get(field);
147+
if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
148+
throw invalid(field, "must be a string");
149+
}
150+
return value.getAsString();
151+
}
152+
153+
private int integer(final JsonObject object, final String field, final int defaultValue, final int minimum, final int maximum) {
154+
if (!object.has(field)) {
155+
return defaultValue;
156+
}
157+
JsonElement value = object.get(field);
158+
if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isNumber()) {
159+
throw invalid(field, "must be an integer");
160+
}
161+
try {
162+
int number = value.getAsBigDecimal().intValueExact();
163+
if (number < minimum || number > maximum) {
164+
throw invalid(field, "is outside its allowed range");
165+
}
166+
return number;
167+
} catch (ArithmeticException | NumberFormatException error) {
168+
throw invalid(field, "must be an integer within its allowed range");
169+
}
170+
}
171+
172+
private IllegalArgumentException invalid(final String field, final String message) {
173+
return new IllegalArgumentException("mcp." + field + " " + message);
174+
}
175+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
19+
package org.apache.shenyu.common.dto;
20+
21+
import com.google.gson.JsonObject;
22+
import com.google.gson.JsonParser;
23+
import org.junit.jupiter.api.Test;
24+
import org.junit.jupiter.params.ParameterizedTest;
25+
import org.junit.jupiter.params.provider.ValueSource;
26+
27+
import java.util.Set;
28+
29+
import static org.junit.jupiter.api.Assertions.assertEquals;
30+
import static org.junit.jupiter.api.Assertions.assertThrows;
31+
32+
/**
33+
* Shared rule configuration validation and immutable default contract.
34+
*/
35+
class AgentGatewayMcpConfigTest {
36+
37+
@Test
38+
void shouldDefaultToNoToolsAndBoundedJson() {
39+
AgentGatewayMcpConfig config = parse("{}");
40+
assertEquals(Set.of(), config.getAllowedTools());
41+
assertEquals(Set.of(), config.getAllowedOrigins());
42+
assertEquals("json", config.getResponseMode());
43+
assertEquals(30000, config.getTimeoutMs());
44+
assertEquals(262144, config.getMaxRequestBytes());
45+
assertEquals(1048576, config.getMaxResponseBytes());
46+
}
47+
48+
@Test
49+
void shouldFreezeExplicitSetsAndAcceptBounds() {
50+
JsonObject source = JsonParser.parseString("{\"allowedTools\":[\"read\"],\"allowedOrigins\":[\"https://example.com\"],"
51+
+ "\"responseMode\":\"sse\",\"timeoutMs\":100,\"maxRequestBytes\":1024,\"maxResponseBytes\":4194304}").getAsJsonObject();
52+
AgentGatewayMcpConfig config = AgentGatewayMcpConfig.parse(source, true);
53+
source.getAsJsonArray("allowedTools").add("write");
54+
assertEquals(Set.of("read"), config.getAllowedTools());
55+
assertThrows(UnsupportedOperationException.class, () -> config.getAllowedTools().add("write"));
56+
assertEquals("sse", config.getResponseMode());
57+
assertEquals(100, config.getTimeoutMs());
58+
assertEquals(1024, config.getMaxRequestBytes());
59+
assertEquals(4194304, config.getMaxResponseBytes());
60+
AgentGatewayMcpConfig upper = parse("{\"timeoutMs\":120000,\"maxRequestBytes\":1048576,\"maxResponseBytes\":1024}");
61+
assertEquals(120000, upper.getTimeoutMs());
62+
assertEquals(1048576, upper.getMaxRequestBytes());
63+
}
64+
65+
@Test
66+
void shouldRejectUnknownOnlyAtAdminBoundary() {
67+
JsonObject object = JsonParser.parseString("{\"future\":true}").getAsJsonObject();
68+
assertThrows(IllegalArgumentException.class, () -> AgentGatewayMcpConfig.parse(object, true));
69+
assertEquals(Set.of(), AgentGatewayMcpConfig.parse(object, false).getAllowedTools());
70+
}
71+
72+
@ParameterizedTest
73+
@ValueSource(strings = {
74+
"null", "[]", "{\"allowedTools\":null}", "{\"allowedTools\":\"read\"}", "{\"allowedTools\":[null]}",
75+
"{\"allowedTools\":[\"*\"]}", "{\"allowedTools\":[\" \" ]}", "{\"allowedTools\":[\"read\",\"read\"]}",
76+
"{\"allowedOrigins\":[\"null\"]}", "{\"allowedOrigins\":[\"https://example.com/\"]}",
77+
"{\"allowedOrigins\":[\"https://user@example.com\"]}", "{\"allowedOrigins\":[\"https://example.com?x=1\"]}",
78+
"{\"allowedOrigins\":[\"ftp://example.com\"]}", "{\"responseMode\":\"stream\"}", "{\"responseMode\":null}",
79+
"{\"timeoutMs\":99}", "{\"timeoutMs\":120001}", "{\"timeoutMs\":1.5}", "{\"timeoutMs\":\"100\"}",
80+
"{\"timeoutMs\":1e30}", "{\"timeoutMs\":null}", "{\"maxRequestBytes\":1023}", "{\"maxRequestBytes\":1048577}",
81+
"{\"maxResponseBytes\":1023}", "{\"maxResponseBytes\":4194305}"
82+
})
83+
void shouldRejectInvalidKnownValues(final String source) {
84+
assertThrows(IllegalArgumentException.class, () -> parse(source));
85+
}
86+
87+
private AgentGatewayMcpConfig parse(final String source) {
88+
return AgentGatewayMcpConfig.parse(JsonParser.parseString(source), true);
89+
}
90+
}

0 commit comments

Comments
 (0)