Skip to main content

How to Call an MCP Tool from C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

MCP tools are usually called by an AI model, but your own code can call them too, which is the quickest way to see what a tool really returns. This guide calls a tool of a remote MCP server from C#, checks whether it worked, and reads its result.

Syntax​

Syntax
McpClientTool <tool> = (await <client>.ListToolsAsync()).Single(tool => tool.Name == "<tool name>");

CallToolResult <result> = await <tool>.CallAsync(
new Dictionary<string, object?> { ["<parameter>"] = <value> });

<result>.IsError
<result>.Content
PartWhat it is
<client>A connected McpClient, from McpClient.CreateAsync
<tool name>The tool's name, exactly as the server lists it
<parameter>, <value>One entry for each argument the tool takes, under the name in its input schema
CallAsyncInvokes the tool on the server, in the words of the SDK reference, and returns a CallToolResult
IsErrortrue when the tool itself failed. The SDK's documentation explains that the error is reported inside the CallToolResult with IsError set to true, rather than as a protocol-level error
ContentWhat the tool returned: a list of content blocks, such as text, images or audio

<client>.CallToolAsync("<tool name>", <arguments>) calls a tool by name without listing first, but the SDK then logs a warning, because it doesn't know the tool's definition.

The Example​

A console app calls the documentation search of the Microsoft Learn MCP server, microsoft_docs_search, with the question create an Azure storage account with the Azure CLI. It prints the title and the link of the first three pages it finds.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, run:

Terminal
dotnet new console -n McpDocsSearch
cd McpDocsSearch
dotnet add package ModelContextProtocol.Core --version 2.4.0

ModelContextProtocol.Core is the official MCP C# SDK for clients. Open the McpDocsSearch folder in VS Code, or McpDocsSearch.csproj in Visual Studio.

Step 2: Find the Tool and Call It​

Replace everything in Program.cs with:

Program.cs
using System.Text.Json;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

await using McpClient client = await McpClient.CreateAsync(
new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri("https://learn.microsoft.com/api/mcp"),
TransportMode = HttpTransportMode.StreamableHttp,
}),
new McpClientOptions { ProtocolVersion = "2025-06-18" });

// Find the search tool in the server's list.
IList<McpClientTool> tools = await client.ListToolsAsync();
McpClientTool search = tools.Single(tool => tool.Name == "microsoft_docs_search");

// Call it with its one argument, query.
CallToolResult result = await search.CallAsync(
new Dictionary<string, object?> { ["query"] = "create an Azure storage account with the Azure CLI" });

if (result.IsError is true)
{
Console.WriteLine("The tool reported an error.");
return;
}
  • The connection is the one from How to Connect to an MCP Server in C# with the MCP C# SDK.
  • Single takes the tool with that name from the list, and stops the program with an exception if the server doesn't have exactly one. Taking the tool from the list also fills the client's cache of tool definitions.
  • The dictionary holds the arguments. microsoft_docs_search takes one, query, as its input schema says.
  • IsError is true checks the result. IsError is a bool?, so is true treats an empty value as success.

Step 3: Read the Result​

The search tool returns one block of text, which holds JSON: a list of results, each with a title, a content excerpt and a contentUrl. Add these lines to the end of Program.cs:

Program.cs (add at the end)
// The answer is text: JSON with a list of results, each with a title and a link.
string json = result.Content.OfType<TextContentBlock>().Single().Text;
using JsonDocument document = JsonDocument.Parse(json);

// The server returns several excerpts of the same page, so keep one result per title.
foreach (JsonElement item in document.RootElement.GetProperty("results").EnumerateArray()
.DistinctBy(item => item.GetProperty("title").GetString())
.Take(3))
{
Console.WriteLine(item.GetProperty("title").GetString());
Console.WriteLine($" {item.GetProperty("contentUrl").GetString()}");
}
  • OfType<TextContentBlock>() keeps the text blocks of the result; .Single() expects exactly one, which is what this tool returns.
  • JsonDocument.Parse reads the JSON, and EnumerateArray goes through its results.
  • DistinctBy keeps the first result of each page. Without it, the first three results here were three excerpts of the same page.

