Skip to content

Commit fde5d08

Browse files
Copilotstephentoub
andauthored
Remove redundant DisposeAsync call and simplify catch blocks in CreateAsync
ConnectAsync already calls DisposeAsync (which awaits Completion) before re-throwing, so the session is already disposed and Completion is resolved by the time CreateAsync's catch block runs. Agent-Logs-Url: https://github.com/modelcontextprotocol/csharp-sdk/sessions/dc4efc81-4b40-45c3-a743-59ade1c1c6df Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
1 parent aa218be commit fde5d08

1 file changed

Lines changed: 4 additions & 18 deletions

File tree

src/ModelContextProtocol.Core/Client/McpClient.Methods.cs

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,14 @@ public static async Task<McpClient> CreateAsync(
5252
{
5353
await clientSession.ConnectAsync(cancellationToken).ConfigureAwait(false);
5454
}
55-
catch (Exception ex) when (ex is not TransportClosedException)
55+
catch (Exception ex) when (ex is not OperationCanceledException and not TransportClosedException)
5656
{
57-
// ConnectAsync already disposed the session. Call DisposeAsync again (no-op)
58-
// to ensure cleanup, then check if the transport provided structured completion
59-
// details indicating why the transport closed.
57+
// ConnectAsync already disposed the session (which includes awaiting Completion).
58+
// Check if the transport provided structured completion details indicating
59+
// why the transport closed that aren't already in the original exception chain.
6060
ClientCompletionDetails? completionDetails = null;
6161
try
6262
{
63-
await clientSession.DisposeAsync().ConfigureAwait(false);
6463
completionDetails = await clientSession.Completion.ConfigureAwait(false);
6564
}
6665
catch { } // allow the original exception to propagate if completion is unavailable
@@ -79,19 +78,6 @@ public static async Task<McpClient> CreateAsync(
7978

8079
throw;
8180
}
82-
catch
83-
{
84-
// The exception is already a TransportClosedException (e.g., from
85-
// ProcessMessagesCoreAsync propagating channel completion details).
86-
// Just ensure cleanup and re-throw.
87-
try
88-
{
89-
await clientSession.DisposeAsync().ConfigureAwait(false);
90-
}
91-
catch { }
92-
93-
throw;
94-
}
9581

9682
return clientSession;
9783
}

0 commit comments

Comments
 (0)