MCP from Scratch: From a C# Method to REST, MCP, and an AI Assistant - Part 1: Understanding MCP Fundamentals in C#
Introduction
This article is the first part of a two-part series. In Part 1, we follow a resume skills operation from a local C# method through REST and into an MCP client-server interaction, covering tool discovery, invocation, implementation, and error handling without an AI model. Part 2 continues with Microsoft Agent Framework and examines how an AI assistant can use these MCP tools.
Model Context Protocol (MCP) provides a standardized way for applications to expose tools and other capabilities that can be discovered and used by compatible clients. Understanding MCP requires more than knowing how to register a tool or call it through an SDK. It also requires understanding the communication between clients and servers, how capabilities are described and discovered, and how requests and results move between applications.
This article explains these concepts through a practical C# example, using the existing implementation in the AI Engineering Training repository. The objective is to understand how MCP works, why it can be useful alongside established approaches such as REST, and how it integrates with Microsoft Agent Framework to make application functionality available to AI assistants.
We begin with a simple requirement: retrieving the skills stored in a fictional resume profile. First, we implement the operation as an ordinary C# method. Next, we consider how a separate application could access the same functionality through a REST API. From there, we introduce MCP and examine how the operation can be exposed as a discoverable tool, invoked through an MCP client, and used without involving an AI model.
Once the MCP interaction is established, we extend the example to an AI assistant built with Microsoft Agent Framework. We follow the complete execution flow and examine how the application validates tool requests, handles errors, enforces execution restrictions, and controls operations that modify files.
The REST examples are illustrative, while the MCP and Agent Framework code comes from the existing repository. By following the same resume operation through these different stages, we can examine each mechanism without changing the underlying business functionality.
1. A profile and a method that retrieves its skills
The server project stores fictional profiles in SampleData/profiles.json. Alex's entry contains an ID, a display name, a summary, and the skills array:
{
"id": "alex",
"name": "Alex Morgan (fictional)",
"summary": "Built a fictional library reservation API with C# and .NET. Stored book availability in PostgreSQL and packaged the API with Docker.",
"skills": ["C#", ".NET", "PostgreSQL", "Docker"]
}The requested operation is deliberately narrower than summarizing a resume. If the caller supplies alex, it should receive C#, .NET, PostgreSQL, and Docker, in that order. In ResumeTools.cs, the operation is expressed as a C# method:
public List<string> ListSkills(
[Description("The exact fictional profile ID, such as alex.")] string profileIdString)
{
return GetProfile(profileIdString).SkillStrings;
}ListSkills does not perform a search itself. It asks GetProfile for the matching profile and returns that profile's SkillStrings. The lookup is:
public ResumeProfile GetProfile(
[Description("The exact fictional profile ID, such as alex.")] string profileIdString)
{
return resumeProfiles.SingleOrDefault(resumeProfile => resumeProfile.IdString == profileIdString)
?? throw new McpException("The requested fictional profile does not exist.");
}SingleOrDefault looks for a record whose IdString matches the supplied value. If no record matches, the method throws instead of choosing a different profile. The source loader and validator, discussed later, ensure that duplicate identifiers are not accepted when the server starts. For alex, the values are:
C#, .NET, PostgreSQL, DockerThe [Description] attribute describes the argument to callers that inspect method metadata. The exception uses McpException because this code lives in the actual MCP server project. Neither detail changes the basic calculation: given an identifier, find the stored profile and return its list. The method makes no request to an AI model. If another part of the same program has access to a suitable ResumeTools instance, it can call ListSkills("alex") just as it would call any ordinary C# method. Arguments and results remain C# values inside one process.
2. A website needs the same information
Suppose the profile data is managed by a resume service, but a website that displays profiles runs as a separate application. The website cannot directly invoke a method on an object inside the service's running process. It needs an interface the service can expose across that boundary. A conventional approach is an HTTP API. One possible REST-style route is GET /profiles/{profileId}/skills. A website requesting Alex's skills could send:
GET /profiles/alex/skills HTTP/1.1
Host: localhost:5000
Accept: application/jsonThe receiving service would extract alex from the route, use its profile lookup, and serialize the returned skills as JSON:
HTTP/1.1 200 OK
Content-Type: application/json
["C#", ".NET", "PostgreSQL", "Docker"]A C# caller could make the same request using HttpClient:
using System.Net.Http.Json;
using var httpClient = new HttpClient
{
BaseAddress = new Uri("http://localhost:5000/")
};
List<string>? skills = await httpClient.GetFromJsonAsync<List<string>>(
"profiles/alex/skills");The website knows an address and an HTTP contract rather than a C# object reference. GET identifies the HTTP operation, /profiles/alex/skills identifies the requested data, and the JSON response can be read by applications written in different languages. A service could return 404 Not Found for an unknown profile, although that mapping would have to be implemented in this hypothetical REST service. The actual MCP project throws McpException in its lookup.
The service may eventually expose other operations, such as returning the entire profile or creating a versioned resume. Those endpoints can be documented with OpenAPI, including routes, parameters, request bodies, and response schemas. OpenAPI is machine-readable, so other software can inspect an HTTP API without guessing its interface. A REST-based system can fully meet the website's requirement.
3. The consumer is an application that brings together external tools
Consider a different consumer. A desktop assistant already connects to several systems, such as a project tracker and a calendar, and needs to offer resume operations alongside them. Its host application must make each operation available in a form that its tool-invocation system understands. For the hypothetical REST endpoint, the integration might read an OpenAPI description, turn the endpoint into a callable tool definition, map a selected profile ID into an HTTP request, and translate the HTTP response back into a result the assistant can use.
That integration is possible. In fact, some systems use OpenAPI descriptions to construct tools automatically. Another design is for the assistant host to use a Model Context Protocol (MCP) client, and for each service to expose an MCP server. The host then communicates with those servers through the same protocol for listing and invoking their tools, even when the services implement different business operations.
The resume service could continue to expose REST endpoints for a website while also providing an MCP interface to compatible hosts. An MCP server could even call an existing REST API internally. The method that returns Alex's skills does not need to change because the external integration interface changes.
For the resume operation, the interface exposed by MCP is not the URL /profiles/alex/skills. It is a tool named list_skills with a named input, profileIdString. An MCP client can ask the server which tools are available and what inputs they accept, then request one of those tools by name. The next sections follow that exchange using an ordinary C# program. The model is not involved in these first MCP calls.
4. The two programs and their connection
The repository's MCP example uses separate .NET console applications: mcp-client and mcp-server. The server owns the profile records and the code that accesses them. The other executable starts the server and communicates with it using an MCP client component.
mcp-client application
|
| MCP messages
v
mcp-server application
|
v
Loaded fictional profilesThese are different processes, even though both run on the same computer. The server's ResumeTools object exists inside the server process. The client cannot treat that object as a normal local reference. Instead, it sends messages requesting the operations that the server exposes.
The example uses standard input/output (STDIO) transport. The client launches the server process and writes protocol messages to its standard input. The server sends protocol messages through standard output. Diagnostics belong on standard error so that ordinary log messages are not mistaken for protocol data. A server in this arrangement does not need an HTTP listener or a web-server framework.
MCP defines the meaning and structure of the exchanged messages; STDIO is how this particular connection carries them. MCP can also be used over HTTP-based transports. The protocol's request messages use JSON-RPC 2.0, which provides fields such as a method name, parameters, and an identifier for matching a response to a request.
Before normal tool requests, a client and server using the protocol generation represented in this project establish an MCP session through initialization. The SDK handles that handshake, including exchanging supported protocol information and capabilities. Application code does not manually construct its initialization messages. Once the connection is ready, the client can ask what the server offers.
5. Discovering list_skills
The client does not need to guess whether the server has a particular method or which input name it expects. MCP defines tools/list, a protocol operation for requesting the tools advertised by a server.
For the resume server, the returned catalog includes three tools:
Advertised tool | Operation |
|---|---|
| Return the selected fictional profile. |
| Return the skills recorded for a supplied profile ID. |
| Attempt to save supplied Markdown under a version label, when server settings permit it. |
The client sends a tools/list request. In the protocol generation used by this project, its essential shape is:
Illustrative discovery request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}The server replies with an array of tool definitions. Each definition includes a tool name and an inputSchema; the resume server supplies descriptions as well. The client learns the names, descriptions, and schemas from that response. It can inspect a tool before trying to invoke it. For list_skills, a simplified form of the input schema is:
{
"type": "object",
"properties": {
"profileIdString": {
"type": "string"
}
},
"required": ["profileIdString"]
}The input is a JSON object with a required string field named profileIdString. A request containing a field named profileId instead would not match this contract. The SDK-generated schema printed by the real program contains additional details beyond this reduced illustration.
tools/list is the standard MCP protocol method. list_skills is a tool name chosen by the resume server. The server can advertise tools even when a particular operation is not currently authorized. For instance, save_resume remains visible on a read-only connection, but the server does not allow a write through that connection. The tool catalog tells the client what is available to request, not what every caller is entitled to execute.
6. Requesting list_skills over MCP
After discovering the required input, the client can invoke the tool. The standard MCP method is tools/call, with the custom tool name and arguments supplied in its parameters. An illustrative request for Alex's skills looks like this:
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "list_skills",
"arguments": {
"profileIdString": "alex"
}
}
}The outer method selects the MCP protocol operation. The inner name selects the server's registered tool. Its arguments object carries the ID in the form described by the schema. JSON-RPC's id connects the response to this particular request; it is not Alex's profile ID. The server SDK finds the registered list_skills operation and invokes its C# method. GetProfile finds alex, and ListSkills returns the stored list. The SDK places that output into an MCP tool result. Because this server returns the list as JSON text, a simplified response can be drawn like this:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "[\"C#\",\".NET\",\"PostgreSQL\",\"Docker\"]"
}
],
"isError": false
}
}The result contains a content block rather than placing the C# list directly at the top level of the JSON-RPC response. The client must read the content and interpret it according to the tool's contract. isError: false indicates a successful tool execution in this illustration. Later we will see why an MCP reply and a successful tool execution are not the same thing. The values still come from the stored profile, not from an AI model.
MCP also defines capabilities for resources and reusable prompts. The current project exposes callable operations, so its application-level protocol traffic focuses on tools. The names tools/list and tools/call belong to MCP; get_profile, list_skills, and save_resume are names chosen for this server.
7. How the C# server exposes its methods
The server cannot advertise list_skills unless it registers that operation with its MCP SDK. Its Program.cs first loads the copied profile JSON and validates the records. ProfileValidator rejects an empty collection, duplicate or blank IDs, missing names or summaries, and skill lists that are empty or contain blank entries. Several independent source errors can be reported together with field paths. Invalid data stops server startup rather than allowing a tool to serve unreliable records.
The startup code also constructs ServerSettings to control whether writing is permitted and where versions may be stored. Missing write permission defaults to disabled; invalid permission values or a relative versions directory stop startup. These decisions come from server configuration, not from a model or tool-call argument.
The server registers its data and services, then enables MCP:
hostApplicationBuilder.Services.AddSingleton(resumeProfiles);
hostApplicationBuilder.Services.AddSingleton(serverSettings);
hostApplicationBuilder.Services.AddSingleton<ResumeWriter>();
hostApplicationBuilder.Services.AddMcpServer().WithStdioServerTransport().WithToolsFromAssembly();The singletons allow dependency injection to supply loaded profiles, settings, and ResumeWriter to the tool class. AddMcpServer() configures the MCP server services. WithStdioServerTransport() selects the local transport. WithToolsFromAssembly() finds the attributed tools in the server assembly.
The ResumeTools class carries [McpServerToolType]. Its skills method is registered with the following metadata:
[McpServerTool(
Name = "list_skills",
ReadOnly = true,
OpenWorld = false)]
[Description("List the skills stated in a fictional profile. Return the source order without adding skills.")]
public List<string> ListSkills(
[Description("The exact fictional profile ID, such as alex.")] string profileIdString)
{
return GetProfile(profileIdString).SkillStrings;
}The public MCP tool name comes from Name = "list_skills". The [Description] attributes give the tool and its parameter human-readable descriptions. The SDK derives the input schema from the method signature and metadata. ReadOnly = true advertises read-only behavior; OpenWorld = false indicates the operation works with the server's controlled data rather than an open-ended external environment. Neither annotation by itself enforces permission: actual behavior comes from code and process configuration. The registered method still delegates to GetProfile(profileIdString).SkillStrings. MCP has added an externally discoverable interface around the existing operation; it has not replaced the source lookup.
8. Finding the server and client code
The relevant project files are organized as follows:
07-mcp-server/
mcp-client/
Program.cs
McpConnection.cs
ResumeAssistant.cs
InputsValidator.cs
ToolResultParser.cs
ResumePreparer.cs
SkillAnswerParser.cs
SkillAnswerValidator.cs
ResumeSaver.cs
OutputPrinter.cs
mcp-server/
Program.cs
ResumeTools.cs
ProfileLoader.cs
ProfileValidator.cs
ServerSettings.cs
ResumeWriter.cs
SampleData/profiles.json
mcp-client.tests/
mcp-server.tests/The server's Program.cs configures startup, ResumeTools.cs contains the exposed operations, and the loader and validator handle the source data. ServerSettings.cs and ResumeWriter.cs are involved in the optional write workflow. On the client side, Program.cs orchestrates preparation, conversation, and saving. McpConnection.cs creates the connection; ToolResultParser.cs and ResumePreparer.cs inspect returned facts. ResumeAssistant.cs, SkillAnswerParser.cs, and SkillAnswerValidator.cs become relevant when the model is added. ResumeSaver.cs owns the approved write stage. The client fixes the selected profile and question at the top of its program:
const string profileIdString = "alex";
const string questionString = "List my skills from the selected fictional profile.";The second fictional profile is sam, whose skills are TypeScript, React, SQLite, and Playwright. The tool interface does not change for Sam. The caller supplies a different ID and receives that profile's facts.
The client build builds the server and copies the server executable, runtime dependencies, and sample data into a Server directory under the client output. The project reference uses ReferenceOutputAssembly="false", which creates a build dependency without exposing the server's C# classes as a normal in-process client API. Paths to copied assets are based on AppContext.BaseDirectory, allowing console runs, Visual Studio, and tests to locate the same inputs.
9. Starting the process and making direct MCP calls
McpConnection.cs checks for the copied Server/mcp-server.dll, resolves its absolute path, and launches it through dotnet. This happens after the build, so compilation output never enters the protocol stream. The transport configuration includes:
Dictionary<string, string?> environmentStringsDictionary =
StdioClientTransportOptions.GetDefaultEnvironmentVariables();
environmentStringsDictionary["RESUME_MCP_ALLOW_WRITE"] = allowWriteBool ? "true" : "false";
environmentStringsDictionary["RESUME_MCP_VERSIONS_DIRECTORY"] = Path.GetFullPath(versionsDirectoryString);
var stdioClientTransport = new StdioClientTransport(new StdioClientTransportOptions
{
Name = "FictionalResumeServer",
Command = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet",
Arguments = [serverPathString],
InheritEnvironmentVariables = false,
EnvironmentVariables = environmentStringsDictionary,
StandardErrorLines = errorString => OutputPrinter.PrintServerLog(errorString)
});Command chooses the .NET host, Arguments supplies the server DLL path, and StandardErrorLines gives the parent application a way to display diagnostic output separately. The server redirects its own console logging to standard error. A message printed to standard output would interfere with a protocol stream that expects MCP messages there.
The child process receives the SDK's default environment values plus RESUME_MCP_ALLOW_WRITE and RESUME_MCP_VERSIONS_DIRECTORY. InheritEnvironmentVariables = false prevents automatic inheritance of the entire parent environment. Note that the server doesn't make any model calls. After the STDIO transport starts, McpClient.CreateAsync establishes the MCP connection. The client's Program.cs creates the read-only connection and lists its tools:
await using McpClient readOnlyMcpClient = await McpConnection.ConnectAsync(
folderString,
allowWriteBool: false,
versionsDirectoryString,
preparationCancellationTokenSource.Token);
IList<McpClientTool> mcpClientTools =
await readOnlyMcpClient.ListToolsAsync(cancellationToken: preparationCancellationTokenSource.Token);
OutputPrinter.PrintDiscovery(mcpClientTools);ListToolsAsync returns McpClientTool objects representing the advertised capabilities. OutputPrinter.PrintDiscovery displays their names, descriptions, and schemas. await using ensures the connection and its managed server process are disposed when the scope ends, including exceptional exits. The program then uses that connection to call get_profile directly. The result is parsed and checked: ResumePreparer confirms the requested ID, nonempty name, summary, and skills, then constructs a Markdown resume draft from those source values. The client also calls list_skills directly:
CallToolResult skillsCallToolResult = await readOnlyMcpClient.CallToolAsync(
"list_skills",
new Dictionary<string, object?>
{
["profileIdString"] = profileIdString
},
cancellationToken: preparationCancellationTokenSource.Token);
List<string> directSkillStrings = ToolResultParser.Parse(skillsCallToolResult).Deserialize<List<string>>()
?? throw new InvalidDataException("The skills tool returned no skill list.");The dictionary uses exactly the profileIdString key declared by the tool schema. The SDK converts the call into MCP messages over the existing connection and returns a CallToolResult. ToolResultParser checks it, then Deserialize<List<string>>() turns the JSON into a C# list. InputsValidator checks the question, the exact catalog of three tools, and agreement between the direct skills and the prepared profile. All of this local discovery and preparation can succeed without any AI model.
10. A returned message can report a failed tool
Suppose the client asks for a profile ID that the source data does not contain. The connection might still work perfectly: the request reaches a known tool, and the tool's lookup throws McpException. That is different from a malformed protocol request or a request for a nonexistent tool. MCP distinguishes protocol-level errors from tool execution errors. A successful exchange of protocol messages does not guarantee that the requested business operation succeeded. CallToolResult can have its IsError flag set even though the client received a reply. The direct parser handles the shape returned by this server:
string textString = string.Join(
"\n",
callToolResult.Content.OfType<TextContentBlock>()
.Select(textContentBlock => textContentBlock.Text));
if (callToolResult.IsError == true)
{
throw new InvalidDataException($"MCP tool failed: {textString}");
}
return JsonElement.Parse(textString);It joins text blocks, checks the tool error flag, and parses the text as JSON. That is suitable for this server's JSON-text replies; other MCP tools may return content types that need different parsing. A valid JSON document is still not automatically a valid profile. ResumePreparer and InputsValidator perform separate application-level checks after parsing. For this resume lookup, there are therefore several possible failure points: the protocol request might be invalid, the tool might report an execution error, the returned content might not parse as expected, or a well-formed result might contain data that fails the application's source checks. The client reports failure rather than filling a gap with guessed skills.
Continue to Part 2
This concludes Part 1 of the series. We have established how the C# MCP server exposes tools and how a client discovers, invokes, and checks their results without involving an AI model. In Part 2, we build on this working connection by integrating the tools with Microsoft Agent Framework, following model-requested tool calls and examining the host-side checks and controls around them.
Leave a Reply
Your e-mail address will not be published. Required fields are marked *