Skip to content

Commit c768dce

Browse files
authored
C# quickstarts (modelcontextprotocol#216)
* Server quickstart docs for C# * C# client quickstart
1 parent fb63fef commit c768dce

File tree

3 files changed

+413
-0
lines changed

3 files changed

+413
-0
lines changed

images/quickstart-dotnet-client.png

81.6 KB
Loading

quickstart/client.mdx

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1365,6 +1365,184 @@ If you see:
13651365

13661366
</Tab>
13671367

1368+
<Tab title="C#">
1369+
[You can find the complete code for this tutorial here.](https://github.io/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient)
1370+
1371+
## System Requirements
1372+
Before starting, ensure your system meets these requirements:
1373+
- .NET 8.0 or higher
1374+
- Anthropic API key (Claude)
1375+
- Windows, Linux, or MacOS
1376+
1377+
## Setting up your environment
1378+
1379+
First, create a new .NET project:
1380+
```bash
1381+
dotnet new console -n QuickstartClient
1382+
cd QuickstartClient
1383+
```
1384+
1385+
Then, add the required dependencies to your project:
1386+
```bash
1387+
dotnet add package ModelContextProtocol --preview
1388+
dotnet add package Anthropic.SDK
1389+
dotnet add package Microsoft.Extensions.Hosting
1390+
```
1391+
1392+
## Setting up your API key
1393+
You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1394+
1395+
```bash
1396+
dotnet user-secrets init
1397+
dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"
1398+
```
1399+
1400+
## Creating the Client
1401+
### Basic Client Structure
1402+
First, let's setup the basic client class:
1403+
```csharp
1404+
using Microsoft.Extensions.Configuration;
1405+
using Microsoft.Extensions.Hosting;
1406+
1407+
var builder = Host.CreateEmptyApplicationBuilder(settings: null);
1408+
1409+
builder.Configuration
1410+
.AddUserSecrets<Program>();
1411+
```
1412+
1413+
This creates the beginnings of a .NET console application that can read the API key from user secrets.
1414+
1415+
Next, we'll setup the MCP Client:
1416+
1417+
```csharp
1418+
var (command, arguments) = args switch
1419+
{
1420+
[var script] when script.EndsWith(".py") => ("python", script),
1421+
[var script] when script.EndsWith(".js") => ("node", script),
1422+
[var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", $"run --project {script} --no-build"),
1423+
_ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
1424+
};
1425+
1426+
var mcpClient = await McpClientFactory.CreateAsync(new()
1427+
{
1428+
Id = "demo-client",
1429+
Name = "Demo Client",
1430+
TransportType = TransportTypes.StdIo,
1431+
TransportOptions = new()
1432+
{
1433+
["command"] = command,
1434+
["arguments"] = arguments,
1435+
}
1436+
});
1437+
1438+
var tools = await mcpClient.ListToolsAsync();
1439+
foreach (var tool in tools)
1440+
{
1441+
Console.WriteLine($"Connected to server with tools: {tool.Name}");
1442+
}
1443+
```
1444+
<Note>
1445+
Be sure to add the `using` statements for the namespaces:
1446+
```csharp
1447+
using ModelContextProtocol.Client;
1448+
using ModelContextProtocol.Protocol.Transport;
1449+
```
1450+
</Note>
1451+
1452+
This configures a MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.
1453+
1454+
### Query processing logic
1455+
Now let's add the core functionality for processing queries and handling tool calls:
1456+
1457+
```csharp
1458+
IChatClient anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
1459+
.Messages
1460+
.AsBuilder()
1461+
.UseFunctionInvocation()
1462+
.Build();
1463+
1464+
var options = new ChatOptions
1465+
{
1466+
MaxOutputTokens = 1000,
1467+
ModelId = "claude-3-5-sonnet-20241022",
1468+
Tools = [.. tools.Cast<AITool>()]
1469+
};
1470+
1471+
while (true)
1472+
{
1473+
Console.WriteLine("MCP Client Started!");
1474+
Console.WriteLine("Type your queries or 'quit' to exit.");
1475+
1476+
string? query = Console.ReadLine();
1477+
1478+
if (string.IsNullOrWhiteSpace(query))
1479+
{
1480+
continue;
1481+
}
1482+
if (string.Equals(query, "quit", StringComparison.OrdinalIgnoreCase))
1483+
{
1484+
break;
1485+
}
1486+
1487+
var response = await anthropicClient.GetResponseAsync(query, options);
1488+
1489+
foreach (var message in response.Messages)
1490+
{
1491+
Console.WriteLine(message.Text);
1492+
}
1493+
}
1494+
1495+
anthropicClient.Dispose();
1496+
await mcpClient.DisposeAsync();
1497+
```
1498+
1499+
## Key Components Explained
1500+
1501+
### 1. Client Initialization
1502+
* The client is initialized using `McpClientFactory.CreateAsync()`, which sets up the transport type and command to run the server.
1503+
1504+
### 2. Server Connection
1505+
* Supports Python, Node.js, and .NET servers.
1506+
* The server is started using the command specified in the arguments.
1507+
* Configures to use stdio for communication with the server.
1508+
* Initializes the session and available tools.
1509+
1510+
### 3. Query Processing
1511+
* Leverages [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/ai-extensions) for the chat client.
1512+
* Configures the `IChatClient` to use automatic tool (function) invocation.
1513+
* The client reads user input and sends it to the server.
1514+
* The server processes the query and returns a response.
1515+
* The response is displayed to the user.
1516+
1517+
### Running the Client
1518+
To run your client with any MCP server:
1519+
```bash
1520+
dotnet run -- path/to/server.csproj # dotnet server
1521+
dotnet run -- path/to/server.py # python server
1522+
dotnet run -- path/to/server.js # node server
1523+
```
1524+
<Note>
1525+
If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `dotnet run -- path/to/QuickstartWeatherServer`.
1526+
</Note>
1527+
1528+
The client will:
1529+
1530+
1. Connect to the specified server
1531+
2. List available tools
1532+
3. Start an interactive chat session where you can:
1533+
- Enter queries
1534+
- See tool executions
1535+
- Get responses from Claude
1536+
4. Exit the session when done
1537+
1538+
Here's an example of what it should look like it connected to a weather server quickstart:
1539+
1540+
<Frame>
1541+
<img src="/images/quickstart-dotnet-client.png" />
1542+
</Frame>
1543+
1544+
</Tab>
1545+
13681546
</Tabs>
13691547

13701548
## Next steps

0 commit comments

Comments
 (0)