Skip to content

Commit 3882f85

Browse files
committed
test(agent-gateway): document and verify MCP entry contract
1 parent 0c35745 commit 3882f85

2 files changed

Lines changed: 214 additions & 2 deletions

File tree

‎shenyu-plugin/shenyu-plugin-agent-gateway/README.md‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,138 @@ not enabled by choosing `responseMode=json`.
117117
| Missing, wildcard-only, or required type with `q=0` | 406 | 406 |
118118
| Malformed media type | 400 | 400 |
119119

120+
### Protocol support and compatibility
121+
122+
This is an implementation contract for the tools-only entry, not a claim of
123+
complete MCP conformance or final protocol approval. The PR remains draft while
124+
the protocol choice and wider Agent Gateway MCP contract are stabilized. The
125+
[fixed versioning contract](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning)
126+
uses per-request version metadata rather than an initialization handshake.
127+
128+
| Boundary | Current entry behavior |
129+
| --- | --- |
130+
| Version | Only `2026-07-28`; no implicit fallback or translation to older revisions |
131+
| `server/discover` | Advertises that version and tools capability only |
132+
| `tools/list` | Complete permission-filtered local list; any supplied cursor is rejected |
133+
| `tools/call` | One authorized local Provider invocation per subscription, without retry |
134+
| Successful response | JSON object, or one final `event: message` SSE frame; no progress stream |
135+
| Lifecycle | No `initialize`, protocol session, GET listener or session DELETE endpoint |
136+
| Other methods | Rejected; no prompts/resources, MRTR, Tasks or subscriptions |
137+
138+
These behaviors apply only after an enabled, continued MCP rule matches. The
139+
plugin does not expose a universal `/mcp` path. Unmatched or disabled traffic,
140+
LLM rules and independently routed legacy MCP traffic keep their existing chain.
141+
An initialization-based client must use a separately configured legacy endpoint
142+
or an explicit client adapter; this entry does not make SDK 0.17.0 interoperable
143+
with the newer wire contract. Remote SDK experiments are not part of this module.
144+
145+
The parser accepts one UTF-8 JSON-RPC 2.0 object with a string or integral ID,
146+
object `params`, and object `_meta`. It requires a string
147+
`io.modelcontextprotocol/protocolVersion` and object
148+
`io.modelcontextprotocol/clientCapabilities`. Batch, notification, response and
149+
request/response-hybrid bodies are rejected. Client metadata is not trusted
150+
identity or a replacement for server-side grants.
151+
152+
| Header | Validated against |
153+
| --- | --- |
154+
| `MCP-Protocol-Version` | `_meta.io.modelcontextprotocol/protocolVersion` |
155+
| `Mcp-Method` | JSON-RPC `method` |
156+
| `Mcp-Name`, for `tools/call` | `params.name`; canonical Base64 sentinel decoding is supported |
157+
158+
Each mirrored header must have one safe value. Header names are case-insensitive,
159+
but values must match exactly. `Content-Type` must be UTF-8 `application/json`.
160+
Absent Origin is not authentication; a supplied Origin must exactly match the
161+
rule's allowed origins, and duplicate origins are rejected. A client-supplied
162+
session ID does not select identity or request state.
163+
164+
### Results, errors and authorization
165+
166+
Visible and callable tools share the intersection of registered tools, rule
167+
`allowedTools` and trusted identity grants. An empty intersection grants no
168+
calls. With a valid rule/registry configuration, unknown and invisible names
169+
have the same public denial. A rule referring to an unregistered tool instead
170+
fails as server misconfiguration, not a successful empty list. Record-level
171+
authorization belongs to the Provider; tool-name permission alone is not enough.
172+
173+
The current Provider returns a business JSON object. The entry encodes it as
174+
`structuredContent` plus one text item and `isError=false`. Declared argument
175+
validation failures and explicit `AgentToolExecutionException` failures instead
176+
produce a sanitized `isError=true` result. Unexpected exceptions and empty
177+
Provider completion are internal protocol errors. Providers must not return an
178+
entire remote `CallToolResult` expecting lossless passthrough; native remote
179+
results need a separate aggregation adapter, outside this PR.
180+
181+
Successful discovery/list results use `resultType=complete`, `ttlMs=0` and
182+
`cacheScope=private`; calls also have `resultType=complete`. Each result includes
183+
server information in `_meta`; this does not create a shared identity cache.
184+
185+
The following matrix assumes an authenticated request passing preceding checks;
186+
it does not specify precedence when several inputs are invalid.
187+
188+
| Condition | HTTP | Body |
189+
| --- | --- | --- |
190+
| Invalid Origin / non-POST / unsupported media / rejected Accept | 403 / 405 / 415 / 406 | Ordinary JSON transport error; malformed media headers use 400 |
191+
| Missing trusted identity | 401 | Ordinary JSON transport error |
192+
| Invalid JSON or UTF-8 | 400 | JSON-RPC error `-32700`, null ID |
193+
| Invalid envelope, including batch or notification | 400 | JSON-RPC error `-32600`, null ID |
194+
| Invalid metadata or parameters; supplied list cursor | 400 | JSON-RPC error `-32602` |
195+
| Missing, duplicate or mismatched mirrored header | 400 | JSON-RPC error `-32020` |
196+
| Unsupported version / method | 400 / 404 | JSON-RPC error `-32022` with supported versions / `-32601` |
197+
| Unknown or forbidden tool | 403 | JSON-RPC error `-32602` |
198+
| Missing required client capability | 400 | JSON-RPC error `-32021` with the missing capability tree |
199+
| Declared Provider argument or business failure | 200 | JSON-RPC result with `isError=true` |
200+
| Invalid server configuration / unexpected tool failure / encoded response overflow | 500 | Configuration or sanitized internal error; no tool retry |
201+
| Request body overflow / execution deadline | 413 / 504 | Ordinary JSON transport error |
202+
203+
Transport and JSON-RPC error responses are JSON in either response mode,
204+
including failures occurring after body parsing. Business failures are results
205+
with `isError=true` and still follow `responseMode`. Parsed protocol errors
206+
preserve the available RPC ID; preflight errors
207+
do not parse the body to recover one. Once the response is committed, the handler
208+
propagates a failure rather than writing a second response. A disconnected client
209+
is not guaranteed to receive an error body.
210+
211+
### Deadlines, isolation and configuration limits
212+
213+
One execution budget covers identity resolution, body acquisition, parsing,
214+
Provider execution, encoding and response writing. The invocation receives its
215+
absolute deadline. The handler cancels the current reactive subscription on
216+
timeout or downstream cancellation, without closing shared registry/pool state.
217+
Termination cleanup is request-local; equal client RPC IDs or supplied session
218+
IDs do not merge calls. Adapters must honor cancellation for their own transport;
219+
this entry cannot kill blocking code, roll back a side effect or stop billing.
220+
221+
After execution has terminated, an uncommitted error write has a separate
222+
best-effort budget of at most `min(1000, timeoutMs)` milliseconds. It does not
223+
extend the Provider's execution allowance. Earlier server filters/connection
224+
policies have their own budgets.
225+
226+
| MCP rule field | Default | Bounds / behavior |
227+
| --- | --- | --- |
228+
| `allowedTools` / `allowedOrigins` | Empty sets | Explicit unique names / exact HTTP(S) origins; no wildcard grant |
229+
| `responseMode` | `json` | `json` or `sse`; does not relax Accept validation |
230+
| `timeoutMs` | 30000 | Integer 100–120000 |
231+
| `maxRequestBytes` | 262144 | Integer 1024–1048576, UTF-8 bytes |
232+
| `maxResponseBytes` | 1048576 | Integer 1024–4194304, includes SSE framing |
233+
234+
Admin create/update/import rejects unknown fields and invalid known values.
235+
Runtime parsing permits unknown fields but rejects invalid known values. Rules
236+
are captured per subscription; later updates affect new requests, not the
237+
in-flight snapshot. `configurationVersion` is a node-local generation, not an
238+
Admin revision. Tool registration is frozen at startup; dynamic targets and
239+
credential/session lifecycle are not provided. Server codec limits may be
240+
smaller than rule limits and remain effective.
241+
242+
### Contract regression coverage
243+
244+
`AgentMcpRequestParserTest` covers envelope, version and mirrored-header checks;
245+
`AgentMcpDispatcherTest` covers discovery, permission filtering, result/error
246+
semantics and asynchronous isolation. `AgentMcpHttpHandlerTest` covers both
247+
response modes, strict Accept, HTTP error mapping, byte limits and cancellation
248+
through body, execution and writing. Config/registry/plugin/Starter tests cover
249+
assembly and snapshot boundaries. Passing these targeted tests is not complete
250+
MCP, OAuth, full-project or arbitrary-client acceptance, nor a reviewer approval.
251+
120252
### Request context
121253

