Skip to content

Connection error at client with McpClientFactory.CreateAsync #385

Closed

Description

@nschuessler

I've tried this with the latest preview 11 and it still happens.

I've created an mcp server (app service, windows) with the ModelContextProtocol library and am trying to connect the client.
It was working previously, but now the connection hangs connecting the SSE transport. This is on a direct connection between client and hosted azure app service.

The remoteUrl parameter is my app services /sse endpoint which is apparently necessary according to 208 and 330 may have an impact here too.

Ultimately, I'm trying to get secure authentication by using Azure API Management service (we can't have unsecured network endpoints on the network), but the 200 OK
doesn't get back to the client due to a transport connection drop on the response to the middle tier so the client never gets it.
In debugging that issue, I found the hang at the app service.

Any ideas what is wrong here?

Image

// Create the logging handler and wrap it around the default HttpClientHandler
var loggingHandler = new LoggingHandler(new HttpClientHandler() {  CheckCertificateRevocationList = true });

// Create HttpClient with our logging handler
HttpClient httpClient = new HttpClient(loggingHandler);

SseClientTransportOptions sseClientTransportOptions = new SseClientTransportOptions
{
    Endpoint = remoteUrl,
    AdditionalHeaders = new Dictionary<string, string>()
    {
        { "Ocp-Apim-Trace", "true" }
    },
    Name = "MCP"
};

var clientTransport = new SseClientTransport(
    sseClientTransportOptions, httpClient, ownsHttpClient: true);

var client = await McpClientFactory.CreateAsync(clientTransport);

foreach (var tool in await client.ListToolsAsync())
{
    Console.WriteLine($"{tool.Name} ({tool.Description})");
}

Activity

  1. stephentoub commented on May 5, 2025

    @stephentoub
    Contributor
  2. nschuessler commented on May 6, 2025

    @nschuessler
    Author

    Ok. Problem solved.

    I added a delegating handler to inspect the responses to the MCP client from the API Management service (traces are given given in the header of the responses from the policies / routing XML). It's hard to find what you need in the logs on the server side.

    There was a call to response.Content.ReadAsync in the delegating handler that wasn't preceded by a check that content length was > 0. Which of course hangs waiting for input when there is no content after the initial GET /sse. This somehow led to a connection timeout or something waiting for the connection to establish (?).

    I've also upgraded to preview.12.

    Sorry for the spam. Here is the fixed handler:

    public class LoggingHandler : DelegatingHandler
    {
        public List<string> ResponseLog { get; } = new();
        public List<string> ResponseHeadersLog { get; } = new();
    
        public LoggingHandler(HttpMessageHandler innerHandler)
            : base(innerHandler) { }
    
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            
            if (response.StatusCode != System.Net.HttpStatusCode.OK &&
                response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                // Log the status code if it's not OK
                ResponseLog.Add($"Status Code: {response.StatusCode}");
    
                // Read and log content if available
                if (response.Content != null &&
                    response.Content.Headers.ContentLength.HasValue &&
                    response.Content.Headers.ContentLength.Value > 0)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    ResponseLog.Add(content);
                }
            }
    
            // Collect all headers from the response
            foreach (var header in response.Headers)
            {
                ResponseHeadersLog.Add($"{header.Key}: {string.Join(", ", header.Value)}");
            }
    
            return response;
        }`
  3. halter73 commented on May 13, 2025

    @halter73
    Contributor

    Good job figuring out the issue was caused by the DelegatingHandler.

    This somehow led to a connection timeout or something waiting for the connection to establish (?).

    This is expected if the HttpClient doesn't return from SendAsync before receiving the complete /sse response body, because CreateAsync does not complete until the client processes the initialization response from the server which arrives as an SSE event while the /sse response body remains incomplete.

    I am a little surprised that response.Content.Headers.ContentLength.HasValue is true given we don't know the Content-Length up front. SSE relies on chunked transfer encoding for HTTP/1.1 and data frames for HTTP/2 and HTTP/3 so it doesn't have to determine the Content-Length up front when sending response headers.

    Regardless, do you think we can close this issue? While it would be nice if we could raise a better error than timing out in this case, I'm not sure it's really feasible to detect if a hang was caused by a buggy DelegatingHandler vs an unresponsive server.

  4. nschuessler commented on May 16, 2025

    @nschuessler
    Author
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions