Skip to content

Commit 1596ee5

Browse files
committed
fix(client): remove 405 from discover-probe initialize fallback
405 means the POST endpoint rejected the request method, so retrying initialize over the same transport is not useful. The spec's 405 handling is the AutoDetect transport's SSE fallback. Remove MethodNotAllowed from McpClientImpl's HTTP-layer fallback catch and route the regression coverage through the AutoDetect test matrix. Also realign three AutoDetect transport tests that still encoded the pre-allowlist 'always fall back to SSE' behavior (403/415), switching them to an allowlisted 404 so they continue to exercise the dual-failure surface path.
1 parent 32ef18a commit 1596ee5

3 files changed

Lines changed: 103 additions & 41 deletions

File tree

‎src/ModelContextProtocol.Core/Client/McpClientImpl.cs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -382,16 +382,18 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
382382
}
383383
catch (HttpRequestException ex) when (
384384
ex.GetStatusCode() is HttpStatusCode.BadRequest
385-
or HttpStatusCode.NotFound
386-
or HttpStatusCode.MethodNotAllowed)
385+
or HttpStatusCode.NotFound)
387386
{
388387
// A server predating SEP-2575 can reject the session-less server/discover POST at the
389-
// HTTP layer instead of with a JSON-RPC error: 400 when it cannot parse the request,
390-
// 404 when it requires Mcp-Session-Id on every non-initialize POST, and 405 when it
391-
// does not accept POST at this endpoint at all. A 400 carrying a structured JSON-RPC
392-
// error is surfaced as McpProtocolException and handled above, so anything reaching
393-
// here is plain or empty. Either way this is an initialize-handshake server, so fall
394-
// back. Other statuses stay uncaught and surface to the caller.
388+
// HTTP layer instead of with a JSON-RPC error: 400 when it cannot parse the request, or
389+
// 404 when it requires Mcp-Session-Id on every non-initialize POST. A 400 carrying a
390+
// structured JSON-RPC error is surfaced as McpProtocolException and handled above, so
391+
// anything reaching here is plain or empty. Either way this is an initialize-handshake
392+
// server, so fall back. A 405 means the POST endpoint rejected the request method
393+
// entirely, so retrying initialize over the same transport is not useful; the spec's 405
394+
// handling is the AutoDetect transport's fallback to SSE, and in explicit Streamable HTTP
395+
// mode a 405 surfaces to the caller. Other statuses stay uncaught and surface to the
396+
// caller.
395397
fallbackToInitialize = true;
396398
}
397399
catch (OperationCanceledException) when (probeCts.IsCancellationRequested && !initializationCts.IsCancellationRequested)

‎tests/ModelContextProtocol.Tests/Client/July2026ProtocolFallbackTests.cs‎

