diff --git a/docs/agent-gateway-controlled-mcp-https.md b/docs/agent-gateway-controlled-mcp-https.md
new file mode 100644
index 000000000000..465d3808b87c
--- /dev/null
+++ b/docs/agent-gateway-controlled-mcp-https.md
@@ -0,0 +1,44 @@
+# Controlled MCP HTTPS routes
+
+Agent Gateway remote MCP targets remain deployment-controlled. Fixed-IP HTTPS keeps
+its historical behavior. A DNS hostname may be used only when deployment properties
+also approve the exact hostname, port, path, and IPv4 address that the transport may
+connect to.
+
+## Deployment configuration
+
+Set `shenyu.plugins.agent.gateway.aggregation.allowed-routes` to comma-separated
+`endpoint=approvedIPv4` entries, for example:
+
+```properties
+shenyu.plugins.agent.gateway.aggregation.allowed-routes=https://mcp.example.com:443/mcp=203.0.113.10,https://192.0.2.20:8443/mcp=
+```
+
+Existing fixed-IP deployments may continue to use the historical comma-separated
+`allowed-endpoints` property. At least one approved fixed endpoint or controlled
+route is required when aggregation is enabled.
+
+An empty address is valid only for a fixed-IP endpoint. A hostname without an address
+is rejected. Admin plugin configuration still selects a configured endpoint and its
+target-bound credential; it cannot add routes, alter approved addresses, or expand TLS
+policy.
+
+## Connection and credential semantics
+
+- The transport uses the original HTTPS hostname for DNS-independent route identity,
+ SNI, and certificate hostname validation, but connects to the approved IPv4 address.
+ This prevents an implicit JVM DNS lookup from bypassing route policy.
+- Each target and credential version receives its own bounded pooled client. A
+ configuration refresh retires the old generation immediately for new requests, while
+ an already acquired in-flight generation remains bound to its prior credential and
+ client. Its client is closed after the last lease is released.
+- Redirects, cookies, authentication caching, connection state, and proxy use remain
+ disabled. Untrusted certificates, hostname mismatches, missing routes, and changed
+ destinations fail closed.
+- Route or credential replacement does not roll back a remote side effect performed by
+ an in-flight request. Emergency revocation stops new requests and closes the old
+ client after its leases drain.
+
+Dynamic DNS refresh, service discovery refresh, IPv6, delegated OAuth, and enterprise
+proxies remain outside this contract. Coordinate dynamic resolution with the remote
+directory refresh work rather than adding a second discovery system here.
diff --git a/docs/agent-gateway-resource-admission.md b/docs/agent-gateway-resource-admission.md
new file mode 100644
index 000000000000..95d7bbe8a828
--- /dev/null
+++ b/docs/agent-gateway-resource-admission.md
@@ -0,0 +1,43 @@
+# Agent Gateway resource admission
+
+Agent Gateway applies deterministic admission around every `tools/call` execution. Admission is deliberately not a retry or circuit-breaking layer: a call still executes at most once.
+
+## Configuration
+
+The trusted plugin configuration may contain one `admission` object:
+
+```json
+{
+ "admission": {
+ "globalInFlight": 128,
+ "globalQueued": 64,
+ "localInFlight": 32,
+ "localQueued": 16,
+ "remoteInFlight": 8,
+ "remoteQueued": 16
+ }
+}
+```
+
+Omitting the object or supplying an empty object selects these defaults. Admin and gateway reject unknown fields and values outside the hard maxima (`128`, `256`, `64`, `128`, `32`, and `128` respectively).
+
+## Semantics
+
+- `global*` bounds all concurrent local and remote tool executions and their waiting work.
+- `local*` bounds startup and request-local HTTP tool providers together.
+- `remote*` is applied independently for each configured remote MCP server name.
+- Admission checks the absolute request deadline before granting each global/local/remote permit, before reporting queue overflow, and immediately before subscribing to execution. An already-expired request never executes its provider, even with free capacity. Time spent waiting counts against execution time.
+- Queue overflow returns HTTP `429` and JSON-RPC `-32026`; an expired request returns HTTP `504` and `-32026`.
+- Every success, business error, gateway error, cancellation, timeout, configuration withdrawal and shutdown releases each acquired permit once.
+- Local validation runs before resource admission. The execution-attempt callback and provider invocation run only when the admitted action is subscribed. Overload, queue timeout and cancellation before admission produce no execution-attempt audit record; their logical terminal record remains available.
+- Existing byte limits, transport concurrency, catalog generation leases and no-retry behavior remain in force.
+
+Configuration reload preserves active and queued accounting. All scope limits are installed before newly available slots are drained. Reload draining, terminal release and shutdown follow the same controller-promotion-monitor then scope-monitor order, including synchronous completion of promoted actions. Remote scope collections are copied under their registry monitor before callbacks or snapshot reads acquire scope monitors.
+
+## Metrics
+
+The Prometheus exporter publishes payload-free aggregates by fixed scope (`global`, `local`, `remote`): `shenyu_agent_admission_inflight`, `shenyu_agent_admission_queued`, `shenyu_agent_admission_inflight_limit`, `shenyu_agent_admission_queue_limit` and `shenyu_agent_admission_rejections_total`. Tool names, subjects, tenants and endpoints are never labels.
+
+## Sizing guidance
+
+Keep the global budget at or below the gateway process's sustainable CPU and response-memory budget. Reserve a separate remote in-flight budget for each latency-critical MCP server, and keep remote queues small: queued remote calls consume a shared global slot while waiting. Increase queue sizes only when clients can tolerate waiting until the existing request deadline; admission does not extend deadlines.
diff --git a/pom.xml b/pom.xml
index 230113de8d1a..fb4d0ca2e9da 100644
--- a/pom.xml
+++ b/pom.xml
@@ -801,6 +801,11 @@
caffeine
${caffeine.version}
+
+ org.apache.httpcomponents
+ httpasyncclient
+ ${httpasyncclient.version}
+
com.netflix.eureka
diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java
new file mode 100644
index 000000000000..2f25a72fec28
--- /dev/null
+++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.common.dto;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.Objects;
+
+/**
+ * Strict fixed resource-admission limits shared by Admin and the gateway.
+ */
+public record AgentGatewayAdmissionConfig(int globalInFlight, int globalQueued,
+ int localInFlight, int localQueued,
+ int remoteInFlight, int remoteQueued) {
+
+ private static final AgentGatewayAdmissionConfig DEFAULT = new AgentGatewayAdmissionConfig(128, 64, 32, 16, 8, 16);
+
+ public AgentGatewayAdmissionConfig {
+ range("globalInFlight", globalInFlight, 1, 128);
+ range("globalQueued", globalQueued, 0, 256);
+ range("localInFlight", localInFlight, 1, 64);
+ range("localQueued", localQueued, 0, 128);
+ range("remoteInFlight", remoteInFlight, 1, 32);
+ range("remoteQueued", remoteQueued, 0, 128);
+ }
+
+ /**
+ * Parse the optional trusted plugin field. Null selects safe operational defaults.
+ * @param node admission object from plugin configuration
+ * @return immutable admission limits
+ */
+ public static AgentGatewayAdmissionConfig parse(final JsonNode node) {
+ if (Objects.isNull(node)) {
+ return DEFAULT;
+ }
+ if (!node.isObject() || node.isEmpty()) {
+ return DEFAULT;
+ }
+ java.util.Set fields = new java.util.HashSet<>();
+ node.fieldNames().forEachRemaining(fields::add);
+ if (!fields.equals(java.util.Set.of("globalInFlight", "globalQueued", "localInFlight",
+ "localQueued", "remoteInFlight", "remoteQueued"))) {
+ throw new IllegalArgumentException("Unknown or missing admission field");
+ }
+ return new AgentGatewayAdmissionConfig(number(node, "globalInFlight"), number(node, "globalQueued"),
+ number(node, "localInFlight"), number(node, "localQueued"),
+ number(node, "remoteInFlight"), number(node, "remoteQueued"));
+ }
+
+ private static int number(final JsonNode node, final String field) {
+ if (!node.path(field).isInt()) {
+ throw new IllegalArgumentException("Admission field must be an integer");
+ }
+ return node.get(field).asInt();
+ }
+
+ private static void range(final String field, final int value, final int minimum, final int maximum) {
+ if (value < minimum || value > maximum) {
+ throw new IllegalArgumentException("Admission field is outside its hard maximum: " + field);
+ }
+ }
+}
diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java
index b36353785f1f..c66b9cbd64bd 100644
--- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java
+++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java
@@ -31,11 +31,13 @@
import java.util.Set;
/** Strict, secret-free configuration shared by Admin and gateway. */
-public record AgentGatewayAggregationConfig(String revision, List servers) {
+public record AgentGatewayAggregationConfig(String revision, List servers, AgentGatewayAdmissionConfig admission) {
private static final ObjectMapper JSON = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+ private static final AgentGatewayAdmissionConfig DEFAULT_ADMISSION = AgentGatewayAdmissionConfig.parse(null);
+
public AgentGatewayAggregationConfig {
if (Objects.isNull(revision) || !revision.matches("[A-Za-z0-9_-]{1,48}")) {
throw new IllegalArgumentException("Invalid aggregation revision");
@@ -53,7 +55,7 @@ public record AgentGatewayAggregationConfig(String revision, List server
*/
public static AgentGatewayAggregationConfig parsePluginConfig(final String source) {
if (Objects.isNull(source) || source.isBlank()) {
- return new AgentGatewayAggregationConfig("empty", List.of());
+ return new AgentGatewayAggregationConfig("empty", List.of(), DEFAULT_ADMISSION);
}
if (source.getBytes(StandardCharsets.UTF_8).length > 16384) {
throw new IllegalArgumentException("Aggregation configuration byte limit");
@@ -64,9 +66,18 @@ public static AgentGatewayAggregationConfig parsePluginConfig(final String sourc
throw new IllegalArgumentException("Expected plugin configuration object");
}
if (root.isEmpty()) {
- return new AgentGatewayAggregationConfig("empty", List.of());
+ return new AgentGatewayAggregationConfig("empty", List.of(), DEFAULT_ADMISSION);
+ }
+ boolean hasAggregation = root.has("aggregation");
+ Set pluginFields = new HashSet<>(hasAggregation ? Set.of("aggregation") : Set.of());
+ if (root.has("admission")) {
+ pluginFields.add("admission");
+ }
+ fields(root, pluginFields);
+ if (!hasAggregation) {
+ return new AgentGatewayAggregationConfig("empty", List.of(),
+ AgentGatewayAdmissionConfig.parse(root.get("admission")));
}
- fields(root, Set.of("aggregation"));
JsonNode aggregation = root.get("aggregation");
fields(aggregation, Set.of("revision", "servers"));
if (!aggregation.path("servers").isArray()) {
@@ -78,7 +89,8 @@ public static AgentGatewayAggregationConfig parsePluginConfig(final String sourc
servers.add(new Server(text(server, "name"), URI.create(text(server, "endpoint")),
text(server, "credentialRef"), text(server, "credentialVersion")));
}
- return new AgentGatewayAggregationConfig(text(aggregation, "revision"), servers);
+ return new AgentGatewayAggregationConfig(text(aggregation, "revision"), servers,
+ AgentGatewayAdmissionConfig.parse(root.get("admission")));
} catch (Exception error) {
// Do not include raw config or a parse exception which could contain a supplied secret.
throw new IllegalArgumentException("Invalid Agent Gateway aggregation configuration");
@@ -97,10 +109,25 @@ private static void fields(final JsonNode node, final Set expected) {
}
/**
- * Validate the agreed fixed-IP transport boundary at both Admin and gateway.
+ * Validate a fixed IP or an explicitly controlled HTTPS hostname at Admin and gateway.
* @param endpoint exact configured endpoint, never an Agent-supplied URL
*/
public static void validateEndpoint(final URI endpoint) {
+ if (Objects.isNull(endpoint) || Objects.isNull(endpoint.getHost())) {
+ throw new IllegalArgumentException("Invalid MCP Server endpoint");
+ }
+ if (endpoint.getHost().matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}")) {
+ validateFixedEndpoint(endpoint);
+ return;
+ }
+ validateHttpsHostnameEndpoint(endpoint);
+ }
+
+ /**
+ * Validate the historical fixed-IP transport boundary.
+ * @param endpoint exact configured endpoint, never an Agent-supplied URL
+ */
+ public static void validateFixedEndpoint(final URI endpoint) {
if (Objects.isNull(endpoint) || Objects.isNull(endpoint.getHost()) || !literalIpv4(endpoint.getHost())
|| !("https".equals(endpoint.getScheme()) || "http".equals(endpoint.getScheme()) && "127.0.0.1".equals(endpoint.getHost()))
|| endpoint.getPort() < 1 || endpoint.getPort() > 65535 || Objects.nonNull(endpoint.getRawUserInfo())
@@ -108,6 +135,32 @@ public static void validateEndpoint(final URI endpoint) {
|| !endpoint.normalize().equals(endpoint) || !endpoint.getRawPath().matches("/(?:[A-Za-z0-9._~-]+/)*[A-Za-z0-9._~-]+")) {
throw new IllegalArgumentException("Invalid fixed-IP MCP Server endpoint");
}
+ validatePath(endpoint);
+ }
+
+ /**
+ * Validate an HTTPS hostname target without resolving or approving its address.
+ * @param endpoint exact configured endpoint, never an Agent-supplied URL
+ */
+ public static void validateHttpsHostnameEndpoint(final URI endpoint) {
+ validateHttpsHostnameShape(endpoint);
+ }
+
+ private static void validateHttpsHostnameShape(final URI endpoint) {
+ if (Objects.isNull(endpoint) || Objects.isNull(endpoint.getHost()) || !endpoint.getHost().matches("(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.){0,5}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
+ || endpoint.getHost().length() > 253 || !"https".equals(endpoint.getScheme())
+ || endpoint.getPort() < 1 || endpoint.getPort() > 65535 || Objects.nonNull(endpoint.getRawUserInfo())
+ || Objects.nonNull(endpoint.getRawQuery()) || Objects.nonNull(endpoint.getRawFragment())
+ || !endpoint.normalize().equals(endpoint)) {
+ throw new IllegalArgumentException("Invalid controlled HTTPS hostname endpoint");
+ }
+ validatePath(endpoint);
+ }
+
+ private static void validatePath(final URI endpoint) {
+ if (Objects.isNull(endpoint.getRawPath()) || !endpoint.getRawPath().matches("/(?:[A-Za-z0-9._~-]+/)*[A-Za-z0-9._~-]+")) {
+ throw new IllegalArgumentException("Invalid MCP Server endpoint path");
+ }
for (String part : endpoint.getRawPath().split("/")) {
if (Set.of(".", "..").contains(part)) {
throw new IllegalArgumentException("Ambiguous MCP endpoint");
diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java
new file mode 100644
index 000000000000..4c87eccb4bf7
--- /dev/null
+++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.common.metrics;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+
+/** Live payload-free admission snapshots, without tool, subject, tenant, or endpoint labels. */
+public final class AgentAdmissionMetrics implements AutoCloseable {
+
+ private static final Set SOURCES = ConcurrentHashMap.newKeySet();
+
+ private final Supplier> source;
+
+ private AgentAdmissionMetrics(final Supplier> source) {
+ this.source = source;
+ }
+
+ /**
+ * Register one controller after startup; the controller owns this registration.
+ * @param source in-memory snapshot supplier
+ * @return registration removed by close
+ */
+ public static AgentAdmissionMetrics register(final Supplier> source) {
+ AgentAdmissionMetrics value = new AgentAdmissionMetrics(source);
+ SOURCES.add(value);
+ return value;
+ }
+
+ /** Aggregate all live controller states.
+ * @return immutable snapshots
+ */
+ public static List snapshots() {
+ return SOURCES.stream().flatMap(registration -> {
+ try {
+ return registration.source.get().stream();
+ } catch (RuntimeException ignored) {
+ return java.util.stream.Stream.empty();
+ }
+ }).toList();
+ }
+
+ @Override
+ public void close() {
+ SOURCES.remove(this);
+ }
+
+ /** One bounded scope; names never carry request or target identity. */
+ public record Snapshot(Scope scope, int inFlight, int queued, int inFlightLimit, int queueLimit, long rejected) {
+ }
+
+ /** Fixed admission scopes, safe as metric labels. */
+ public enum Scope {
+ GLOBAL, LOCAL, REMOTE
+ }
+}
diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java
index c8dc0df61f61..d8505da26799 100644
--- a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java
+++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java
@@ -33,6 +33,7 @@
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -41,7 +42,8 @@ class AgentInvocationAuditBridgeTest {
@Test
void reusesTerminalIdempotenceAndKeepsAttemptIdentity() {
List records = new CopyOnWriteArrayList<>();
- AiRequestObservation observation = new AiRequestObservation(AgentInvocationAuditBridge.ai(null, records::add), context("one"));
+ AgentRequestContext initial = context("one");
+ AiRequestObservation observation = new AiRequestObservation(AgentInvocationAuditBridge.ai(null, records::add), initial);
AiRequestObservation.Attempt primary = observation.startAttempt(observation.getContext().withTarget("primary", "chat", null),
AiAttemptEvent.Kind.PRIMARY, "openai", "chat", false);
primary.status(503);
@@ -57,6 +59,11 @@ void reusesTerminalIdempotenceAndKeepsAttemptIdentity() {
assertEquals(List.of(1, 2), records.stream().filter(event -> event.getAttempt().isPresent()).map(event -> event.getAttempt().orElseThrow()).toList());
assertEquals(1, records.stream().filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).count());
assertTrue(records.stream().allMatch(event -> event.getApiKeyId().orElseThrow().equals("key-id-one")));
+ assertNull(initial.getTarget());
+ assertEquals("primary", records.get(0).getTarget().orElseThrow());
+ assertEquals("fallback", records.get(1).getTarget().orElseThrow());
+ // startAttempt updates the logical owner while each attempt keeps its selected target.
+ assertEquals("fallback", observation.getContext().getTarget());
assertEquals("fallback", records.get(2).getTarget().orElseThrow());
}
diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java
index f614f8a56328..4f1d01c4db06 100644
--- a/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java
+++ b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java
@@ -33,6 +33,12 @@ void emptyConfigurationIsExplicitLocalOnly(final String source) {
assertTrue(AgentGatewayAggregationConfig.parsePluginConfig(source).servers().isEmpty());
}
+ @Test
+ void acceptsControlledHttpsHostnameEndpointShape() {
+ String server = "{\"name\":\"orders\",\"endpoint\":\"https://example.com:443/mcp\",\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}";
+ assertEquals("https://example.com:443/mcp", AgentGatewayAggregationConfig.parsePluginConfig(wrap(server)).servers().get(0).endpoint().toString());
+ }
+
@ParameterizedTest
@ValueSource(strings = {"[]", "null", "{\"unknown\":1}", "{\"aggregation\":null}",
"{\"aggregation\":{\"revision\":\"v1\"}}", "{\"aggregation\":{\"revision\":\"v1\",\"servers\":{}}}",
@@ -54,10 +60,39 @@ void freezesServerReferencesAndAcceptsHttpsSyntax() {
assertThrows(IllegalArgumentException.class, () -> AgentGatewayAggregationConfig.parsePluginConfig(wrap(server + "," + server)));
}
+ @Test
+ void parsesOptionalStrictAdmissionConfiguration() {
+ String source = "{\"aggregation\":{\"revision\":\"v1\",\"servers\":[]},"
+ + "\"admission\":{\"globalInFlight\":1,\"globalQueued\":2,\"localInFlight\":3,"
+ + "\"localQueued\":4,\"remoteInFlight\":5,\"remoteQueued\":6}}";
+ AgentGatewayAdmissionConfig admission = AgentGatewayAggregationConfig.parsePluginConfig(source).admission();
+ assertEquals(1, admission.globalInFlight());
+ assertEquals(2, admission.globalQueued());
+ assertEquals(3, admission.localInFlight());
+ assertEquals(4, admission.localQueued());
+ assertEquals(5, admission.remoteInFlight());
+ assertEquals(6, admission.remoteQueued());
+ }
+
+ @Test
+ void parsesAdmissionWithoutRemoteAggregation() {
+ String source = "{\"admission\":{\"globalInFlight\":8,\"globalQueued\":4,\"localInFlight\":1,"
+ + "\"localQueued\":0,\"remoteInFlight\":2,\"remoteQueued\":2}}";
+ AgentGatewayAggregationConfig config = AgentGatewayAggregationConfig.parsePluginConfig(source);
+ assertTrue(config.servers().isEmpty());
+ assertEquals(1, config.admission().localInFlight());
+ }
+
+ @Test
+ void rejectsUnknownOrExcessiveAdmissionFields() {
+ assertThrows(IllegalArgumentException.class, () -> new AgentGatewayAdmissionConfig(0, 0, 1, 0, 1, 0));
+ assertThrows(IllegalArgumentException.class, () -> new AgentGatewayAdmissionConfig(129, 0, 1, 0, 1, 0));
+ }
+
@ParameterizedTest
@ValueSource(strings = {"http://user:pass@127.0.0.1:8080/mcp", "http://127.0.0.1/mcp", "http://127.0.0.1:8080/a/../mcp",
"http://127.0.0.1:8080/mcp?key=SECRET", "http://127.0.0.1:8080/mcp#SECRET", "http://127.0.0.1:8080/%2e/mcp",
- "https://example.com:443/mcp", "http://192.0.2.10:8080/mcp", "https://0.0.0.0:443/mcp", "https://255.255.255.255:443/mcp"})
+ "http://example.com:443/mcp", "http://192.0.2.10:8080/mcp", "https://0.0.0.0:443/mcp", "https://255.255.255.255:443/mcp"})
void rejectsAmbiguousEndpoints(final String endpoint) {
String server = "{\"name\":\"orders\",\"endpoint\":\"" + endpoint + "\",\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}";
assertThrows(IllegalArgumentException.class, () -> AgentGatewayAggregationConfig.parsePluginConfig(wrap(server)));
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml
index ab93136a3bf9..601a1f7ffa2a 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml
@@ -50,6 +50,10 @@
${project.version}
test
+
+ org.apache.httpcomponents
+ httpasyncclient
+
io.modelcontextprotocol.sdk
mcp-core
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java
index 449a8d7ebe6e..69baa4a49cac 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java
@@ -25,17 +25,18 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.shenyu.common.dto.AgentGatewayHttpToolConfig;
+import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceRegistry;
+import org.apache.shenyu.plugin.agent.gateway.tool.AgentHttpToolProvider;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolArgumentException;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolCapabilityException;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolDefinition;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolExecutionException;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolInvocation;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry;
-import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceRegistry;
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider;
-import org.apache.shenyu.plugin.agent.gateway.tool.AgentHttpToolProvider;
import reactor.core.publisher.Mono;
+import java.util.List;
import java.util.Map;
import java.net.http.HttpTimeoutException;
import java.util.concurrent.TimeoutException;
@@ -51,6 +52,8 @@ public final class AgentMcpDispatcher {
private final AgentMcpRemoteCatalog remoteCatalog;
+ private final AgentMcpResourceAdmission admission;
+
private final AgentMcpResourceDispatcher resources;
private final AgentResourceRegistry resourceRegistry;
@@ -66,15 +69,52 @@ public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverN
}
public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, final AgentMcpRemoteCatalog remoteCatalog) {
- this(registry, serverName, serverVersion, remoteCatalog, new AgentResourceRegistry(java.util.List.of()));
+ this(registry, serverName, serverVersion, remoteCatalog, AgentMcpResourceAdmission.NOOP);
}
+ /**
+ * Managed dispatcher with bounded remote resource admission.
+ * @param registry trusted local tool registry
+ * @param serverName server name
+ * @param serverVersion server version
+ * @param remoteCatalog optional remote catalog
+ * @param admission remote admission policy
+ */
+ public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion,
+ final AgentMcpRemoteCatalog remoteCatalog, final AgentMcpResourceAdmission admission) {
+ this(registry, serverName, serverVersion, remoteCatalog, new AgentResourceRegistry(List.of()), admission);
+ }
+
+ /**
+ * Managed dispatcher with local resources.
+ * @param registry trusted local tool registry
+ * @param serverName server name
+ * @param serverVersion server version
+ * @param remoteCatalog optional remote catalog
+ * @param resourceRegistry explicitly registered local resources
+ */
public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, final AgentMcpRemoteCatalog remoteCatalog,
final AgentResourceRegistry resourceRegistry) {
+ this(registry, serverName, serverVersion, remoteCatalog, resourceRegistry, AgentMcpResourceAdmission.NOOP);
+ }
+
+ /**
+ * Managed dispatcher with local resources and bounded remote resource admission.
+ * @param registry trusted local tool registry
+ * @param serverName server name
+ * @param serverVersion server version
+ * @param remoteCatalog optional remote catalog
+ * @param resourceRegistry explicitly registered local resources
+ * @param admission remote admission policy
+ */
+ public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion,
+ final AgentMcpRemoteCatalog remoteCatalog, final AgentResourceRegistry resourceRegistry,
+ final AgentMcpResourceAdmission admission) {
this.registry = Objects.requireNonNull(registry, "registry");
this.remoteCatalog = remoteCatalog;
this.resourceRegistry = Objects.requireNonNull(resourceRegistry, "resourceRegistry");
- resources = new AgentMcpResourceDispatcher(resourceRegistry);
+ this.resources = new AgentMcpResourceDispatcher(resourceRegistry);
+ this.admission = Objects.requireNonNull(admission, "admission");
if (Objects.requireNonNull(serverName, "serverName").isBlank() || Objects.requireNonNull(serverVersion, "serverVersion").isBlank()) {
throw new IllegalArgumentException("Server identity must not be blank");
}
@@ -106,7 +146,8 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier bound);
+ return new AgentMcpDispatcher(captured, serverName, serverVersion, remoteCatalog,
+ resourceRegistry, Objects.isNull(remoteCatalog) ? admission : remoteCatalog.admission()).dispatch(request, () -> bound);
}
if (Objects.nonNull(remoteCatalog)) {
return remoteCatalog.withSnapshot(snapshot -> routeWithRemote(request, context, snapshot))
@@ -141,6 +182,13 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier routeWithRemote(final AgentMcpRequest request, final Ag
ObjectNode params = request.getParams();
JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject();
return Mono.defer(() -> {
- context.notifyAttempt();
- return snapshot.invoke(name, arguments, context);
+ return admission.withRemote(remoteServer(name), context.getDeadline(),
+ Mono.fromRunnable(context::notifyAttempt).then(snapshot.invoke(name, arguments, context)));
})
.switchIfEmpty(Mono.error(new IllegalStateException("Remote tool completed without a result")))
.map(value -> {
@@ -265,7 +313,8 @@ private Mono call(final AgentMcpRequest request, final AgentMcpExecu
JsonObject capabilities = request.getClientCapabilities();
return registry.invoke(name, context.getAllowedTools(),
() -> new AgentToolInvocation(context.getRequestId(), context.getSubject(), arguments,
- context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt)
+ context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt,
+ execution -> admission.withLocal(context.getDeadline(), execution))
.map(value -> {
// Active field policies must not introduce an opaque metadata channel.
ObjectNode result = filter.isActive() ? mapper.createObjectNode().put("resultType", "complete") : complete();
@@ -296,6 +345,11 @@ private ObjectNode toolFailure(final AgentMcpRequest request, final String messa
return response(request, filterResult(request, filter, result));
}
+ private String remoteServer(final String exposedName) {
+ int separator = exposedName.indexOf('.');
+ return separator > 0 ? exposedName.substring(0, separator) : exposedName;
+ }
+
private AgentMcpResultFilter prepareResultFilter(final AgentMcpRequest request, final AgentMcpExecutionContext context,
final String name, final JsonNode schema) {
try {
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java
index b7f17bf64308..627075dc3c8a 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java
@@ -78,7 +78,7 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi
final Set ruleTools, final Set securityGrants, final Instant deadline,
final AgentGatewayResultFilterConfig resultFilters) {
this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters,
- Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, null);
+ Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, null, null);
}
public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
@@ -86,14 +86,14 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi
final AgentGatewayResultFilterConfig resultFilters, final Set ruleResources,
final Set resourceGrants) {
this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters,
- ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, null);
+ ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, null, null);
}
public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
final Set ruleTools, final Set securityGrants, final Instant deadline,
final AgentGatewayResultFilterConfig resultFilters, final String tenant) {
this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters,
- Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, tenant);
+ Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, tenant, null);
}
public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
@@ -101,7 +101,7 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi
final AgentGatewayResultFilterConfig resultFilters, final Set ruleResources,
final Set resourceGrants, final String tenant) {
this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters,
- ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, tenant);
+ ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, tenant, null);
}
public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
@@ -109,7 +109,7 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi
final AgentGatewayResultFilterConfig resultFilters, final AgentGatewayHttpToolConfig httpTools,
final AgentHttpToolInvoker httpInvoker) {
this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters,
- Set.of(), Set.of(), httpTools, httpInvoker, null);
+ Set.of(), Set.of(), httpTools, httpInvoker, null, null);
}
public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
@@ -120,6 +120,29 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi
Set.of(), Set.of(), httpTools, httpInvoker, tenant, null);
}
+ /**
+ * Request-local context with HTTP tools and one terminal attempt callback.
+ * @param requestId trusted request identity
+ * @param subject trusted authenticated subject
+ * @param ruleId matched rule identity
+ * @param configurationVersion rule snapshot generation
+ * @param ruleTools configured tool allow-list
+ * @param securityGrants identity tool grants
+ * @param deadline request deadline
+ * @param resultFilters configured result filters
+ * @param httpTools request-owned HTTP tool definitions
+ * @param httpInvoker internal gateway HTTP executor
+ * @param tenant trusted tenant identity
+ * @param attemptListener internal attempt callback
+ */
+ AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
+ final Set ruleTools, final Set securityGrants, final Instant deadline,
+ final AgentGatewayResultFilterConfig resultFilters, final AgentGatewayHttpToolConfig httpTools,
+ final AgentHttpToolInvoker httpInvoker, final String tenant, final Runnable attemptListener) {
+ this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters,
+ Set.of(), Set.of(), httpTools, httpInvoker, tenant, attemptListener);
+ }
+
public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
final Set ruleTools, final Set securityGrants, final Instant deadline,
final AgentGatewayResultFilterConfig resultFilters, final Set ruleResources,
@@ -129,6 +152,23 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi
ruleResources, resourceGrants, httpTools, httpInvoker, tenant, null);
}
+ /**
+ * Fully populated request-local context.
+ * @param requestId trusted request identity
+ * @param subject trusted authenticated subject
+ * @param ruleId matched rule identity
+ * @param configurationVersion rule snapshot generation
+ * @param ruleTools configured tool allow-list
+ * @param securityGrants identity tool grants
+ * @param deadline request deadline
+ * @param resultFilters configured result filters
+ * @param ruleResources configured resource allow-list
+ * @param resourceGrants identity resource grants
+ * @param httpTools request-owned HTTP tool definitions
+ * @param httpInvoker internal gateway HTTP executor
+ * @param tenant trusted tenant identity
+ * @param attemptListener internal attempt callback
+ */
AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion,
final Set ruleTools, final Set securityGrants, final Instant deadline,
final AgentGatewayResultFilterConfig resultFilters, final Set ruleResources,
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java
index 11a5503e540c..a612504e3a0c 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java
@@ -138,19 +138,21 @@ public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcp
}
observation.parsed(request);
return dispatcher.dispatch(request, () -> new AgentMcpExecutionContext(traffic.getRequestId(),
- identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(),
- identity.getToolGrants(), deadline, config.getResultFilters(), config.getAllowedResources(),
- identity.getResourceGrants(), config.getHttpTools(), httpInvoker,
- identity.getTenant().orElse(null), () -> {
- if (Objects.nonNull(terminal)) {
- terminal.attempted();
- }
- }))
+ identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(),
+ identity.getToolGrants(), deadline, config.getResultFilters(), config.getAllowedResources(),
+ identity.getResourceGrants(), config.getHttpTools(), httpInvoker,
+ identity.getTenant().orElse(null), () -> {
+ if (Objects.nonNull(terminal)) {
+ terminal.attempted();
+ }
+ }))
.contextWrite(observation::traceContext)
.contextWrite(context -> context.put(AgentRuntimeMetrics.KEY, metrics))
.contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY,
- traffic.toRequestContext(configurationVersion).withIdentity(identity.getTenant().orElse(null), identity.getSubject())
- .withTarget("tools/call".equals(request.getMethod()) ? request.getParams().path("name").textValue() : null,
+ traffic.toRequestContext(configurationVersion)
+ .withIdentity(identity.getTenant().orElse(null), identity.getSubject())
+ .withTarget("tools/call".equals(request.getMethod())
+ ? request.getParams().path("name").textValue() : null,
request.getMethod(), AgentMcpRequestParser.VERSION)));
}))
.flatMap(response -> {
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java
index c1ecb20f5676..873ff05c25f5 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java
@@ -36,6 +36,14 @@ public interface AgentMcpRemoteCatalog {
*/
Mono withSnapshot(Function> operation);
+ /** Return the closeable request-admission controller owned by this catalog.
+ * @return controller implementation
+ */
+ default AgentMcpResourceAdmission admission() {
+ return AgentMcpResourceAdmission.NOOP;
+ }
+
+
/** Distinguishes an unavailable catalog from unexpected gateway failures. */
final class CatalogUnavailableException extends IllegalStateException {
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java
new file mode 100644
index 000000000000..5de88a82121b
--- /dev/null
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.agent.gateway.protocol;
+
+import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig;
+import org.apache.shenyu.common.metrics.AgentAdmissionMetrics;
+import reactor.core.publisher.Mono;
+
+import java.time.Instant;
+import java.util.Objects;
+
+/** Optional resource-admission port; the no-op implementation preserves existing behavior. */
+public interface AgentMcpResourceAdmission {
+
+ AgentMcpResourceAdmission NOOP = new AgentMcpResourceAdmission() {
+ @Override
+ public Mono withLocal(final Instant deadline, final Mono action) {
+ return action;
+ }
+
+ @Override
+ public Mono withRemote(final String server, final Instant deadline, final Mono action) {
+ return action;
+ }
+ };
+
+ /** Bound one local-provider execution.
+ * @param deadline absolute request deadline
+ * @param action controlled execution
+* @param result type
+ * @return controlled result
+ */
+ Mono withLocal(Instant deadline, Mono action);
+
+ /** Bound one configured remote-server execution.
+ * @param server stable target name, never Agent input
+ * @param deadline absolute request deadline
+ * @param action controlled execution
+* @param result type
+ * @return controlled result
+ */
+ Mono withRemote(String server, Instant deadline, Mono action);
+
+ /** Wrap the concrete deterministic controller while retaining the small port.
+ * @param config trusted hard-bounded configuration
+ * @return closeable port implementation
+ */
+ static ResourceAdmissionController create(final AgentGatewayAdmissionConfig config) {
+ return new ResourceAdmissionController(new AgentResourceAdmission(config));
+ }
+
+ /** Closeable wrapper used by the Spring lifecycle. */
+ final class ResourceAdmissionController implements AgentMcpResourceAdmission, AutoCloseable {
+
+ private final AgentResourceAdmission delegate;
+
+ private volatile AgentResourceAdmission current;
+
+ private ResourceAdmissionController(final AgentResourceAdmission delegate) {
+ this.delegate = delegate;
+ this.current = delegate;
+ }
+
+ @Override
+ public Mono withLocal(final Instant deadline, final Mono action) {
+ return current.withLocal(deadline, action);
+ }
+
+ @Override
+ public Mono withRemote(final String server, final Instant deadline, final Mono action) {
+ return current.withRemote(server, deadline, action);
+ }
+
+ /**
+ * Apply replacement limits without replacing the shared accounting state.
+ * Requests owned by the active controller remain admitted or queued across reloads.
+ *
+ * @param replacement validated replacement controller
+ */
+ public void replace(final ResourceAdmissionController replacement) {
+ Objects.requireNonNull(replacement, "replacement");
+ if (replacement.delegate.closed()) {
+ replacement.delegate.close();
+ return;
+ }
+ try {
+ current.updateLimits(replacement.delegate);
+ } finally {
+ replacement.delegate.close();
+ }
+ }
+
+ @Override
+ public void close() {
+ AgentResourceAdmission active;
+ synchronized (this) {
+ active = current;
+ }
+ active.close();
+ }
+
+ /**
+ * Read the currently active limits without creating another controller.
+ * @return immutable trusted limits
+ */
+ public AgentGatewayAdmissionConfig config() {
+ return current.config();
+ }
+
+ /**
+ * Read the live states of the active controller.
+ * @return immutable controller snapshots
+ */
+ public java.util.List snapshot() {
+ return current.snapshot();
+ }
+ }
+}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java
new file mode 100644
index 000000000000..4a73fb33ab17
--- /dev/null
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java
@@ -0,0 +1,416 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.agent.gateway.protocol;
+
+import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig;
+import org.apache.shenyu.common.metrics.AgentAdmissionMetrics;
+import reactor.core.publisher.Mono;
+
+import java.time.Instant;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+/** Deterministic gateway resource admission with bounded deadline-aware queues. */
+public final class AgentResourceAdmission implements AutoCloseable {
+
+ private volatile AgentGatewayAdmissionConfig config;
+
+ private final Scope global;
+
+ private final Scope local;
+
+ private final Deque remotes = new ArrayDeque<>();
+
+ private final Object promotionLock = new Object();
+
+ private final AgentAdmissionMetrics registration;
+
+ private volatile boolean closed;
+
+ public AgentResourceAdmission(final AgentGatewayAdmissionConfig config) {
+ this.config = Objects.requireNonNull(config, "config");
+ global = new Scope("global", promotionLock, config.globalInFlight(), config.globalQueued());
+ local = new Scope("local", promotionLock, config.localInFlight(), config.localQueued());
+ registration = AgentAdmissionMetrics.register(this::snapshot);
+ }
+
+ /**
+ * Acquire global and LOCAL admission around the single local provider execution.
+ * @param deadline absolute request deadline, including queue wait
+ * @param action execution after all permits are acquired
+ * @param response type
+ * @return one execution result with terminal permit release
+ */
+ public Mono withLocal(final Instant deadline, final Mono action) {
+ return with(global, deadline, with(local, deadline, action));
+ }
+
+ /**
+ * Acquire global and one stable remote-server scope around a single tool call.
+ * @param server configured remote target name
+ * @param deadline absolute request deadline, including queue wait
+ * @param action execution after all permits are acquired
+* @param response type
+ * @return one execution result with terminal permit release
+ */
+ public Mono withRemote(final String server, final Instant deadline, final Mono action) {
+ return with(global, deadline, with(remote(server), deadline, action));
+ }
+
+ private Mono with(final Scope scope, final Instant deadline, final Mono action) {
+ return Mono.defer(() -> {
+ if (closed) {
+ scope.rejected.incrementAndGet();
+ return Mono.error(AgentAdmissionException.closed());
+ }
+ AcquireResult acquired = scope.acquire(deadline);
+ if (Objects.nonNull(acquired.error)) {
+ return Mono.error(acquired.error);
+ }
+ return acquired.wait.admission()
+ .timeout(Duration.between(Instant.now(), deadline))
+ .onErrorMap(java.util.concurrent.TimeoutException.class,
+ error -> AgentAdmissionException.deadline())
+ .then(Mono.defer(() -> Instant.now().isBefore(deadline) ? action : Mono.error(AgentAdmissionException.deadline())))
+ .doFinally(signal -> scope.release(acquired.wait));
+ });
+ }
+
+ private Scope remote(final String name) {
+ if (Objects.isNull(name) || !name.matches("[A-Za-z0-9_-]{1,48}")) {
+ throw new IllegalArgumentException("Invalid remote admission scope");
+ }
+ synchronized (remotes) {
+ for (Scope scope : remotes) {
+ if (scope.name.equals(name)) {
+ return scope;
+ }
+ }
+ Scope scope = new Scope(name, promotionLock, config.remoteInFlight(), config.remoteQueued());
+ remotes.add(scope);
+ return scope;
+ }
+ }
+
+ /**
+ * Secret-free live states for bounded runtime metrics.
+ * @return immutable controller snapshot
+ */
+ public List snapshot() {
+ List result = new ArrayList<>();
+ result.add(global.snapshot(AgentAdmissionMetrics.Scope.GLOBAL));
+ result.add(local.snapshot(AgentAdmissionMetrics.Scope.LOCAL));
+ remoteScopes().forEach(scope -> result.add(scope.snapshot(AgentAdmissionMetrics.Scope.REMOTE)));
+ return result;
+ }
+
+ private List remoteScopes() {
+ synchronized (remotes) {
+ return List.copyOf(remotes);
+ }
+ }
+
+ /**
+ * Current trusted limits.
+ * @return immutable admission configuration
+ */
+ public AgentGatewayAdmissionConfig config() {
+ return config;
+ }
+
+ /**
+ * Apply new limits to the same accounting state. Requests already admitted or queued
+ * remain owned by this controller, so a configuration reload cannot reset their permits.
+ *
+ * @param replacement trusted controller whose validated configuration is applied
+ */
+ void updateLimits(final AgentResourceAdmission replacement) {
+ Objects.requireNonNull(replacement, "replacement");
+ if (closed) {
+ throw new IllegalStateException("Admission controller is closed");
+ }
+ final AgentGatewayAdmissionConfig replacementConfig = replacement.config();
+ synchronized (promotionLock) {
+ synchronized (remotes) {
+ config = replacementConfig;
+ global.installLimits(replacementConfig.globalInFlight(), replacementConfig.globalQueued());
+ local.installLimits(replacementConfig.localInFlight(), replacementConfig.localQueued());
+ remotes.forEach(scope -> scope.installLimits(replacementConfig.remoteInFlight(), replacementConfig.remoteQueued()));
+ }
+ // Completion can synchronously release a promoted request: retain the
+ // same promotionLock -> scope lock order used by release and close.
+ global.promote();
+ local.promote();
+ remoteScopes().forEach(Scope::promote);
+ }
+ }
+
+ /**
+ * Whether this controller has already been closed.
+ * @return terminal close state
+ */
+ public boolean closed() {
+ return closed;
+ }
+
+ /** Stop new work and cancel queued waiters; terminal executions still release once. */
+ public void close() {
+ synchronized (promotionLock) {
+ closed = true;
+ registration.close();
+ global.close();
+ local.close();
+ remoteScopes().forEach(Scope::close);
+ }
+ }
+
+ /** Explicit resource-limit rejection, distinguishable from provider failures. */
+ public static final class AgentAdmissionException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ private final boolean timeout;
+
+ private final boolean closed;
+
+ private AgentAdmissionException(final boolean timeout, final boolean closed) {
+ super(timeout ? "Admission deadline exceeded" : closed ? "Gateway admission closed" : "Gateway resource limit exceeded");
+ this.timeout = timeout;
+ this.closed = closed;
+ }
+
+ static AgentAdmissionException overloaded() {
+ return new AgentAdmissionException(false, false);
+ }
+
+ static AgentAdmissionException deadline() {
+ return new AgentAdmissionException(true, false);
+ }
+
+ private static AgentAdmissionException closed() {
+ return new AgentAdmissionException(false, true);
+ }
+
+ /** Whether the request already exhausted its absolute deadline.
+ * @return deadline category
+ */
+ public boolean isTimeout() {
+ return timeout;
+ }
+ }
+
+ private static final class Wait {
+
+ private final Scope scope;
+
+ private final Waiter waiter;
+
+ private final boolean queued;
+
+ private Wait(final Scope scope, final Waiter waiter) {
+ this.scope = scope;
+ this.waiter = waiter;
+ this.queued = Objects.nonNull(waiter);
+ }
+
+ private Mono admission() {
+ return Objects.isNull(waiter) ? Mono.empty() : waiter.ready.asMono();
+ }
+ }
+
+ private static final class Scope {
+
+ private final String name;
+
+ private int inFlightLimit;
+
+ private int queueLimit;
+
+ private final AtomicLong rejected = new AtomicLong();
+
+ private final Object lock = new Object();
+
+ private final Object promotionLock;
+
+ private final Deque waiting = new ArrayDeque<>();
+
+ private int inFlight;
+
+ private int queued;
+
+ private boolean closed;
+
+ private Scope(final String name, final Object promotionLock, final int inFlightLimit, final int queueLimit) {
+ this.name = name;
+ this.promotionLock = promotionLock;
+ this.inFlightLimit = inFlightLimit;
+ this.queueLimit = queueLimit;
+ }
+
+ AcquireResult acquire(final Instant deadline) {
+ synchronized (lock) {
+ if (closed) {
+ rejected.incrementAndGet();
+ return AcquireResult.reject(AgentAdmissionException.closed());
+ }
+ if (!Instant.now().isBefore(deadline)) {
+ rejected.incrementAndGet();
+ return AcquireResult.reject(AgentAdmissionException.deadline());
+ }
+ if (inFlight < inFlightLimit) {
+ inFlight++;
+ return AcquireResult.admitted(new Wait(this, null));
+ }
+ if (queued >= queueLimit) {
+ rejected.incrementAndGet();
+ return AcquireResult.reject(AgentAdmissionException.overloaded());
+ }
+ Waiter waiter = new Waiter(deadline);
+ waiting.addLast(waiter);
+ queued++;
+ return AcquireResult.admitted(new Wait(this, waiter));
+ }
+ }
+
+ void release(final Wait wait) {
+ synchronized (promotionLock) {
+ synchronized (lock) {
+ if (Objects.isNull(wait.waiter)) {
+ completeActive(wait);
+ return;
+ }
+ boolean promoted = wait.waiter.state == State.PROMOTED;
+ if (wait.waiter.state == State.WAITING && waiting.remove(wait.waiter)) {
+ queued--;
+ rejected.incrementAndGet();
+ }
+ wait.waiter.completeExceptionally(AgentAdmissionException.deadline());
+ if (promoted) {
+ completeActive(wait);
+ }
+ }
+ }
+ }
+
+ private void completeActive(final Wait wait) {
+ synchronized (lock) {
+ inFlight--;
+ promote();
+ }
+ }
+
+ private void promote() {
+ synchronized (lock) {
+ while (inFlight < inFlightLimit) {
+ Waiter next = waiting.pollFirst();
+ if (Objects.isNull(next)) {
+ return;
+ }
+ queued--;
+ if (!Instant.now().isBefore(next.deadline) || closed) {
+ rejected.incrementAndGet();
+ next.completeExceptionally(AgentAdmissionException.deadline());
+ continue;
+ }
+ inFlight++;
+ next.complete();
+ }
+ }
+ }
+
+
+ void close() {
+ synchronized (lock) {
+ closed = true;
+ Waiter wait;
+ while (Objects.nonNull(wait = waiting.pollFirst())) {
+ queued--;
+ rejected.incrementAndGet();
+ wait.completeExceptionally(AgentAdmissionException.closed());
+ }
+ }
+ }
+
+ AgentAdmissionMetrics.Snapshot snapshot(final AgentAdmissionMetrics.Scope scope) {
+ synchronized (lock) {
+ return new AgentAdmissionMetrics.Snapshot(scope, inFlight, queued, inFlightLimit, queueLimit, rejected.get());
+ }
+ }
+
+ void installLimits(final int inFlightLimit, final int queueLimit) {
+ synchronized (lock) {
+ this.inFlightLimit = inFlightLimit;
+ this.queueLimit = queueLimit;
+ }
+ }
+ }
+
+ private static final class Waiter {
+
+ private final reactor.core.publisher.Sinks.One ready = reactor.core.publisher.Sinks.one();
+
+ private final Instant deadline;
+
+ private State state = State.WAITING;
+
+ private Waiter(final Instant deadline) {
+ this.deadline = deadline;
+ }
+
+ void complete() {
+ state = State.PROMOTED;
+ ready.tryEmitValue(null);
+ }
+
+ void completeExceptionally(final AgentAdmissionException error) {
+ state = State.TERMINATED;
+ ready.tryEmitError(error);
+ }
+ }
+
+ private enum State {
+ WAITING,
+ PROMOTED,
+ TERMINATED
+ }
+
+ private static final class AcquireResult {
+
+ private final Wait wait;
+
+ private final Throwable error;
+
+ private AcquireResult(final Wait wait, final Throwable error) {
+ this.wait = wait;
+ this.error = error;
+ }
+
+ static AcquireResult admitted(final Wait wait) {
+ return new AcquireResult(wait, null);
+ }
+
+ static AcquireResult reject(final Throwable error) {
+ return new AcquireResult(null, error);
+ }
+ }
+}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteHttpResponse.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteHttpResponse.java
new file mode 100644
index 000000000000..7f39fd1b4c39
--- /dev/null
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteHttpResponse.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.agent.gateway.remote;
+
+import org.apache.http.Header;
+import org.apache.http.HttpResponse;
+
+import java.io.ByteArrayOutputStream;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/** Immutable HTTP response adapter used by the target-owned Apache transport. */
+final class ApacheRemoteHttpResponse {
+
+ private final int status;
+
+ private final Map> headers;
+
+ private final ByteArrayOutputStream body;
+
+ private ApacheRemoteHttpResponse(final int status, final Map> headers, final ByteArrayOutputStream body) {
+ this.status = status;
+ this.headers = Map.copyOf(headers);
+ this.body = body;
+ }
+
+ static ApacheRemoteHttpResponse from(final HttpResponse response, final ByteArrayOutputStream body) {
+ Map> values = new java.util.TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ for (Header header : response.getAllHeaders()) {
+ values.computeIfAbsent(header.getName().toLowerCase(Locale.ROOT), ignored -> new java.util.ArrayList<>()).add(header.getValue());
+ }
+ return new ApacheRemoteHttpResponse(response.getStatusLine().getStatusCode(), values, body);
+ }
+
+ int status() {
+ return status;
+ }
+
+ Map> headers() {
+ return headers;
+ }
+
+ byte[] body() {
+ return body.toByteArray();
+ }
+
+}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteMcpTransport.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteMcpTransport.java
new file mode 100644
index 000000000000..3880a28fd2ce
--- /dev/null
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteMcpTransport.java
@@ -0,0 +1,376 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.agent.gateway.remote;
+
+import org.apache.http.conn.routing.HttpRoute;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.RedirectStrategy;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.concurrent.FutureCallback;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.nio.IOControl;
+import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
+import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
+import org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionFactory;
+import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
+import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
+import org.apache.http.impl.nio.reactor.IOReactorConfig;
+import org.apache.http.nio.conn.SchemeIOSessionStrategy;
+import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
+import org.apache.http.nio.protocol.BasicAsyncRequestProducer;
+import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
+import org.apache.http.nio.protocol.HttpAsyncResponseConsumer;
+import org.apache.http.nio.reactor.ConnectingIOReactor;
+import org.apache.http.nio.reactor.IOReactorException;
+import org.apache.http.protocol.HttpContext;
+import reactor.core.publisher.Mono;
+import reactor.core.publisher.Sinks;
+
+import javax.net.ssl.SSLContext;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Objects;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * One exclusively owned, bounded pooled transport per target and credential generation.
+ * The connection manager maps the approved hostname only to its approved IPv4 address;
+ * TLS and SNI continue to use the original HttpHost hostname.
+ */
+final class ApacheRemoteMcpTransport implements AutoCloseable {
+
+ private static final int MAX_POOL = 8;
+
+ private final ConnectingIOReactor reactor;
+
+ private final PoolingNHttpClientConnectionManager connections;
+
+ private final CloseableHttpAsyncClient client;
+
+ private ApacheRemoteMcpTransport(final ConnectingIOReactor reactor, final PoolingNHttpClientConnectionManager connections,
+ final CloseableHttpAsyncClient client) {
+ this.reactor = reactor;
+ this.connections = connections;
+ this.client = client;
+ }
+
+ static ApacheRemoteMcpTransport create(final RemoteTransportRoute route, final SSLContext testContext) {
+ SSLContext context;
+ try {
+ context = Objects.isNull(testContext) ? SSLContext.getDefault() : testContext;
+ } catch (java.security.NoSuchAlgorithmException error) {
+ throw new IllegalStateException("Remote MCP TLS initialization failed");
+ }
+ try {
+ IOReactorConfig reactorConfig = IOReactorConfig.custom()
+ .setIoThreadCount(1)
+ .setConnectTimeout(2000)
+ .setTcpNoDelay(true)
+ .setSoKeepAlive(true)
+ .setSndBufSize(8192)
+ .setRcvBufSize(8192)
+ .build();
+ ConnectingIOReactor reactor = new DefaultConnectingIOReactor(reactorConfig, task -> {
+ Thread thread = new Thread(task, "shenyu-agent-mcp-transport");
+ thread.setDaemon(true);
+ return thread;
+ });
+ Registry strategies = RegistryBuilder.create()
+ .register("https", new SSLIOSessionStrategy(context))
+ .register("http", NoopIOSessionStrategy.INSTANCE)
+ .build();
+ PoolingNHttpClientConnectionManager connections = new PoolingNHttpClientConnectionManager(
+ reactor, ManagedNHttpClientConnectionFactory.INSTANCE, strategies, new FixedAddressResolver(route), 30, TimeUnit.SECONDS);
+ connections.setMaxTotal(MAX_POOL);
+ connections.setDefaultMaxPerRoute(MAX_POOL);
+ CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
+ .setConnectionManager(connections)
+ .setMaxConnTotal(MAX_POOL)
+ .setMaxConnPerRoute(MAX_POOL)
+ .setConnectionTimeToLive(30, TimeUnit.SECONDS)
+ .setRedirectStrategy(new NeverRedirectStrategy())
+ .disableConnectionState()
+ .disableCookieManagement()
+ .disableAuthCaching()
+ .build();
+ client.start();
+ return new ApacheRemoteMcpTransport(reactor, connections, client);
+ } catch (IOReactorException error) {
+ throw new IllegalStateException("Remote MCP transport initialization failed");
+ }
+ }
+
+ AsyncRequestHandle execute(final HttpHost target, final HttpRequest request,
+ final long deadlineMillis) {
+ int timeout = deadlineMillis > Integer.MAX_VALUE ? Integer.MAX_VALUE : Math.max(1, (int) deadlineMillis);
+ RequestConfig config = RequestConfig.custom()
+ .setRedirectsEnabled(false)
+ .setConnectionRequestTimeout(timeout)
+ .setConnectTimeout(timeout)
+ .setSocketTimeout(timeout)
+ .build();
+ HttpRequest configured = request instanceof ConfigurableRequest configurable
+ ? configurable.withConfig(config)
+ : request;
+ HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(target, configured);
+ Sinks.One completion = Sinks.one();
+ Future> owned = client.execute(producer, new BoundedResponseConsumer(), new FutureCallback() {
+ @Override
+ public void completed(final ApacheRemoteHttpResponse result) {
+ completion.tryEmitValue(result);
+ }
+
+ @Override
+ public void failed(final Exception error) {
+ completion.tryEmitError(error);
+ }
+
+ @Override
+ public void cancelled() {
+ completion.tryEmitError(new IllegalStateException("Remote MCP request cancelled"));
+ }
+ });
+ return new AsyncRequestHandle<>(owned, completion);
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ client.close();
+ } finally {
+ connections.shutdown();
+ reactor.shutdown();
+ }
+ }
+
+ /** Bind the approved route and port while retaining the original target hostname. */
+ private static final class FixedAddressResolver implements org.apache.http.nio.pool.SocketAddressResolver {
+
+ private final RemoteTransportRoute route;
+
+ private FixedAddressResolver(final RemoteTransportRoute route) {
+ this.route = route;
+ }
+
+ @Override
+ public SocketAddress resolveLocalAddress(final HttpRoute key) {
+ return null;
+ }
+
+ @Override
+ public SocketAddress resolveRemoteAddress(final HttpRoute key) {
+ HttpHost target = key.getTargetHost();
+ if (!route.endpoint().getHost().equalsIgnoreCase(target.getHostName()) || route.endpoint().getPort() != target.getPort()) {
+ throw new IllegalStateException("Unauthorized remote MCP route");
+ }
+ return new InetSocketAddress(route.address(), route.endpoint().getPort());
+ }
+ }
+
+ /** Bridge the client future to the already subscribed Reactor signal without blocking callers. */
+ static final class AsyncRequestHandle implements Future {
+
+ private final Future> owned;
+
+ private final Sinks.One completion;
+
+ /** Bridge a completion-stage-like future for isolated tests and production callbacks. */
+ & java.util.concurrent.CompletionStage> AsyncRequestHandle(final F owned) {
+ this(owned, Sinks.one());
+ owned.whenComplete((value, error) -> {
+ if (Objects.nonNull(error)) {
+ completion.tryEmitError(error);
+ } else {
+ completion.tryEmitValue(value);
+ }
+ });
+ }
+
+ private AsyncRequestHandle(final Future> owned, final Sinks.One completion) {
+ this.owned = owned;
+ this.completion = completion;
+ }
+
+ Mono signal() {
+ return completion.asMono();
+ }
+
+ @Override
+ public boolean cancel(final boolean mayInterruptIfRunning) {
+ return owned.cancel(mayInterruptIfRunning);
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return owned.isCancelled();
+ }
+
+ @Override
+ public boolean isDone() {
+ return owned.isDone();
+ }
+
+ @Override
+ public T get() {
+ return block();
+ }
+
+ @Override
+ public T get(final long timeout, final TimeUnit unit) throws InterruptedException, java.util.concurrent.TimeoutException {
+ T value = completion.asMono().block(java.time.Duration.ofMillis(unit.toMillis(timeout)));
+ if (Objects.isNull(value)) {
+ throw new java.util.concurrent.TimeoutException();
+ }
+ return value;
+ }
+
+ private T block() {
+ return completion.asMono().block();
+ }
+ }
+
+ /** Redirect execution is intentionally disabled by returning no redirect request. */
+ private static final class NeverRedirectStrategy implements RedirectStrategy {
+ @Override
+ public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) {
+ return false;
+ }
+
+ @Override
+ public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) {
+ return null;
+ }
+ }
+
+ /** Exposes per-request timeouts to HttpAsyncClient's Configurable contract. */
+ static final class ConfigurableRequest extends org.apache.http.message.BasicHttpEntityEnclosingRequest
+ implements org.apache.http.client.methods.Configurable {
+
+ private RequestConfig config;
+
+ ConfigurableRequest(final String method, final String uri) {
+ super(method, uri);
+ }
+
+ ConfigurableRequest withConfig(final RequestConfig value) {
+ this.config = value;
+ return this;
+ }
+
+ @Override
+ public RequestConfig getConfig() {
+ return config;
+ }
+ }
+
+ /** Bounded response consumer retaining only headers and at most 8 KiB of body. */
+ private static final class BoundedResponseConsumer implements HttpAsyncResponseConsumer {
+
+ private static final int LIMIT = 8192;
+
+ private final ByteArrayOutputStream body = new ByteArrayOutputStream();
+
+ private volatile boolean completed;
+
+ private volatile ApacheRemoteHttpResponse response;
+
+ private volatile Exception failure;
+
+ private volatile boolean cancelled;
+
+ @Override
+ public void responseReceived(final HttpResponse response) {
+ this.response = ApacheRemoteHttpResponse.from(response, body);
+ }
+
+ @Override
+ public void consumeContent(final org.apache.http.nio.ContentDecoder decoder, final IOControl ioControl) throws IOException {
+ ByteBuffer buffer = ByteBuffer.allocate(4096);
+ int count;
+ while ((count = decoder.read(buffer)) > 0) {
+ if (body.size() + count > LIMIT) {
+ throw new IOException("Response byte limit");
+ }
+ buffer.flip();
+ body.write(buffer.array(), 0, count);
+ buffer.clear();
+ }
+ }
+
+ @Override
+ public void responseCompleted(final HttpContext context) {
+ completed = true;
+ }
+
+ @Override
+ public void failed(final Exception exception) {
+ failure = exception;
+ }
+
+ @Override
+ public void close() throws IOException {
+ // The owned stream is only a bounded in-memory adapter.
+ }
+
+ @Override
+ public boolean cancel() {
+ cancelled = true;
+ return true;
+ }
+
+ @Override
+ public ApacheRemoteHttpResponse getResult() {
+ return completed && Objects.isNull(failure) && !cancelled ? response : null;
+ }
+
+ @Override
+ public Exception getException() {
+ return failure;
+ }
+
+ @Override
+ public boolean isDone() {
+ return completed || Objects.nonNull(failure) || cancelled;
+ }
+
+ }
+
+ /** Plain-HTTP strategy retained only for the historical loopback fixed-IP contract. */
+ private enum NoopIOSessionStrategy implements SchemeIOSessionStrategy {
+ INSTANCE;
+
+ @Override
+ public org.apache.http.nio.reactor.IOSession upgrade(final org.apache.http.HttpHost host,
+ final org.apache.http.nio.reactor.IOSession iosession) {
+ return iosession;
+ }
+
+ @Override
+ public boolean isLayeringRequired() {
+ return false;
+ }
+ }
+}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java
index af8006823efe..89db4ff87671 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java
@@ -23,6 +23,7 @@
import com.google.gson.JsonObject;
import io.modelcontextprotocol.common.McpTransportContext;
import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig;
+import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig;
import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry;
import org.apache.shenyu.common.config.contract.ConfigurationScope;
import org.apache.shenyu.common.config.contract.ConfigurationValidation;
@@ -32,6 +33,7 @@
import org.apache.shenyu.common.tracing.AgentTraceContext;
import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext;
import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog;
+import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
@@ -63,12 +65,16 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut
private final RemoteCatalogLifecycle lifecycle;
- private final Set allowedEndpoints;
+ private final RemoteTransportRouteSet routes;
private final Set localNames;
private final RemoteServiceCredentialResolver credentials;
+ private final javax.net.ssl.SSLContext verificationTlsContext;
+
+ private final AgentMcpResourceAdmission.ResourceAdmissionController admission;
+
private final Scheduler scheduler = Schedulers.newBoundedElastic(1, 16, "agent-mcp-config");
private final Sinks.Many updates = Sinks.many().unicast().onBackpressureBuffer(new ArrayBlockingQueue<>(16));
@@ -84,22 +90,52 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut
private volatile boolean closed;
/**
- * Managed Remote Mcp Catalog.
- * @param allowedEndpoints trusted allowedEndpoints value
- * @param localNames trusted localNames value
- * @param credentials trusted credentials value
+ * Managed catalog compatibility constructor for fixed-IP deployments.
+ * @param allowedEndpoints trusted fixed-IP endpoints
+ * @param localNames local tool names
+ * @param credentials fixed service credential resolver
*/
public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, final RemoteServiceCredentialResolver credentials) {
- this(allowedEndpoints, localNames, credentials, false);
+ this(allowedEndpoints, localNames, credentials, AgentMcpResourceAdmission.create(AgentGatewayAdmissionConfig.parse(null)), false);
}
- public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, final RemoteServiceCredentialResolver credentials,
- final boolean resourcesEnabled) {
+ /**
+ * Managed catalog with a shared admission controller.
+ * @param allowedEndpoints trusted fixed-IP endpoints
+ * @param localNames local tool names
+ * @param credentials fixed service credential resolver
+ * @param admission shared controller
+ */
+ public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames,
+ final RemoteServiceCredentialResolver credentials,
+ final AgentMcpResourceAdmission.ResourceAdmissionController admission) {
+ this(allowedEndpoints, localNames, credentials, admission, false);
+ }
+
+ /**
+ * Managed catalog with shared admission and resource lifecycle configuration.
+ * @param allowedEndpoints trusted fixed-IP endpoints
+ * @param localNames local tool names
+ * @param credentials fixed service credential resolver
+ * @param admission shared controller
+ * @param resourcesEnabled whether remote resources are enabled
+ */
+ public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames,
+ final RemoteServiceCredentialResolver credentials,
+ final AgentMcpResourceAdmission.ResourceAdmissionController admission, final boolean resourcesEnabled) {
+ this(fixedRoutes(allowedEndpoints), localNames, credentials, admission, resourcesEnabled, null);
+ }
+
+ private ManagedRemoteMcpCatalog(final Set allowedRoutes, final Set localNames,
+ final RemoteServiceCredentialResolver credentials,
+ final AgentMcpResourceAdmission.ResourceAdmissionController admission,
+ final boolean resourcesEnabled, final javax.net.ssl.SSLContext verificationTlsContext) {
lifecycle = new RemoteCatalogLifecycle(3, resourcesEnabled);
- this.allowedEndpoints = Set.copyOf(allowedEndpoints);
+ this.routes = RemoteTransportRouteSet.parse(allowedRoutes);
this.localNames = Set.copyOf(localNames);
this.credentials = Objects.requireNonNull(credentials, "credentials");
- this.allowedEndpoints.forEach(RemoteTransportPolicy::endpoint);
+ this.admission = Objects.requireNonNull(admission, "admission");
+ this.verificationTlsContext = verificationTlsContext;
// The single owned subscription belongs to the control-plane lifecycle, never a request.
lifecycle.refresh(List.of()).block(Duration.ofSeconds(6));
worker = updates.asFlux().publishOn(scheduler, 1).concatMap(this::applyUpdate, 1).subscribe();
@@ -113,11 +149,65 @@ public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set allowedRoutes, final Set localNames,
+ final RemoteServiceCredentialResolver credentials) {
+ return forRoutes(allowedRoutes, localNames, credentials, false);
+ }
+
+ /**
+ * Create a route-aware managed catalog with default admission.
+ * @param allowedRoutes trusted routes
+ * @param localNames local tool names
+ * @param credentials fixed service credential resolver
+ * @param resourcesEnabled whether remote resources are enabled
+ * @return route-aware catalog
+ */
+ public static ManagedRemoteMcpCatalog forRoutes(final Set allowedRoutes, final Set localNames,
+ final RemoteServiceCredentialResolver credentials, final boolean resourcesEnabled) {
+ return forRoutes(allowedRoutes, localNames, credentials, AgentMcpResourceAdmission.create(AgentGatewayAdmissionConfig.parse(null)), resourcesEnabled);
+ }
+
+ /**
+ * Create a route-aware managed catalog sharing the gateway admission controller.
+ * @param allowedRoutes trusted routes
+ * @param localNames local tool names
+ * @param credentials fixed service credential resolver
+ * @param admission shared controller
+ * @param resourcesEnabled whether remote resources are enabled
+ * @return route-aware catalog
+ */
+ public static ManagedRemoteMcpCatalog forRoutes(final Set allowedRoutes, final Set localNames,
+ final RemoteServiceCredentialResolver credentials,
+ final AgentMcpResourceAdmission.ResourceAdmissionController admission, final boolean resourcesEnabled) {
+ return new ManagedRemoteMcpCatalog(allowedRoutes, localNames, credentials, admission, resourcesEnabled, null);
+ }
+
+ static ManagedRemoteMcpCatalog forRoutesWithVerificationTlsContext(final Set allowedRoutes, final Set localNames,
+ final RemoteServiceCredentialResolver credentials,
+ final javax.net.ssl.SSLContext verificationTlsContext) {
+ return new ManagedRemoteMcpCatalog(allowedRoutes, localNames, credentials,
+ AgentMcpResourceAdmission.create(AgentGatewayAdmissionConfig.parse(null)), false, verificationTlsContext);
+ }
+
+ private static Set fixedRoutes(final Set allowedEndpoints) {
+ return allowedEndpoints.stream().map(endpoint -> endpoint + "=").collect(java.util.stream.Collectors.toUnmodifiableSet());
+ }
+
private Mono applyUpdate(final ControlUpdate update) {
return Mono.defer(() -> {
if (update.sequence() != revision.get()) {
return Mono.empty();
}
+ if (!update.enabled()) {
+ return lifecycle.closeIdle().thenReturn(0L);
+ }
return reload(update.source(), () -> !closed && update.sequence() == revision.get()).doOnSuccess(version -> {
recordFailure(update.sequence(), "");
}).onErrorResume(error -> {
@@ -146,7 +236,7 @@ public synchronized void accept(final PluginData plugin) {
lastFailure = "ConfigurationByteLimit";
return;
}
- Sinks.EmitResult result = updates.tryEmitNext(new ControlUpdate(sequence, source));
+ Sinks.EmitResult result = updates.tryEmitNext(new ControlUpdate(sequence, source, enabled));
if (result.isFailure() && !closed) {
lifecycle.withdraw();
lastFailure = "ConfigurationQueueRejected";
@@ -174,9 +264,15 @@ private Mono reload(final String source, final BooleanSupplier stillCurren
List targets = new ArrayList<>();
for (AgentGatewayAggregationConfig.Server server : config.servers()) {
RemoteServerBinding.Config reference = new RemoteServerBinding.Config(server.name(), server.endpoint(), server.credentialRef(), server.credentialVersion());
- targets.add(RemoteServerBinding.resolve(reference, allowedEndpoints, credentials::resolve).lifecycleConfig());
+ RemoteServerBinding binding = RemoteServerBinding.resolve(reference, routes, credentials::resolve);
+ targets.add(binding.lifecycleConfig(routes.route(server.endpoint()), verificationTlsContext));
}
- return lifecycle.refresh(targets, List.of(), localNames, stillCurrent);
+ return lifecycle.refresh(targets, List.of(), localNames, stillCurrent)
+ .doOnSuccess(ignored -> {
+ if (stillCurrent.getAsBoolean()) {
+ admission.replace(AgentMcpResourceAdmission.create(config.admission()));
+ }
+ });
});
}
@@ -197,6 +293,19 @@ public Mono withSnapshot(final Function>
});
}
+ @Override
+ public AgentMcpResourceAdmission admission() {
+ return admission;
+ }
+
+ /**
+ * Current validated admission limits.
+ * @return immutable trusted configuration
+ */
+ public AgentGatewayAdmissionConfig admissionConfig() {
+ return admission.config();
+ }
+
/**
* Secret-free lifecycle diagnostics for management and verification.
* @return immutable diagnostic values
@@ -205,6 +314,10 @@ public Map diagnostics() {
Diagnostics state = diagnosticsState();
Map result = new LinkedHashMap<>(state.lifecycle().toMap());
result.put("lastFailure", state.lastFailure());
+ AgentGatewayAdmissionConfig config = admission.config();
+ result.put("admission", Map.of("globalInFlight", config.globalInFlight(), "globalQueued", config.globalQueued(),
+ "localInFlight", config.localInFlight(), "localQueued", config.localQueued(),
+ "remoteInFlight", config.remoteInFlight(), "remoteQueued", config.remoteQueued()));
return Map.copyOf(result);
}
@@ -230,6 +343,7 @@ public Mono closeAsync() {
return Mono.defer(() -> {
closed = true;
catalogMetrics.close();
+ admission.close();
worker.dispose();
scheduler.dispose();
return lifecycle.closeGracefully();
@@ -245,7 +359,7 @@ public void close() {
public record Diagnostics(RemoteCatalogLifecycle.Diagnostics lifecycle, long revision, String lastFailure) {
}
- private record ControlUpdate(long sequence, String source) {
+ private record ControlUpdate(long sequence, String source, boolean enabled) {
}
private static final class CatalogSnapshot implements Snapshot {
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java
index 9b8a7fa41edb..8f1337de4359 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java
@@ -342,7 +342,7 @@ private Mono release(final Generation generation) {
});
}
- private Mono closeIdle() {
+ Mono closeIdle() {
List> tasks = new ArrayList<>();
synchronized (lock) {
for (Generation generation : generations) {
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java
index 3588a10a1cf8..0c5c37575c36 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java
@@ -22,7 +22,6 @@
import java.net.URI;
import java.util.Objects;
-import java.util.Set;
import java.util.function.Function;
/** Immutable target and independently resolved credential binding. */
@@ -42,18 +41,17 @@ private RemoteServerBinding(final Config config, final Credential credential) {
/**
* resolve.
* @param config trusted config value
- * @param allowedEndpoints trusted allowedEndpoints value
+ * @param routes trusted approved routes
* @param localResolver trusted localResolver value
* @return operation result
*/
- public static RemoteServerBinding resolve(final Config config, final Set allowedEndpoints, final Function localResolver) {
- if (Objects.isNull(config) || Objects.isNull(allowedEndpoints) || Objects.isNull(localResolver)) {
+ public static RemoteServerBinding resolve(final Config config, final RemoteTransportRouteSet routes,
+ final Function localResolver) {
+ if (Objects.isNull(config) || Objects.isNull(routes) || Objects.isNull(localResolver)) {
throw new IllegalArgumentException("Missing controlled target configuration");
}
- // Exact configured URI, including path/port. Never resolve an Agent-provided URL.
- if (!Set.copyOf(allowedEndpoints).contains(config.endpoint())) {
- throw new SecurityException("Target is not in the configured allowlist");
- }
+ // Exact configured URI, including path/port, must also have a deployment-approved address.
+ routes.route(config.endpoint());
Credential credential;
try {
credential = localResolver.apply(config);
@@ -80,16 +78,35 @@ String authorization() {
}
/**
- * new Client.
+ * new Client bound to the historical fixed-IP route.
* @return operation result
*/
public RequestScopedMcpClient newClient() {
- return new RequestScopedMcpClient(this, event -> {
+ return newClient(RemoteTransportRoute.fixed(config.endpoint()));
+ }
+
+ /**
+ * new Client bound to an approved route.
+ * @param route trusted immutable route
+ * @return operation result
+ */
+ public RequestScopedMcpClient newClient(final RemoteTransportRoute route) {
+ return newClient(route, null);
+ }
+
+ /**
+ * new Client with an explicit test-only TLS context.
+ * @param route trusted immutable route
+ * @param testContext fixture TLS context
+ * @return operation result
+ */
+ RequestScopedMcpClient newClient(final RemoteTransportRoute route, final javax.net.ssl.SSLContext testContext) {
+ return new RequestScopedMcpClient(this, route, event -> {
if (LOG.isDebugEnabled()) {
LOG.debug("Remote MCP response server={} method={} id={} status={} bytes={}",
event.get("server"), event.get("method"), event.get("id"), event.get("status"), event.get("bytes"));
}
- });
+ }, testContext);
}
/**
@@ -97,7 +114,26 @@ public RequestScopedMcpClient newClient() {
* @return operation result
*/
public RemoteCatalogLifecycle.Config lifecycleConfig() {
- return new RemoteCatalogLifecycle.Config(config.name(), config.credentialVersion(), this::newClient);
+ return lifecycleConfig(RemoteTransportRoute.fixed(config.endpoint()));
+ }
+
+ /**
+ * lifecycle Config with deployment-approved route.
+ * @param route trusted immutable route
+ * @return operation result
+ */
+ public RemoteCatalogLifecycle.Config lifecycleConfig(final RemoteTransportRoute route) {
+ return lifecycleConfig(route, null);
+ }
+
+ /**
+ * lifecycle Config with a verification-only TLS context.
+ * @param route trusted immutable route
+ * @param verificationTlsContext fixture TLS context, never production configuration
+ * @return lifecycle configuration
+ */
+ RemoteCatalogLifecycle.Config lifecycleConfig(final RemoteTransportRoute route, final javax.net.ssl.SSLContext verificationTlsContext) {
+ return new RemoteCatalogLifecycle.Config(config.name(), config.credentialVersion(), () -> newClient(route, verificationTlsContext));
}
@Override
@@ -142,4 +178,5 @@ public String toString() {
return "ServiceCredential[REDACTED]";
}
}
+
}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java
index 2854ff2d519b..1f014c980fcd 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java
@@ -55,10 +55,26 @@ public void connectFailed(final URI uri, final SocketAddress address, final IOEx
* @param uri trusted uri value
*/
public static void endpoint(final URI uri) {
- // No DNS: JDK connects to the configured address and validates HTTPS against its IP SAN.
+ // Fixed IP keeps the historical JDK path; controlled hostnames require an approved route.
org.apache.shenyu.common.dto.AgentGatewayAggregationConfig.validateEndpoint(uri);
}
+ /**
+ * Validate a historical fixed-IP target.
+ * @param uri trusted uri value
+ */
+ public static void fixedEndpoint(final URI uri) {
+ org.apache.shenyu.common.dto.AgentGatewayAggregationConfig.validateFixedEndpoint(uri);
+ }
+
+ /**
+ * Validate an HTTPS hostname without resolving it.
+ * @param uri trusted uri value
+ */
+ public static void httpsHostname(final URI uri) {
+ org.apache.shenyu.common.dto.AgentGatewayAggregationConfig.validateHttpsHostnameEndpoint(uri);
+ }
+
/**
* session.
* @param values trusted values value
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRoute.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRoute.java
new file mode 100644
index 000000000000..1d6b4c16b410
--- /dev/null
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRoute.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.agent.gateway.remote;
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.util.Objects;
+
+/**
+ * Immutable route from an approved target URI to its single connection address.
+ * DNS targets must be accompanied by an operator-approved address, so the JDK
+ * never performs an implicit second resolution after policy validation.
+ */
+final class RemoteTransportRoute {
+
+ private final URI endpoint;
+
+ private final InetAddress address;
+
+ private RemoteTransportRoute(final URI endpoint, final InetAddress address) {
+ this.endpoint = endpoint;
+ this.address = address;
+ }
+
+ /**
+ * Create a route whose connection address is the endpoint's fixed IPv4 address.
+ * @param endpoint approved fixed-IP endpoint
+ * @return immutable route
+ */
+ static RemoteTransportRoute fixed(final URI endpoint) {
+ RemoteTransportPolicy.fixedEndpoint(endpoint);
+ try {
+ return new RemoteTransportRoute(endpoint, InetAddress.getByName(endpoint.getHost()));
+ } catch (UnknownHostException error) {
+ throw new IllegalArgumentException("Invalid fixed MCP endpoint address");
+ }
+ }
+
+ /**
+ * Create a controlled DNS route without querying DNS.
+ * @param endpoint approved HTTPS hostname endpoint
+ * @param approvedAddress operator-approved literal IPv4 address
+ * @return immutable route
+ */
+ static RemoteTransportRoute controlledDns(final URI endpoint, final String approvedAddress) {
+ RemoteTransportPolicy.httpsHostname(endpoint);
+ if (Objects.isNull(approvedAddress) || !approvedAddress.matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}")) {
+ throw new IllegalArgumentException("Invalid approved MCP address");
+ }
+ try {
+ InetAddress address = InetAddress.getByName(approvedAddress);
+ if (address.isAnyLocalAddress() || address.isLinkLocalAddress()
+ || address.isMulticastAddress() || address.getHostAddress().startsWith("224.")
+ || address.getHostAddress().startsWith("240.") || "255.255.255.255".equals(address.getHostAddress())) {
+ throw new IllegalArgumentException("Unapproved MCP address class");
+ }
+ return new RemoteTransportRoute(endpoint, address);
+ } catch (UnknownHostException error) {
+ throw new IllegalArgumentException("Invalid approved MCP address");
+ }
+ }
+
+ URI endpoint() {
+ return endpoint;
+ }
+
+ InetAddress address() {
+ return address;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ return other instanceof RemoteTransportRoute route && endpoint.equals(route.endpoint) && address.equals(route.address);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(endpoint, address);
+ }
+
+ @Override
+ public String toString() {
+ return "RemoteTransportRoute[endpoint=" + endpoint.getHost() + ", address=" + address.getHostAddress() + "]";
+ }
+}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRouteSet.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRouteSet.java
new file mode 100644
index 000000000000..f81fd333b8de
--- /dev/null
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRouteSet.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.agent.gateway.remote;
+
+import java.net.URI;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Immutable deployment-owned routes; hostname targets fail closed until approved. */
+final class RemoteTransportRouteSet {
+
+ private final Map routes;
+
+ private RemoteTransportRouteSet(final Map routes) {
+ this.routes = Map.copyOf(routes);
+ }
+
+ /**
+ * Parse endpoint=address route declarations.
+ * @param declarations deployment-owned declarations, never Admin plugin data
+ * @return immutable routes
+ */
+ static RemoteTransportRouteSet parse(final Collection declarations) {
+ if (Objects.isNull(declarations)) {
+ throw new IllegalArgumentException("Missing controlled MCP routes");
+ }
+ Map parsed = declarations.stream()
+ .map(RemoteTransportRouteSet::parseRoute)
+ .collect(Collectors.toUnmodifiableMap(RemoteTransportRoute::endpoint, route -> route));
+ return new RemoteTransportRouteSet(parsed);
+ }
+
+ private static RemoteTransportRoute parseRoute(final String declaration) {
+ if (Objects.isNull(declaration) || declaration.length() > 2048) {
+ throw new IllegalArgumentException("Invalid controlled MCP route");
+ }
+ int separator = declaration.lastIndexOf('=');
+ if (separator < 1) {
+ throw new IllegalArgumentException("Invalid controlled MCP route");
+ }
+ URI endpoint = URI.create(declaration.substring(0, separator));
+ String address = declaration.substring(separator + 1);
+ if (isLiteralIpv4(endpoint.getHost())) {
+ if (!address.isEmpty()) {
+ throw new IllegalArgumentException("Fixed-IP route cannot override its endpoint address");
+ }
+ return RemoteTransportRoute.fixed(endpoint);
+ }
+ if (address.isEmpty()) {
+ throw new IllegalArgumentException("Controlled hostname route requires an address");
+ }
+ return RemoteTransportRoute.controlledDns(endpoint, address);
+ }
+
+ private static boolean isLiteralIpv4(final String value) {
+ return Objects.nonNull(value) && value.matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}");
+ }
+
+ Set endpoints() {
+ return routes.keySet();
+ }
+
+ RemoteTransportRoute route(final URI endpoint) {
+ RemoteTransportRoute route = routes.get(endpoint);
+ if (Objects.isNull(route) || !route.endpoint().equals(endpoint)) {
+ throw new SecurityException("Target has no approved transport route");
+ }
+ return route;
+ }
+
+ @Override
+ public String toString() {
+ return "RemoteTransportRouteSet[endpoints=" + routes.size() + "]";
+ }
+}
diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java
index e0d2201eddbc..d21578964f3e 100644
--- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java
+++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java
@@ -24,32 +24,29 @@
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.modelcontextprotocol.common.McpTransportContext;
import io.modelcontextprotocol.spec.McpSchema;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpHost;
import org.apache.shenyu.common.tracing.AgentTraceContext;
import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType;
-import reactor.core.publisher.Sinks;
-import java.io.ByteArrayOutputStream;
import java.net.URI;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpResponse;
+import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionException;
-import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.Flow;
+import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
@@ -71,7 +68,9 @@ public final class RequestScopedMcpClient implements RemoteMcpEndpoint {
private static final int MAX_IN_FLIGHT = 64;
- private final HttpClient http;
+ private final RemoteTransportRoute route;
+
+ private final ApacheRemoteMcpTransport http;
private final URI endpoint;
@@ -87,7 +86,7 @@ public final class RequestScopedMcpClient implements RemoteMcpEndpoint {
private final AtomicInteger active = new AtomicInteger();
- private final Set> inFlight = ConcurrentHashMap.newKeySet();
+ private final Set> inFlight = ConcurrentHashMap.newKeySet();
private volatile String session;
@@ -110,12 +109,16 @@ public RequestScopedMcpClient(final RemoteServerBinding binding, final java.util
}
RequestScopedMcpClient(final RemoteServerBinding binding, final java.util.function.Consumer