Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
4b3ef30
feat(agent-gateway): authorize tools from trusted identities
BobSong-dev Oct 18, 2026
6788e7b
feat(agent-gateway): authorize tools from trusted identities
BobSong-dev Oct 19, 2026
19eea6f
feat(agent-gateway): unify request context and terminal observation
BobSong-dev Oct 19, 2026
3c09a39
merge: reconcile master retry policy with agent observation
BobSong-dev Oct 20, 2026
dd6d878
merge: reconcile agent context tests with latest master
BobSong-dev Oct 20, 2026
f4392ce
feat(agent-gateway): add runtime governance observability
BobSong-dev Oct 21, 2026
5d97d96
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 21, 2026
e451ec6
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 23, 2026
8aba05c
feat(agent-gateway): add unified invocation auditing
BobSong-dev Oct 23, 2026
4721203
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 23, 2026
19d83df
feat(agent-gateway): add bounded mcp resource admission
BobSong-dev Oct 24, 2026
4a9544d
merge: reconcile agent observation with latest master
BobSong-dev Oct 25, 2026
2324714
ci: re-run agent gateway checks
BobSong-dev Oct 25, 2026
b015555
test(agent-gateway): locate migration null fixture structurally
BobSong-dev Oct 25, 2026
c343fb4
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 25, 2026
423278e
test(agent-gateway): harden migration null fixture
BobSong-dev Oct 26, 2026
4736952
test(agent-gateway): harden migration null fixture
BobSong-dev Oct 26, 2026
1664140
fix(agent-gateway): address observation and ordering review
BobSong-dev Oct 26, 2026
be45a5f
Merge remote-tracking branch 'fork/integration/agent-gateway-p003' in…
BobSong-dev Oct 26, 2026
020fd64
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 26, 2026
cad1e72
merge: reconcile agent integration with latest master
BobSong-dev Oct 26, 2026
5b0a459
fix(agent-gateway): preserve metrics and tracing compatibility
BobSong-dev Oct 26, 2026
5e72769
Merge commit 'cad1e72320a4c2bf7c9e952762450feca8599a81' into feat/age…
BobSong-dev Oct 26, 2026
fa79ddd
Merge commit '5b0a4597c0a3a3fba57a622a18d1aed2fe3a702b' into feat/age…
BobSong-dev Oct 26, 2026
e69b7cc
fix(agent-gateway): align audit module version
BobSong-dev Oct 26, 2026
c8b7a32
chore: retrigger checks
BobSong-dev Oct 26, 2026
e1f4692
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 26, 2026
f9eb7ba
fix(agent-gateway): preserve released upgrade migrations
BobSong-dev Oct 27, 2026
a34127b
test(admin): cover plugin tables in migration contract fixtures
BobSong-dev Oct 27, 2026
3f417a3
merge: reconcile governance observability with latest master
BobSong-dev Oct 27, 2026
0fac12d
Merge commit 'a34127bc8a492e6de33efdb48285b3abd6c476e6' into HEAD
BobSong-dev Oct 27, 2026
6e1486e
Merge commit '3f417a358a0f5c4f37016235f7a564fdcc3c8456' into HEAD
BobSong-dev Oct 27, 2026
1b68fcb
Merge remote-tracking branch 'origin/master' into HEAD
BobSong-dev Oct 27, 2026
d093d0e
fix(ai-proxy): preserve audit mapping after master merge
BobSong-dev Oct 27, 2026
cb82930
Merge commit 'a34127bc8a492e6de33efdb48285b3abd6c476e6' into integrat…
BobSong-dev Oct 27, 2026
89a2fe2
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 27, 2026
4f58def
merge: reconcile agent admission with latest master
BobSong-dev Oct 27, 2026
cb5c276
fix(agent-gateway): align migration baseline fixes
BobSong-dev Oct 27, 2026
9545498
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 28, 2026
d25e1bb
Merge commit 'a34127bc8a492e6de33efdb48285b3abd6c476e6' into feat/age…
BobSong-dev Oct 28, 2026
361ee75
fix(agent-gateway): preserve admission state across reloads
BobSong-dev Oct 28, 2026
0b7bfb3
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 28, 2026
220521a
fix(agent-gateway): drain admission queues after limit reloads
BobSong-dev Oct 28, 2026
98b1f42
fix(agent-gateway): synchronize admission queue promotion
BobSong-dev Oct 28, 2026
8fe70c2
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 28, 2026
6b1207c
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 28, 2026
1a05008
Merge remote-tracking branch 'fork/integration/agent-gateway-p003' in…
BobSong-dev Oct 28, 2026
e9dc976
Merge remote-tracking branch 'fork/integration/agent-gateway-p105' in…
BobSong-dev Oct 28, 2026
4c6d01b
fix(agent-gateway): preserve rejection audits across master merge
BobSong-dev Oct 30, 2026
504d5bd
fix(agent-gateway): serialize admission reloads and reject expired work
BobSong-dev Oct 30, 2026
6c14893
fix(agent-gateway): record local attempts only after admission
BobSong-dev Oct 30, 2026
6cda864
Merge latest master into audit publication base
BobSong-dev Nov 5, 2026
c19a068
Merge current audit publication baseline into admission baseline
BobSong-dev Nov 5, 2026
63b02d3
fix(metrics): preserve single registration when reconciling audit bas…
BobSong-dev Nov 5, 2026
a73d8b2
Merge branch 'integration/audit-publication-20261105' into integratio…
BobSong-dev Nov 5, 2026
b9a5bdc
fix(ai-proxy): remove stale transport import from integration baseline
BobSong-dev Nov 5, 2026
79a060e
fix(metrics): retain runtime registration after baseline synchronization
BobSong-dev Nov 5, 2026
b26fd8e
Merge branch 'integration/audit-publication-20261105' into integratio…
BobSong-dev Nov 5, 2026
0fdd9db
feat(agent-gateway): connect controlled HTTPS MCP endpoints
BobSong-dev Nov 5, 2026
c367e15
Merge branch 'integration/admission-publication-20261105' into feat/m…
BobSong-dev Nov 5, 2026
6fa0abc
ci: rerun admission checks after intermittent admin failures
BobSong-dev Nov 5, 2026
85e8e93
ci: rerun HTTPS checks after discovery integration timeout
BobSong-dev Nov 5, 2026
ab421f7
test(admin): await recorded master selection failures
BobSong-dev Nov 5, 2026
98da9ea
test(admin): respond to HTTP probes in ZooKeeper discovery fixture
BobSong-dev Nov 5, 2026
c3487f5
test(agent-gateway): clarify logical audit target propagation
BobSong-dev Nov 5, 2026
594fead
fix(ci): reconcile MCP admission with master test fixes
BobSong-dev Nov 9, 2026
a45f700
fix(ci): reconcile HTTPS baseline with master discovery fixture
BobSong-dev Nov 9, 2026
2c4288d
ci: retrigger checks for MCP resource admission
BobSong-dev Nov 9, 2026
1a6ded2
ci: retry checks after Kubernetes download timeouts
BobSong-dev Nov 9, 2026
41c792d
merge: reconcile audit integration with current master
BobSong-dev Nov 12, 2026
226f40e
merge: reconcile resource admission with current audit baseline
BobSong-dev Nov 12, 2026
57f6f3b
merge: reconcile HTTPS catalog tests with shared config contracts
BobSong-dev Nov 12, 2026
1085737
merge: retain HTTPS transport with current managed dependencies
BobSong-dev Nov 18, 2026
8dba5a1
chore: reconcile MCP HTTPS routes with accepted audit baseline
BobSong-dev Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions docs/agent-gateway-controlled-mcp-https.md
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 43 additions & 0 deletions docs/agent-gateway-resource-admission.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,11 @@
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>${httpasyncclient.version}</version>
</dependency>

<dependency>
<groupId>com.netflix.eureka</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -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);

Check warning on line 34 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q1

[Q1] '128' is a magic number. Reuse an existing constant or declare a named constant with its unit.

Check warning on line 34 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q2

[Q2] The string "globalInFlight" appears 3 times in this file. Extract it into a constant.
range("globalQueued", globalQueued, 0, 256);

Check warning on line 35 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q1

[Q1] '256' is a magic number. Reuse an existing constant or declare a named constant with its unit.

Check warning on line 35 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q2

[Q2] The string "globalQueued" appears 3 times in this file. Extract it into a constant.
range("localInFlight", localInFlight, 1, 64);

Check warning on line 36 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q1

[Q1] '64' is a magic number. Reuse an existing constant or declare a named constant with its unit.

Check warning on line 36 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q2

[Q2] The string "localInFlight" appears 3 times in this file. Extract it into a constant.
range("localQueued", localQueued, 0, 128);

Check warning on line 37 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q1

[Q1] '128' is a magic number. Reuse an existing constant or declare a named constant with its unit.

Check warning on line 37 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q2

[Q2] The string "localQueued" appears 3 times in this file. Extract it into a constant.
range("remoteInFlight", remoteInFlight, 1, 32);

Check warning on line 38 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q1

[Q1] '32' is a magic number. Reuse an existing constant or declare a named constant with its unit.

Check warning on line 38 in shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q2

[Q2] The string "remoteInFlight" appears 3 times in this file. Extract it into a constant.
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<String> 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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@
import java.util.Set;

/** Strict, secret-free configuration shared by Admin and gateway. */
public record AgentGatewayAggregationConfig(String revision, List<Server> servers) {
public record AgentGatewayAggregationConfig(String revision, List<Server> 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");
Expand All @@ -53,7 +55,7 @@ public record AgentGatewayAggregationConfig(String revision, List<Server> 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");
Expand All @@ -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<String> 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()) {
Expand All @@ -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");
Expand All @@ -97,17 +109,58 @@ private static void fields(final JsonNode node, final Set<String> 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())
|| Objects.nonNull(endpoint.getRawQuery()) || Objects.nonNull(endpoint.getRawFragment())
|| !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");
Expand Down
Original file line number Diff line number Diff line change
@@ -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<AgentAdmissionMetrics> SOURCES = ConcurrentHashMap.newKeySet();

private final Supplier<List<Snapshot>> source;

private AgentAdmissionMetrics(final Supplier<List<Snapshot>> 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<List<Snapshot>> source) {
AgentAdmissionMetrics value = new AgentAdmissionMetrics(source);
SOURCES.add(value);
return value;
}

/** Aggregate all live controller states.
* @return immutable snapshots
*/
public static List<Snapshot> 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
}
}
Loading
Loading