Skip to content

Commit e9f093b

Browse files
authored
Fix server/discover timeout interrupting OAuth (#1719)
1 parent af0fda3 commit e9f093b

19 files changed

Lines changed: 940 additions & 48 deletions

‎Directory.Packages.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
<!-- Product dependencies .NET Standard -->
2626
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
2727
<PackageVersion Include="Microsoft.Bcl.Memory" Version="$(System10Version)" />
28+
<PackageVersion Include="Microsoft.Bcl.TimeProvider" Version="8.0.1" />
2829
<PackageVersion Include="System.Collections.Immutable" Version="$(System10Version)" />
2930
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="$(System10Version)" />
3031
<PackageVersion Include="System.IO.Pipelines" Version="$(System10Version)" />

‎docs/concepts/transports/transports.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,21 @@ var transport = new HttpClientTransport(new HttpClientTransportOptions
145145
});
146146
```
147147

148+
#### Controlling client timeout timers in tests
149+
150+
<xref:ModelContextProtocol.Client.McpClientOptions.TimeProvider> controls
151+
<xref:ModelContextProtocol.Client.McpClientOptions.InitializationTimeout> and
152+
<xref:ModelContextProtocol.Client.McpClientOptions.DiscoverProbeTimeout>. It defaults to
153+
`TimeProvider.System`. Tests can set it to a `FakeTimeProvider` from the
154+
`Microsoft.Extensions.TimeProvider.Testing` package and advance time explicitly instead
155+
of waiting for real deadlines.
156+
157+
Use synchronization signals to wait until the request or authorization phase being tested
158+
has started before advancing the clock. Fake time does not control HTTP processing or
159+
task scheduling, so keep a real-time outer test deadline as a safety bound. The client
160+
time provider does not change `HttpClient.Timeout`, OAuth token expiration, or
161+
<xref:ModelContextProtocol.Client.HttpClientTransportOptions.ConnectionTimeout>.
162+
148163
#### Resuming sessions
149164

150165
Streamable HTTP supports session resumption. Save the session ID, server capabilities, and server info from the original session, then use <xref:ModelContextProtocol.Client.McpClient.ResumeSessionAsync*> to reconnect:

‎src/ModelContextProtocol.Core/Authentication/ClientOAuthProvider.cs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,11 @@ internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage r
198198
if (request.Headers.Authorization is null && request.RequestUri is not null)
199199
{
200200
string? accessToken;
201-
(accessToken, attemptedRefresh) = await GetAccessTokenSilentAsync(request.RequestUri, cancellationToken).ConfigureAwait(false);
201+
using (message?.Context?.RequestTimeout?.Suspend())
202+
{
203+
cancellationToken.ThrowIfCancellationRequested();
204+
(accessToken, attemptedRefresh) = await GetAccessTokenSilentAsync(request.RequestUri, cancellationToken).ConfigureAwait(false);
205+
}
202206

203207
if (!string.IsNullOrEmpty(accessToken))
204208
{
@@ -308,7 +312,12 @@ private async Task<HttpResponseMessage> HandleUnauthorizedResponseAsync(
308312
throw new McpException($"The server does not support the '{BearerScheme}' authentication scheme. Server supports: [{serverSchemes}].");
309313
}
310314

311-
var accessToken = await GetAccessTokenAsync(response, attemptedRefresh, usedAccessToken, cancellationToken).ConfigureAwait(false);
315+
string accessToken;
316+
using (originalJsonRpcMessage?.Context?.RequestTimeout?.Suspend())
317+
{
318+
cancellationToken.ThrowIfCancellationRequested();
319+
accessToken = await GetAccessTokenAsync(response, attemptedRefresh, usedAccessToken, cancellationToken).ConfigureAwait(false);
320+
}
312321

313322
using var retryRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri);
314323

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,15 @@ private async Task InitializeSseTransportAsync(JsonRpcMessage message, HttpReque
161161
try
162162
{
163163
LogAttemptingSSE(_name);
164+
// Discovery has been abandoned. Stop its timer rather than restarting it after
165+
// the legacy GET; caller/initialization cancellation and ConnectionTimeout still apply.
166+
message.Context?.RequestTimeout?.Stop();
164167
await sseTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);
165-
await sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
168+
169+
if (message is not JsonRpcRequest { Method: RequestMethods.ServerDiscover })
170+
{
171+
await sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
172+
}
166173

167174
LogUsingSSE(_name);
168175
ActiveTransport = sseTransport;
@@ -186,6 +193,12 @@ private async Task InitializeSseTransportAsync(JsonRpcMessage message, HttpReque
186193
await sseTransport.DisposeAsync().ConfigureAwait(false);
187194
throw;
188195
}
196+
197+
if (message is JsonRpcRequest { Method: RequestMethods.ServerDiscover })
198+
{
199+
// Let the client apply its initialization and minimum-version policy; never send discover over SSE.
200+
throw new ServerDiscoverSkippedForSseException();
201+
}
189202
}
190203

191204
public async ValueTask DisposeAsync()

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

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,9 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
287287
_ = _sessionHandler.ProcessMessagesAsync(CancellationToken.None);
288288

289289
// Perform initialization sequence
290-
using var initializationCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
291-
initializationCts.CancelAfter(_options.InitializationTimeout);
290+
var timeProvider = _options.TimeProvider;
291+
using var initializationTimeout = new RequestTimeout(_options.InitializationTimeout, timeProvider, cancellationToken);
292+
var initializationToken = initializationTimeout.Token;
292293

293294
try
294295
{
@@ -297,31 +298,39 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
297298
// capabilities and then begins sending normal RPCs that carry protocolVersion /
298299
// clientInfo / clientCapabilities in their per-request _meta. A null ProtocolVersion
299300
// prefers the 2026-07-28 revision and automatically falls back to the initialize
300-
// handshake when the server doesn't support it. The initialize branch below runs only when
301-
// the caller explicitly pins a version that still supports Streamable HTTP sessions (opting out of the default).
301+
// handshake when the server doesn't support it. HTTP+SSE defaults to the initialize handshake,
302+
// including when AutoDetect selects it while sending the discovery probe.
302303
if (_options.ProtocolVersion is null || McpProtocolVersions.RequiresPerRequestMetadata(_options.ProtocolVersion))
303304
{
304305
string preferredVersion = _options.ProtocolVersion ?? McpProtocolVersions.July2026ProtocolVersion;
305306

306307
DiscoverResult? discoverResult = null;
307-
bool fallbackToInitialize = false;
308+
// Modern-over-SSE is unusual, but honor an explicit version choice instead of forcing initialize.
309+
bool fallbackToInitialize = _transport is SseClientSessionTransport && _options.ProtocolVersion is null;
308310
IList<string>? serverSupportedVersions = null;
309311
string discoverVersion = preferredVersion;
310312

311313
// Apply a probe timeout so dual-path clients don't block forever waiting for an
312314
// initialize-handshake server that silently drops unknown methods (per stdio.mdx fallback rules).
313315
// The probe timeout is configurable via McpClientOptions.DiscoverProbeTimeout and is
314-
// always bounded by InitializationTimeout (only applied when it is the tighter bound).
316+
// always bounded by InitializationTimeout. OAuth can suspend only the probe timer.
315317
var probeTimeout = _options.DiscoverProbeTimeout;
316-
using var probeCts = CancellationTokenSource.CreateLinkedTokenSource(initializationCts.Token);
317-
if (_options.InitializationTimeout > probeTimeout)
318-
{
319-
probeCts.CancelAfter(probeTimeout);
320-
}
318+
using var probeTimeoutController = !fallbackToInitialize && probeTimeout != Timeout.InfiniteTimeSpan &&
319+
(_options.InitializationTimeout == Timeout.InfiniteTimeSpan || probeTimeout < _options.InitializationTimeout)
320+
? new RequestTimeout(probeTimeout, timeProvider, initializationToken)
321+
: null;
322+
var probeToken = probeTimeoutController?.Token ?? initializationToken;
321323

322324
try
323325
{
324-
discoverResult = await SendDiscoverAsync(discoverVersion, probeCts.Token).ConfigureAwait(false);
326+
if (!fallbackToInitialize)
327+
{
328+
discoverResult = await SendDiscoverAsync(discoverVersion, probeToken).ConfigureAwait(false);
329+
}
330+
}
331+
catch (ServerDiscoverSkippedForSseException)
332+
{
333+
fallbackToInitialize = true;
325334
}
326335
catch (UnsupportedProtocolVersionException ex)
327336
{
@@ -347,7 +356,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
347356
}
348357

349358
discoverVersion = retryVersion;
350-
discoverResult = await SendDiscoverAsync(discoverVersion, probeCts.Token).ConfigureAwait(false);
359+
discoverResult = await SendDiscoverAsync(discoverVersion, probeToken).ConfigureAwait(false);
351360
}
352361
else
353362
{
@@ -392,7 +401,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
392401
// server, so fall back. Other statuses stay uncaught and surface to the caller.
393402
fallbackToInitialize = true;
394403
}
395-
catch (OperationCanceledException) when (probeCts.IsCancellationRequested && !initializationCts.IsCancellationRequested)
404+
catch (OperationCanceledException) when (probeToken.IsCancellationRequested && !initializationToken.IsCancellationRequested)
396405
{
397406
// Probe timeout elapsed without a response. Per stdio.mdx fallback rules, no
398407
// response within a reasonable timeout means the server requires initialize. Fall back.
@@ -434,7 +443,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
434443
: $"Server-supported versions: {string.Join(", ", serverSupportedVersions)}."));
435444
}
436445

437-
await PerformInitializeHandshakeAsync(fallbackVersion, initializationCts.Token).ConfigureAwait(false);
446+
await PerformInitializeHandshakeAsync(fallbackVersion, initializationToken).ConfigureAwait(false);
438447
}
439448
else
440449
{
@@ -466,6 +475,7 @@ async Task<DiscoverResult> SendDiscoverAsync(string protocolVersion, Cancellatio
466475
new DiscoverRequestParams(),
467476
McpJsonUtilities.JsonContext.Default.DiscoverRequestParams,
468477
McpJsonUtilities.JsonContext.Default.DiscoverResult,
478+
context: probeTimeoutController is null ? null : new JsonRpcMessageContext { RequestTimeout = probeTimeoutController },
469479
cancellationToken: cancellationToken).ConfigureAwait(false);
470480
}
471481
}
@@ -475,10 +485,10 @@ async Task<DiscoverResult> SendDiscoverAsync(string protocolVersion, Cancellatio
475485
// ProtocolVersion that still supports Streamable HTTP sessions (opting out of the default), so
476486
// _options.ProtocolVersion is non-null here.
477487
string requestProtocol = _options.ProtocolVersion ?? McpProtocolVersions.November2025ProtocolVersion;
478-
await PerformInitializeHandshakeAsync(requestProtocol, initializationCts.Token).ConfigureAwait(false);
488+
await PerformInitializeHandshakeAsync(requestProtocol, initializationToken).ConfigureAwait(false);
479489
}
480490
}
481-
catch (OperationCanceledException oce) when (initializationCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
491+
catch (OperationCanceledException oce) when (initializationToken.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
482492
{
483493
LogClientInitializationTimeout(_endpointName);
484494
throw new TimeoutException("Initialization timed out", oce);

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ public sealed class McpClientOptions
7070
/// negotiates a different version. To try more than one version, leave this unset for automatic fallback
7171
/// or retry the connection with a different value.
7272
/// </para>
73+
/// <para>
74+
/// HTTP+SSE connections use the <c>initialize</c> handshake by default.
75+
/// An explicit protocol version is attempted when <see cref="HttpTransportMode.Sse"/> is selected.
76+
/// </para>
7377
/// </remarks>
7478
public string? ProtocolVersion { get; set; }
7579

@@ -86,12 +90,36 @@ public sealed class McpClientOptions
8690
/// an exception is thrown.
8791
/// </para>
8892
/// <para>
93+
/// This timeout includes OAuth token acquisition performed during the handshake. Neither this timeout nor
94+
/// caller cancellation is suspended while authenticating. Transport connection establishment that precedes
95+
/// the handshake, such as an explicitly selected SSE connection, retains its transport-specific timeout.
96+
/// </para>
97+
/// <para>
8998
/// Setting an appropriate timeout prevents the client from hanging indefinitely when
9099
/// connecting to unresponsive servers.
91100
/// </para>
92101
/// </remarks>
93102
public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);
94103

104+
/// <summary>
105+
/// Gets or sets the time provider used for <see cref="InitializationTimeout"/> and <see cref="DiscoverProbeTimeout"/>.
106+
/// </summary>
107+
/// <value>The time provider. The default is <see cref="TimeProvider.System"/>.</value>
108+
/// <remarks>
109+
/// This provider does not control HTTP client timeouts, OAuth token expiration, or transport-specific
110+
/// deadlines such as <see cref="HttpClientTransportOptions.ConnectionTimeout"/>.
111+
/// </remarks>
112+
/// <exception cref="ArgumentNullException">The value is <see langword="null"/>.</exception>
113+
public TimeProvider TimeProvider
114+
{
115+
get;
116+
set
117+
{
118+
Throw.IfNull(value);
119+
field = value;
120+
}
121+
} = TimeProvider.System;
122+
95123
/// <summary>
96124
/// Gets or sets the timeout applied to the <c>server/discover</c> probe that the client issues
97125
/// before falling back to the <c>initialize</c> handshake.
@@ -121,6 +149,12 @@ public sealed class McpClientOptions
121149
/// greater than or equal to <see cref="InitializationTimeout"/>, the probe is effectively bounded by
122150
/// <see cref="InitializationTimeout"/> alone.
123151
/// </para>
152+
/// <para>
153+
/// SDK OAuth token acquisition, including metadata discovery, registration, interactive authorization,
154+
/// and token refresh or exchange, is excluded from the probe timeout. After token acquisition, the
155+
/// HTTP request gets a fresh full probe budget, covering both response headers and body processing.
156+
/// <see cref="InitializationTimeout"/> and caller cancellation continue to apply during authentication.
157+
/// </para>
124158
/// </remarks>
125159
/// <exception cref="ArgumentOutOfRangeException">
126160
/// The value is not positive and is not <see cref="System.Threading.Timeout.InfiniteTimeSpan"/>.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
namespace ModelContextProtocol.Client;
2+
3+
/// <summary>Signals that AutoDetect selected SSE and the client must initialize instead of discovering.</summary>
4+
internal sealed class ServerDiscoverSkippedForSseException()
5+
: Exception("AutoDetect selected HTTP+SSE. Use initialize instead of server/discover.");

‎src/ModelContextProtocol.Core/McpSession.Methods.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public ValueTask<TResult> SendRequestAsync<TParameters, TResult>(
3838
serializerOptions.GetTypeInfo<TParameters>(),
3939
serializerOptions.GetTypeInfo<TResult>(),
4040
requestId,
41-
cancellationToken);
41+
cancellationToken: cancellationToken);
4242
}
4343

4444
/// <summary>
@@ -51,6 +51,7 @@ public ValueTask<TResult> SendRequestAsync<TParameters, TResult>(
5151
/// <param name="parametersTypeInfo">The type information for request parameter serialization.</param>
5252
/// <param name="resultTypeInfo">The type information for result deserialization.</param>
5353
/// <param name="requestId">The request ID for the request.</param>
54+
/// <param name="context">Non-serialized runtime context for the request.</param>
5455
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
5556
/// <returns>A task that represents the asynchronous operation. The task result contains the deserialized result.</returns>
5657
internal async ValueTask<TResult> SendRequestAsync<TParameters, TResult>(
@@ -59,6 +60,7 @@ internal async ValueTask<TResult> SendRequestAsync<TParameters, TResult>(
5960
JsonTypeInfo<TParameters> parametersTypeInfo,
6061
JsonTypeInfo<TResult> resultTypeInfo,
6162
RequestId requestId = default,
63+
JsonRpcMessageContext? context = null,
6264
CancellationToken cancellationToken = default)
6365
where TResult : notnull
6466
{
@@ -71,6 +73,7 @@ internal async ValueTask<TResult> SendRequestAsync<TParameters, TResult>(
7173
Id = requestId,
7274
Method = method,
7375
Params = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo),
76+
Context = context,
7477
};
7578

7679
JsonRpcResponse response = await SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);

‎src/ModelContextProtocol.Core/ModelContextProtocol.Core.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
4343
<Compile Include="..\Common\CancellableStreamReader\**\*.cs" />
4444
<PackageReference Include="Microsoft.Bcl.Memory" />
45+
<PackageReference Include="Microsoft.Bcl.TimeProvider" />
4546
<PackageReference Include="System.Collections.Immutable" />
4647
<PackageReference Include="System.Diagnostics.DiagnosticSource" />
4748
<PackageReference Include="System.Text.Json" />

‎src/ModelContextProtocol.Core/Protocol/JsonRpcMessageContext.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,9 @@ public sealed class JsonRpcMessageContext
130130
/// log notifications for the request. Legacy requests continue to use their negotiated logging behavior.
131131
/// </remarks>
132132
public LoggingLevel? LogLevel { get; set; }
133+
134+
/// <summary>
135+
/// Gets or sets the discovery-owned timer, allowing awaited OAuth work to suspend only the probe deadline.
136+
/// </summary>
137+
internal RequestTimeout? RequestTimeout { get; set; }
133138
}

0 commit comments

Comments
 (0)