Run the app:

In the terminal, in the McpDocsSearch folder, run:

Terminal
dotnet run
Output
Create an Azure storage account
https://learn.microsoft.com/azure/storage/common/storage-account-create#create-a-storage-account
Quickstart: Create, download, and list blobs with Azure CLI
https://learn.microsoft.com/azure/storage/blobs/storage-quickstart-blobs-cli
Quickstart: Create, assign, and run a storage task by using Azure CLI
https://learn.microsoft.com/azure/storage-actions/storage-tasks/storage-task-quickstart-cli

macOS-style terminal window titled Terminal — McpDocsSearch showing dotnet run printing three Microsoft Learn pages with their links: Create an Azure storage account, Quickstart: Create, download, and list blobs with Azure CLI, and Quickstart: Create, assign, and run a storage task by using Azure CLI

Three pages of Microsoft's documentation, best match first, each with the exact section the excerpt came from.

The Complete File​

macOS-style code window titled Program.cs showing a C# console app that connects to the Microsoft Learn MCP server, takes microsoft_docs_search from ListToolsAsync, calls it with CallAsync and a query argument, checks IsError, parses the text block's JSON and prints the title and contentUrl of the first three distinct results

Program.cs
using System.Text.Json;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

await using McpClient client = await McpClient.CreateAsync(
new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri("https://learn.microsoft.com/api/mcp"),
TransportMode = HttpTransportMode.StreamableHttp,
}),
new McpClientOptions { ProtocolVersion = "2025-06-18" });

// Find the search tool in the server's list.
IList<McpClientTool> tools = await client.ListToolsAsync();
McpClientTool search = tools.Single(tool => tool.Name == "microsoft_docs_search");

// Call it with its one argument, query.
CallToolResult result = await search.CallAsync(
new Dictionary<string, object?> { ["query"] = "create an Azure storage account with the Azure CLI" });

if (result.IsError is true)
{
Console.WriteLine("The tool reported an error.");
return;
}

// The answer is text: JSON with a list of results, each with a title and a link.
string json = result.Content.OfType<TextContentBlock>().Single().Text;
using JsonDocument document = JsonDocument.Parse(json);

// The server returns several excerpts of the same page, so keep one result per title.
foreach (JsonElement item in document.RootElement.GetProperty("results").EnumerateArray()
.DistinctBy(item => item.GetProperty("title").GetString())
.Take(3))
{
Console.WriteLine(item.GetProperty("title").GetString());
Console.WriteLine($" {item.GetProperty("contentUrl").GetString()}");
}

Common Mistakes​

MistakeWhat happensDo this instead
Calling client.CallToolAsync right after connectingwarn: … Tool '…' not found in cache during tools/call. Mcp-Param-* headers will not be sent.Take the tool from ListToolsAsync and use its CallAsync
Catching exceptions to find a tool that failedA failed tool doesn't throw: the failure is in IsErrorCheck IsError first
Building on the exact JSON a server returnsMicrosoft says the Learn server's request and response formats can changeCheck what you read, and keep the parsing in one place

Troubleshooting​

SymptomLikely causeFix
InvalidOperationException: Sequence contains no matching element from SingleThe server has no tool with that namePrint the names from ListToolsAsync and check the spelling
The tool warning about the cacheThe tool was called by name before the tools were listedFixed: Tool not found in cache during tools/call

FAQ​

What does the tool return besides the text?​

This one also returns the same results as structured content, in result.StructuredContent. The MCP specification asks for that duplicate: a tool that returns structured content SHOULD also return the serialized JSON in a TextContent block. Read whichever is easier; here the text block is enough.

How do I know which arguments a tool takes?​

Each McpClientTool has a JsonSchema, the input schema the server sent. tool.JsonSchema.GetRawText() prints it: for microsoft_docs_search it lists one property, query, of type string.

Conclusion​

To call an MCP tool from C#, take it from ListToolsAsync, call CallAsync with a dictionary of arguments, check IsError, and read Content. The search tool of the Microsoft Learn MCP server returns one block of text with JSON in it, which JsonDocument reads like any other JSON.

Additional Resources​