Lines changed: 68 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -214,16 +214,16 @@ public void DiscoverProbeTimeout_Setter_Accepts_PositiveAndInfiniteValues()
214214
[InlineData(HttpStatusCode.NotFound, HttpTransportMode.AutoDetect)]
215215
[InlineData(HttpStatusCode.BadRequest, HttpTransportMode.StreamableHttp)]
216216
[InlineData(HttpStatusCode.BadRequest, HttpTransportMode.AutoDetect)]
217-
[InlineData(HttpStatusCode.MethodNotAllowed, HttpTransportMode.StreamableHttp)]
218-
[InlineData(HttpStatusCode.MethodNotAllowed, HttpTransportMode.AutoDetect)]
219217
public async Task Client_OnFallbackHttpStatusFromProbe_FallsBackTo_Initialize(
220218
HttpStatusCode status, HttpTransportMode transportMode)
221219
{
222220
// A server predating SEP-2575 can reject the session-less server/discover probe at the HTTP layer
223221
// rather than with a JSON-RPC error: 404 when it requires Mcp-Session-Id on every non-initialize
224-
// POST, a plain/empty 400 when it cannot parse the request, or 405 when the endpoint rejects
225-
// the probe method. All three are initialize-handshake servers, so the connect must fall back
226-
// instead of failing.
222+
// POST, or a plain/empty 400 when it cannot parse the request. Both are initialize-handshake
223+
// servers, so the connect must fall back instead of failing. (405 is deliberately excluded: the
224+
// POST endpoint rejecting the request method does not mean initialize will succeed over the same
225+
// transport, and the spec routes 405 to the AutoDetect transport's SSE fallback — see
226+
// Client_On405FromProbe_DoesNotFallBackTo_Initialize.)
227227
var ct = TestContext.Current.CancellationToken;
228228
var initializeReceived = false;
229229

@@ -247,8 +247,6 @@ public async Task Client_OnFallbackHttpStatusFromProbe_FallsBackTo_Initialize(
247247
[InlineData(HttpStatusCode.BadRequest, HttpTransportMode.AutoDetect)]
248248
[InlineData(HttpStatusCode.NotFound, HttpTransportMode.StreamableHttp)]
249249
[InlineData(HttpStatusCode.NotFound, HttpTransportMode.AutoDetect)]
250-
[InlineData(HttpStatusCode.MethodNotAllowed, HttpTransportMode.StreamableHttp)]
251-
[InlineData(HttpStatusCode.MethodNotAllowed, HttpTransportMode.AutoDetect)]
252250
public async Task Client_OnStructuredFallbackHttpStatusFromProbe_FallsBackTo_Initialize(
253251
HttpStatusCode status, HttpTransportMode transportMode)
254252
{
@@ -269,6 +267,66 @@ public async Task Client_OnStructuredFallbackHttpStatusFromProbe_FallsBackTo_Ini
269267
Assert.Equal(McpProtocolVersions.November2025ProtocolVersion, client.NegotiatedProtocolVersion);
270268
}
271269

270+
[Theory]
271+
[InlineData(HttpTransportMode.StreamableHttp, false)]
272+
[InlineData(HttpTransportMode.AutoDetect, true)]
273+
public async Task Client_On405FromProbe_DoesNotFallBackTo_Initialize(
274+
HttpTransportMode transportMode, bool expectSseAttempt)
275+
{
276+
// 405 means the POST endpoint rejected the request method, so retrying initialize over the same
277+
// transport is not useful. The spec routes 405 to the AutoDetect transport's SSE fallback: in
278+
// Streamable HTTP mode the 405 surfaces directly, and in AutoDetect mode the client attempts the
279+
// deprecated SSE GET instead of initialize. Neither path may attempt initialize.
280+
var ct = TestContext.Current.CancellationToken;
281+
var initializeReceived = false;
282+
var sseRequested = false;
283+
284+
using var mockHttpHandler = new MockHttpHandler();
285+
using var httpClient = new HttpClient(mockHttpHandler);
286+
mockHttpHandler.RequestHandler = CreateProbeRejectingServer(
287+
HttpStatusCode.MethodNotAllowed, "Invalid session ID",
288+
() => initializeReceived = true, () => sseRequested = true);
289+
290+
await using var transport = CreateTransport(httpClient, transportMode);
291+
292+
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
293+
{
294+
await using var client = await McpClient.CreateAsync(transport, new McpClientOptions(),
295+
loggerFactory: LoggerFactory, cancellationToken: ct);
296+
});
297+
298+
Assert.False(initializeReceived);
299+
Assert.Equal(expectSseAttempt, sseRequested);
300+
}
301+
302+
[Theory]
303+
[InlineData(HttpTransportMode.StreamableHttp)]
304+
[InlineData(HttpTransportMode.AutoDetect)]
305+
public async Task Client_OnStructured405FromProbe_DoesNotFallBackTo_Initialize(
306+
HttpTransportMode transportMode)
307+
{
308+
// A 405 carrying a structured JSON-RPC error body means the peer is a Streamable HTTP server
309+
// that rejected the method; the AutoDetect transport adopts the transport and surfaces the error
310+
// instead of trying SSE, and neither transport should attempt initialize.
311+
var ct = TestContext.Current.CancellationToken;
312+
var initializeReceived = false;
313+
314+
using var mockHttpHandler = new MockHttpHandler();
315+
using var httpClient = new HttpClient(mockHttpHandler);
316+
mockHttpHandler.RequestHandler = CreateStructuredProbeRejectingServer(
317+
HttpStatusCode.MethodNotAllowed, () => initializeReceived = true);
318+
319+
await using var transport = CreateTransport(httpClient, transportMode);
320+
321+
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
322+
{
323+
await using var client = await McpClient.CreateAsync(transport, new McpClientOptions(),
324+
loggerFactory: LoggerFactory, cancellationToken: ct);
325+
});
326+
327+
Assert.False(initializeReceived);
328+
}
329+
272330
[Theory]
273331
[InlineData(HttpStatusCode.InternalServerError, HttpTransportMode.StreamableHttp)]
274332
[InlineData(HttpStatusCode.Forbidden, HttpTransportMode.StreamableHttp)]
@@ -278,8 +336,9 @@ public async Task Client_OnStructuredFallbackHttpStatusFromProbe_FallsBackTo_Ini
278336
public async Task Client_OnOtherHttpErrorFromProbe_Surfaces_NoFallback(
279337
HttpStatusCode status, HttpTransportMode transportMode)
280338
{
281-
// Only 400, 404, and 405 indicate that the server needs the initialize handshake. Authentication
282-
// and server failures must surface directly, without probing deprecated SSE or attempting initialize.
339+
// Only 400 and 404 indicate that the server needs the initialize handshake (405 routes to the
340+
// AutoDetect SSE fallback instead). Authentication and server failures must surface directly,
341+
// without probing deprecated SSE or attempting initialize.
283342
var ct = TestContext.Current.CancellationToken;
284343
var initializeReceived = false;
285344
var sseRequested = false;

‎tests/ModelContextProtocol.Tests/Transport/HttpClientTransportAutoDetectTests.cs‎

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public async Task AutoDetectMode_UsesStreamableHttp_WhenServerSupportsIt()
5353
[Fact]
5454
public async Task AutoDetectMode_WhenBothTransportsFail_PreservesStreamableHttpException()
5555
{
56-
// Regression test: when Streamable HTTP POST fails (e.g. 403) and the SSE GET
56+
// Regression test: when Streamable HTTP POST fails (e.g. 404) and the SSE GET
5757
// fallback also fails (e.g. 405), the original Streamable HTTP error should
5858
// be preserved. The SSE connection failure is available as its inner exception.
5959
var options = new HttpClientTransportOptions
@@ -71,11 +71,11 @@ public async Task AutoDetectMode_WhenBothTransportsFail_PreservesStreamableHttpE
7171
{
7272
if (request.Method == HttpMethod.Post)
7373
{
74-
// Streamable HTTP POST fails with 403 (auth error)
74+
// Streamable HTTP POST fails with 404 (an SSE-only server with no POST endpoint).
7575
return Task.FromResult(new HttpResponseMessage
7676
{
77-
StatusCode = HttpStatusCode.Forbidden,
78-
Content = new StringContent("Forbidden")
77+
StatusCode = HttpStatusCode.NotFound,
78+
Content = new StringContent("Streamable HTTP not supported")
7979
});
8080
}
8181

@@ -99,12 +99,12 @@ public async Task AutoDetectMode_WhenBothTransportsFail_PreservesStreamableHttpE
9999
var ex = await Assert.ThrowsAsync<HttpRequestException>(
100100
() => McpClient.CreateAsync(transport, cancellationToken: TestContext.Current.CancellationToken));
101101

102-
Assert.Contains("403", ex.Message);
102+
Assert.Contains("404", ex.Message);
103103
Assert.IsType<HttpRequestException>(ex.InnerException);
104104
Assert.Contains("405", ex.InnerException.Message);
105-
Assert.Equal(HttpStatusCode.Forbidden, ex.Data["ModelContextProtocol.HttpStatusCode"]);
105+
Assert.Equal(HttpStatusCode.NotFound, ex.Data["ModelContextProtocol.HttpStatusCode"]);
106106
#if NET
107-
Assert.Equal(HttpStatusCode.Forbidden, ex.StatusCode);
107+
Assert.Equal(HttpStatusCode.NotFound, ex.StatusCode);
108108
#endif
109109
}
110110

@@ -278,11 +278,12 @@ await session.SendMessageAsync(
278278
}
279279

280280
// Regression test for https://github.com/modelcontextprotocol/csharp-sdk/issues/1526
281-
// When Streamable HTTP returns 415 (e.g. wrong Content-Type) and the SSE fallback also fails
282-
// (e.g. a Streamable-HTTP-only server returns 405 to the GET), the surfaced exception must
283-
// preserve the original Streamable HTTP error rather than dropping it on the floor.
281+
// When Streamable HTTP returns 404 (e.g. an SSE-only server with no POST endpoint) and the
282+
// SSE fallback also fails (e.g. a Streamable-HTTP-only server returns 405 to the GET), the
283+
// surfaced exception must preserve the original Streamable HTTP error rather than dropping
284+
// it on the floor.
284285
[Fact]
285-
public async Task AutoDetectMode_PreservesOriginalError_WhenStreamableHttpReturns415AndSseFallbackFails()
286+
public async Task AutoDetectMode_PreservesOriginalError_WhenStreamableHttpReturns404AndSseFallbackFails()
286287
{
287288
var options = new HttpClientTransportOptions
288289
{
@@ -295,24 +296,24 @@ public async Task AutoDetectMode_PreservesOriginalError_WhenStreamableHttpReturn
295296
using var httpClient = new HttpClient(mockHttpHandler);
296297
await using var transport = new HttpClientTransport(options, httpClient, LoggerFactory);
297298

298-
const string streamableHttpBody = "Content-Type must be 'application/json'";
299+
const string streamableHttpBody = "Streamable HTTP not supported";
299300

300301
mockHttpHandler.RequestHandler = (request) =>
301302
{
302303
if (request.Method == HttpMethod.Post)
303304
{
304-
// Streamable HTTP fails with 415 - this is the real server diagnostic the user needs to see.
305+
// Streamable HTTP fails with 404 - this is the real server diagnostic the user needs to see.
305306
return Task.FromResult(new HttpResponseMessage
306307
{
307-
StatusCode = HttpStatusCode.UnsupportedMediaType,
308+
StatusCode = HttpStatusCode.NotFound,
308309
Content = new StringContent(streamableHttpBody),
309310
});
310311
}
311312

312313
if (request.Method == HttpMethod.Get)
313314
{
314315
// Streamable-HTTP-only server: SSE GET is rejected with 405. Without the fix this is the
315-
// ONLY error the user ever sees, masking the real 415 diagnostic above.
316+
// ONLY error the user ever sees, masking the real 404 diagnostic above.
316317
return Task.FromResult(new HttpResponseMessage
317318
{
318319
StatusCode = HttpStatusCode.MethodNotAllowed,
@@ -331,11 +332,11 @@ public async Task AutoDetectMode_PreservesOriginalError_WhenStreamableHttpReturn
331332
new JsonRpcRequest { Method = RequestMethods.Initialize, Id = new RequestId(1) },
332333
TestContext.Current.CancellationToken));
333334

334-
// Walk the exception chain and assert the original 415 (and its body) is somewhere in it.
335+
// Walk the exception chain and assert the original 404 (and its body) is somewhere in it.
335336
// We don't pin the exact exception type so this stays robust to future error-shape tweaks,
336337
// but the underlying status code and server body must reach the caller.
337338
var combined = Flatten(ex);
338-
Assert.Contains("415", combined);
339+
Assert.Contains("404", combined);
339340
Assert.Contains(streamableHttpBody, combined);
340341

341342
static string Flatten(Exception e)
@@ -378,15 +379,15 @@ public async Task AutoDetectMode_SurfacesStreamableHttpError_WithSseAsInner_When
378379
using var httpClient = new HttpClient(mockHttpHandler);
379380
await using var transport = new HttpClientTransport(options, httpClient, LoggerFactory);
380381

381-
const string streamableHttpBody = "Content-Type must be 'application/json'";
382+
const string streamableHttpBody = "Streamable HTTP not supported";
382383

383384
mockHttpHandler.RequestHandler = (request) =>
384385
{
385386
if (request.Method == HttpMethod.Post)
386387
{
387388
return Task.FromResult(new HttpResponseMessage
388389
{
389-
StatusCode = HttpStatusCode.UnsupportedMediaType,
390+
StatusCode = HttpStatusCode.NotFound,
390391
Content = new StringContent(streamableHttpBody),
391392
});
392393
}
@@ -412,11 +413,11 @@ public async Task AutoDetectMode_SurfacesStreamableHttpError_WithSseAsInner_When
412413

413414
// The surfaced exception is the original Streamable HTTP error (the real server diagnostic), not the SSE 405.
414415
var httpEx = Assert.IsType<HttpRequestException>(ex);
415-
Assert.Contains("415", httpEx.Message);
416+
Assert.Contains("404", httpEx.Message);
416417
Assert.Contains(streamableHttpBody, httpEx.Message);
417-
Assert.Equal(HttpStatusCode.UnsupportedMediaType, httpEx.Data["ModelContextProtocol.HttpStatusCode"]);
418+
Assert.Equal(HttpStatusCode.NotFound, httpEx.Data["ModelContextProtocol.HttpStatusCode"]);
418419
#if NET
419-
Assert.Equal(HttpStatusCode.UnsupportedMediaType, httpEx.StatusCode);
420+
Assert.Equal(HttpStatusCode.NotFound, httpEx.StatusCode);
420421
#endif
421422

422423
// The SSE fallback failure (the 405 from the GET) is preserved as the inner exception, not dropped.
@@ -482,8 +483,8 @@ public async Task AutoDetectMode_LogsWarning_WhenSseFallbackFailsAfterStreamable
482483
{
483484
return Task.FromResult(new HttpResponseMessage
484485
{
485-
StatusCode = HttpStatusCode.UnsupportedMediaType,
486-
Content = new StringContent("Content-Type must be 'application/json'"),
486+
StatusCode = HttpStatusCode.NotFound,
487+
Content = new StringContent("Streamable HTTP not supported"),
487488
});
488489
}
489490

0 commit comments

Comments
 (0)