122254
`AgentTrafficContext` is immutable and is created per subscription. It contains

‎shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandlerTest.java‎

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext;
2626
import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity;
2727
import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver;
28+
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolExecutionException;
2829
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolInvocation;
2930
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider;
3031
import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry;
@@ -309,6 +310,83 @@ void shouldPreserveProtocolErrorAndNeverInvokeInvalidRequest() {
309310
assertEquals(0, calls.get());
310311
}
311312

313+
@ParameterizedTest
314+
@CsvSource({
315+
"json,legacy-version,400,-32022", "sse,legacy-version,400,-32022",
316+
"json,unknown-version,400,-32022", "sse,unknown-version,400,-32022",
317+
"json,unknown-method,404,-32601", "sse,unknown-method,404,-32601",
318+
"json,notification,400,-32600", "sse,notification,400,-32600",
319+
"json,batch,400,-32600", "sse,batch,400,-32600",
320+
"json,cursor,400,-32602", "sse,cursor,400,-32602",
321+
"json,header-mismatch,400,-32020", "sse,header-mismatch,400,-32020",
322+
"json,invalid-capabilities,400,-32602", "sse,invalid-capabilities,400,-32602"
323+
})
324+
void shouldPreserveToolsOnlyHttpErrorContract(final String mode, final String scenario, final int status, final int code) {
325+
String method = "unknown-method".equals(scenario) ? "initialize" : "cursor".equals(scenario) ? "tools/list" : "tools/call";
326+
JsonObject request = JsonParser.parseString(body(method)).getAsJsonObject();
327+
JsonObject params = request.getAsJsonObject("params");
328+
String version = scenario.endsWith("-version") ? "legacy-version".equals(scenario) ? "2025-06-18" : "1900-01-01" : AgentMcpRequestParser.VERSION;
329+
MockServerHttpRequest.BodyBuilder headers = MockServerHttpRequest.method(HttpMethod.POST, "/agent");
330+
headers.contentType(MediaType.APPLICATION_JSON).header(HttpHeaders.ACCEPT, "application/json, text/event-stream")
331+
.header("MCP-Protocol-Version", version).header("Mcp-Method", method);
332+
if ("tools/call".equals(method)) {
333+
headers.header("Mcp-Name", "header-mismatch".equals(scenario) ? "another-tool" : "read");
334+
}
335+
if (scenario.endsWith("-version")) {
336+
params.getAsJsonObject("_meta").addProperty("io.modelcontextprotocol/protocolVersion", version);
337+
} else if ("notification".equals(scenario)) {
338+
request.remove("id");
339+
} else if ("cursor".equals(scenario)) {
340+
params.addProperty("cursor", "");
341+
} else if ("invalid-capabilities".equals(scenario)) {
342+
params.getAsJsonObject("_meta").addProperty("io.modelcontextprotocol/clientCapabilities", false);
343+
}
344+
String payload = "batch".equals(scenario) ? "[" + request + "]" : request.toString();
345+
AgentToolProvider tool = provider(input -> Mono.just(input.getArguments()));
346+
MockServerWebExchange exchange = MockServerWebExchange.from(headers.body(payload));
347+
execute(handler(tool), exchange, "{\"responseMode\":\"" + mode + "\"}");
348+
assertEquals(status, exchange.getResponse().getStatusCode().value());
349+
assertEquals(MediaType.APPLICATION_JSON, exchange.getResponse().getHeaders().getContentType());
350+
assertFalse(exchange.getResponse().getHeaders().containsKey("Mcp-Session-Id"));
351+
JsonObject response = JsonParser.parseString(exchange.getResponse().getBodyAsString().block()).getAsJsonObject();
352+
assertEquals(code, response.getAsJsonObject("error").get("code").getAsInt());
353+
if ("notification".equals(scenario) || "batch".equals(scenario)) {
354+
assertTrue(response.get("id").isJsonNull());
355+
} else {
356+
assertEquals("client-id", response.get("id").getAsString());
357+
}
358+
if (scenario.endsWith("-version")) {
359+
assertEquals(AgentMcpRequestParser.VERSION, response.getAsJsonObject("error").getAsJsonObject("data").getAsJsonArray("supported").get(0).getAsString());
360+
}
361+
verify(tool, never()).validate(org.mockito.ArgumentMatchers.any());
362+
verify(tool, never()).invoke(org.mockito.ArgumentMatchers.any());
363+
}
364+
365+
@ParameterizedTest
366+
@CsvSource({"json", "sse"})
367+
void shouldWriteBusinessFailureInChosenResponseModeWithoutRetry(final String mode) {
368+
AtomicInteger calls = new AtomicInteger();
369+
AgentToolProvider tool = provider(input -> {
370+
calls.incrementAndGet();
371+
return Mono.error(new AgentToolExecutionException("provider-private-diagnostic"));
372+
});
373+
MockServerWebExchange exchange = exchange("tools/call", body("tools/call"));
374+
execute(handler(tool), exchange, "{\"responseMode\":\"" + mode + "\"}");
375+
assertEquals(200, exchange.getResponse().getStatusCode().value());
376+
assertEquals("sse".equals(mode) ? MediaType.TEXT_EVENT_STREAM : MediaType.APPLICATION_JSON, exchange.getResponse().getHeaders().getContentType());
377+
String payload = exchange.getResponse().getBodyAsString().block();
378+
assertFalse(payload.contains("provider-private-diagnostic"));
379+
if ("sse".equals(mode)) {
380+
assertEquals(1, payload.split("event: message", -1).length - 1);
381+
payload = payload.substring(payload.indexOf("data: ") + 6).trim();
382+
}
383+
JsonObject response = JsonParser.parseString(payload).getAsJsonObject();
384+
assertEquals("client-id", response.get("id").getAsString());
385+
assertFalse(response.has("error"));
386+
assertTrue(response.getAsJsonObject("result").get("isError").getAsBoolean());
387+
assertEquals(1, calls.get());
388+
}
389+
312390
@Test
313391
void shouldReleasePooledBodyOnNormalCompletionAndOverflow() {
314392
NettyDataBuffer normal = pooled(body("tools/list"));
@@ -423,8 +501,10 @@ void shouldCancelOnlyOneHttpCallWithTheSameClientId() {
423501
AgentToolProvider tool = provider(input -> "A".equals(input.getSubject())
424502
? Mono.<JsonObject>never().doOnSubscribe(subscription -> started.set(true)).doOnCancel(() -> cancelled.set(true)) : survivor.asMono());
425503
AgentMcpHttpHandler handler = handler(next -> Mono.just(new AgentMcpIdentity(next.getRequest().getHeaders().getFirst("Test-Verified-Identity"), Set.of("read"))), tool);
426-
MockServerWebExchange first = MockServerWebExchange.from(builder(HttpMethod.POST, "tools/call").header("Test-Verified-Identity", "A").body(body("tools/call")));
427-
MockServerWebExchange second = MockServerWebExchange.from(builder(HttpMethod.POST, "tools/call").header("Test-Verified-Identity", "B").body(body("tools/call")));
504+
MockServerWebExchange first = MockServerWebExchange.from(builder(HttpMethod.POST, "tools/call").header("Test-Verified-Identity", "A")
505+
.header("Mcp-Session-Id", "client-chosen-session").body(body("tools/call")));
506+
MockServerWebExchange second = MockServerWebExchange.from(builder(HttpMethod.POST, "tools/call").header("Test-Verified-Identity", "B")
507+
.header("Mcp-Session-Id", "client-chosen-session").body(body("tools/call")));
428508
StepVerifier.create(handler.handle(second, config("{}"), traffic, 7)).then(() -> {
429509
StepVerifier.create(handler.handle(first, config("{}"), traffic, 7)).then(() -> assertTrue(started.get())).thenCancel().verify();
430510
assertTrue(cancelled.get());

0 commit comments

Comments
 (0)