Skip to content

ModelContextProtocol.McpException: Transport is not connected #333

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
hemantkathuria opened this issue Apr 19, 2025 · 8 comments
Open
Labels
bug Something isn't working

Comments

@hemantkathuria
Copy link

hemantkathuria commented Apr 19, 2025

I am using SementicKernel to consume MCP tools.

Keep on getting the below error.

fail: Microsoft.SemanticKernel.KernelFunction[0]
Function Tools-GetCropHealthParameters failed. Error: Transport is not connected
ModelContextProtocol.McpException: Transport is not connected
at ModelContextProtocol.Shared.McpSession.SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken)
at ModelContextProtocol.McpEndpointExtensions.SendRequestAsync[TParameters,TResult](IMcpEndpoint endpoint, String method, TParameters parameters, JsonTypeInfo1 parametersTypeInfo, JsonTypeInfo1 resultTypeInfo, Nullable1 requestId, CancellationToken cancellationToken) at ModelContextProtocol.Client.McpClientTool.InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken) at Microsoft.SemanticKernel.ChatCompletion.AIFunctionKernelFunction.InvokeCoreAsync(Kernel kernel, KernelArguments arguments, CancellationToken cancellationToken) at Microsoft.SemanticKernel.KernelFunction.<>c__DisplayClass31_0.<<InvokeAsync>b__0>d.MoveNext() --- End of stack trace from previous location --- at Microsoft.SemanticKernel.Kernel.InvokeFilterOrFunctionAsync(NonNullCollection1 functionFilters, Func2 functionCallback, FunctionInvocationContext context, Int32 index) at Microsoft.SemanticKernel.Kernel.OnFunctionInvocationAsync(KernelFunction function, KernelArguments arguments, FunctionResult functionResult, Boolean isStreaming, Func2 functionCallback, CancellationToken cancellationToken)
at Microsoft.SemanticKernel.KernelFunction.InvokeAsync(Kernel kernel, KernelArguments arguments, CancellationToken cancellationToken)

@hemantkathuria hemantkathuria added the bug Something isn't working label Apr 19, 2025
@anuraj
Copy link

anuraj commented Apr 19, 2025

Can you add example code or repository?

@hemantkathuria
Copy link
Author

@anuraj

MCP Server is hosted on Azure App Service.

Below is the code of my client which also hosted on another App Service which is utilizing Semantic Kernel to register tools as plugins. Once registered, after that it is Semantic Kernal which utilizes McpClient to invoke the tool. If I restart my client App Service, it works for few minutes but after that it starts failing.

`///


/// Creates an MCP client and connects it to the MCPServer server.
///

/// An instance of .
static Task CreateSSeMcpClientAsync(string mcpServerUrl)
{
return McpClientFactory.CreateAsync(new SseClientTransport(new()
{
Name = "MCPServer",

    // Point the client to the MCPServer server executable
    Endpoint = new Uri(mcpServerUrl),
}));

}

static async Task AddTools(string mcpServerUrl, IKernelBuilder kernelBuilder)
{
IMcpClient mcpClient = await CreateSSeMcpClientAsync(mcpServerUrl);

IList<McpClientTool> tools = await mcpClient.ListToolsAsync();

kernelBuilder.Plugins.AddFromFunctions("Tools", tools.Select(aiFunction => aiFunction.AsKernelFunction()));

}

@Matonen
Copy link

Matonen commented Apr 21, 2025

Do you use .NET dependency injection (DI)? Both Kernel and McpClient should be registered as transient.

In my application, I use Azure Container Apps where the API and MCP are deployed as separate Azure Container Apps. I noticed that when I stopped and restarted the MCP container, the API began throwing the same error. Initially, I had McpClient registered as a singleton, but after changing it to transient, everything started working correctly again.

I'm still wondering about the exact root cause, but it might be related to how McpClient manages its connections.

For example:

builder.Services.AddTransient(sp =>
{
    var mcpClient = McpClientFactory.CreateAsync(new SseClientTransport(new SseClientTransportOptions
        { Endpoint = new Uri(mcpServerUrl) })).GetAwaiter().GetResult();
    return mcpClient;
});

builder.Services.AddTransient(sp =>
{
    KernelPluginCollection pluginCollection = [];

    var mcpTools = sp.GetRequiredService<IMcpClient>().ListToolsAsync().GetAwaiter().GetResult();
    pluginCollection.AddFromFunctions("McpServer",
        mcpTools.Select(aiFunction => aiFunction.AsKernelFunction()));

    return new Kernel(sp, pluginCollection);
});

@anuraj
Copy link

anuraj commented Apr 21, 2025

Can you able to access the MCP Server from Azure App service in your local dev environment? I hosted one and I am able to access it without any issues.

@hemantkathuria
Copy link
Author

@Matonen - I used the below syntax to add Kernel and I believe it is adding as transient. MCPClient is hidden for me as Sementic Kernel uses it when LLM asks for a function call.

// Add Kernel
IKernelBuilder kernelBuilder = builder.Services.AddKernel();

@hemantkathuria
Copy link
Author

Can you able to access the MCP Server from Azure App service in your local dev environment? I hosted one and I am able to access it without any issues.

I am also able to access but it starts failing after sometime!

@halter73
Copy link
Contributor

.GetAwaiter().GetResult()

You probably shouldn't do this. It's usually better to register a factory service type with a Task<IMcpClient> ConnectMcpClientAsync() and Task<Kernel> CreateKernelAsync() methods. Eveng registering Task<IMcpClient> or Task<Kernel> as services would be slightly better than using .GetAwaiter().GetResult(). Blocking threads in DI factories can cause thread pool starvation.

fail: Microsoft.SemanticKernel.KernelFunction[0]
Function Tools-GetCropHealthParameters failed. Error: Transport is not connected
at ModelContextProtocol.Shared.McpSession.SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken)

As of 0.1.0-preview.10, you should no longer see this exception now that McpSession.SendRequestAsync doesn't check if the transport is connected. It's still possible for StdioClientSessionTransport.SendMessageAsync to throw a similar exception, but it now should at least include a more informative inner exception for why the process may have exited:

try
{
hasExited = _process.HasExited;
}
catch (Exception e)
{
processException = e;
hasExited = true;
}
if (hasExited)
{
throw new InvalidOperationException("Transport is not connected", processException);
}

Can you try upgrading and tell us what happens? Another thing that might help would be lowering the log-level to Trace in appsetting.Development.json and including all the trace-level and higher logs and posting that back here.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-9.0#configure-logging

@anuraj
Copy link

anuraj commented Apr 22, 2025

Can you able to access the MCP Server from Azure App service in your local dev environment? I hosted one and I am able to access it without any issues.

I am also able to access but it starts failing after sometime!

I deployed my MCP server and client in Azure App Service - And it is working properly. Here is the client code. I am using GitHub models in my Semantic Kernel.

builder.Services.AddSingleton(serviceProvider =>
{
    var clientTransport = new SseClientTransport(new SseClientTransportOptions
    {
        Name = "McpServer",
        Endpoint = new Uri(mcpSseUrl)
    });

    var mcpClient = McpClientFactory.CreateAsync(clientTransport).Result;

    var githubToken = builder.Configuration["GithubToken"];
    var kernelBuilder = Kernel.CreateBuilder()
        .AddOpenAIChatCompletion("gpt-4o", new Uri("https://models.inference.ai.azure.com"), githubToken);

    kernelBuilder.Plugins.AddFromFunctions("McpServer", mcpClient.ListToolsAsync()
        .Result
        .Select(t => t.AsKernelFunction()));

    return kernelBuilder.Build();
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants