The Model Context Protocol (MCP) makes it possible for AI applications to communicate with external tools, services, and data sources through a common protocol. A .NET application can use an MCP client to discover available tools and execute them without implementing a separate integration for every service.
However, connecting to an MCP server is only part of the work. In a real application, an MCP tool may take several seconds to respond, return incomplete data, encounter a network failure, or become temporarily unavailable.
For example, imagine an AI-powered customer support application that uses an MCP tool to retrieve order information. The tool may communicate with an external order management system. If that system is slow, the MCP request can take longer than expected. If the service is temporarily unavailable, the request may fail entirely.
Without proper handling, these problems can affect the entire application.
In this article, we will explore how to call MCP tools from C#, configure timeouts, propagate cancellation, implement controlled retries, handle tool errors, and protect ASP.NET Core applications from slow or unreliable MCP services.
Understanding Slow MCP Tool Responses
An MCP client communicates with an MCP server to discover and execute tools.
A typical request follows this process:
ASP.NET Core Application
|
v
MCP Client
|
v
MCP Server
|
v
External Service
|
v
Tool Result
|
v
MCP Client
|
v
Application Response
The MCP server may perform additional operations before returning a result. It might query a database, call a third-party API, read a file, or communicate with another internal service.
This means the response time depends on more than the MCP connection itself.
Common causes of slow or unreliable responses include:
- Slow database queries inside the MCP tool.
- External API response delays.
- Network interruptions between the client and server.
- Rate limiting from third-party services.
- Large tool responses that take time to process.
- Temporary server failures.
- Long-running operations that exceed the application's request timeout.
The application should not assume that every tool call will complete immediately.
Instead, each tool invocation should have a defined timeout, cancellation behavior, and error-handling strategy.
Creating an MCP Client in .NET
The official MCP C# SDK provides client functionality for connecting to MCP servers and calling their tools.
Create a console application:
dotnet new console -n MCPReliableClient
cd MCPReliableClient
dotnet add package ModelContextProtocol
For this example, we will connect to an MCP server through the standard input/output transport.
Create a client using StdioClientTransport:
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
var transport = new StdioClientTransport(
new StdioClientTransportOptions
{
Name = "Order MCP Server",
Command = "dotnet",
Arguments =
[
"run",
"--project",
"../OrderMcpServer"
]
});
await using var client = await McpClient.CreateAsync(transport);
var tools = await client.ListToolsAsync();
foreach (var tool in tools)
{
Console.WriteLine(
$"{tool.Name}: {tool.Description}");
}
The transport starts the configured MCP server process and communicates with it through standard input and output.
The ListToolsAsync method retrieves the tools exposed by the server.
For a production deployment, the server process, executable path, arguments, permissions, and environment variables should be configured carefully. If the MCP server runs remotely, use an appropriate HTTP transport instead.
The important point is that tool discovery and tool execution are separate operations. Discovering a tool does not guarantee that its underlying service will always be available.
Calling an MCP Tool With a Timeout
One of the most important protections is a timeout.
Without a timeout, a request may continue waiting for a response longer than the application can reasonably tolerate.
The MCP C# SDK allows a CancellationToken to be passed to CallToolAsync.
We can use CancellationTokenSource.CancelAfter to establish a maximum execution time.
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
public sealed class McpToolService
{
private readonly McpClient _client;
public McpToolService(McpClient client)
{
_client = client;
}
public async Task<CallToolResult> GetOrderAsync(
string orderId,
CancellationToken cancellationToken)
{
using var timeoutSource =
CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken);
timeoutSource.CancelAfter(
TimeSpan.FromSeconds(10));
var arguments = new Dictionary<string, object?>
{
["orderId"] = orderId
};
return await _client.CallToolAsync(
"get_order",
arguments,
cancellationToken: timeoutSource.Token);
}
}
The timeout source is linked to the original cancellation token.
This provides two cancellation paths:
- The application can cancel the operation when the user disconnects or the request is no longer needed.
- The timeout source can cancel the operation when it exceeds the configured execution limit.
For example, if the timeout is ten seconds and the MCP tool takes longer, the client stops waiting by requesting cancellation.
Cancellation is cooperative. The MCP server and the underlying tool must support and respond to cancellation for the actual work to stop. A timeout should not be treated as proof that the remote operation has been terminated.
Handling Tool Errors Separately From Exceptions
An important detail in MCP is that a tool can return an error result without necessarily causing the client call to throw an exception.
The CallToolResult object includes an IsError property.
For example, a tool may successfully execute its request and return a meaningful error indicating that an order does not exist.
That is different from a transport failure where the client cannot communicate with the server.
Consider the following implementation:
public async Task<string> GetOrderResponseAsync(
string orderId,
CancellationToken cancellationToken)
{
var result = await GetOrderAsync(
orderId,
cancellationToken);
if (result.IsError)
{
return "The order information could not be retrieved.";
}
var text = result.Content
.OfType<TextContentBlock>()
.FirstOrDefault()?.Text;
return text ?? "The MCP tool returned no text data.";
}
This implementation handles three possible outcomes:
- The tool returns a successful response containing text.
- The tool returns a tool-level error.
- The tool returns no text content.
In a production application, the error response should be logged with appropriate context, while the user receives a safe and understandable message.
Do not assume every MCP tool returns only text. Depending on the tool, its result may contain other supported content types. Process the result according to the tool's documented output contract.
Implementing Controlled Retries
Timeouts protect the application from waiting indefinitely, but they do not automatically solve temporary failures.
For example, an external service used by an MCP tool may briefly return an error because of a network interruption.
A retry can help when the failure is temporary.
However, retrying every failed operation is dangerous.
Imagine an MCP tool that creates a payment or submits an order. If the first request succeeds on the server but the response is lost, retrying the same request may create a duplicate operation.
Retries should therefore be limited to operations that are safe to repeat, such as read-only queries or operations protected by a reliable idempotency mechanism.
The following example implements a simple retry policy for a read-only order lookup:
public async Task<CallToolResult> GetOrderWithRetryAsync(
string orderId,
CancellationToken cancellationToken)
{
const int maxAttempts = 3;
for (var attempt = 1; attempt <= maxAttempts; attempt++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
return await GetOrderAsync(
orderId,
cancellationToken);
}
catch (OperationCanceledException)
when (!cancellationToken.IsCancellationRequested)
{
if (attempt == maxAttempts)
{
throw new TimeoutException(
"The MCP tool exceeded its execution timeout.");
}
}
catch (HttpRequestException)
{
if (attempt == maxAttempts)
{
throw;
}
}
var delay = TimeSpan.FromMilliseconds(
500 * Math.Pow(2, attempt - 1));
await Task.Delay(delay, cancellationToken);
}
throw new InvalidOperationException(
"The MCP operation could not be completed.");
}
Join the conversation! Your thoughts help the community grow.