Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
20cc59b
Start on MCP server template
joelverhagen Jun 26, 2025
38d446e
Merge branch 'main' into jver/mcp-template
joelverhagen Jun 26, 2025
5ef5c50
Improve
joelverhagen Jun 26, 2025
8b06c6f
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
cd6a0e2
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
36c90b1
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
5935e56
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
4127955
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
28363b4
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
4e64775
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 26, 2025
a2ac345
Fix type, improve readme
joelverhagen Jun 26, 2025
06d2247
Update src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/Mcp…
joelverhagen Jun 30, 2025
3a6a3e8
Address comments
joelverhagen Jul 1, 2025
fb056fc
Make package path consistent
joelverhagen Jul 1, 2025
7963103
Merge remote-tracking branch 'origin/jver/mcp-template' into jver/mcp…
joelverhagen Jul 1, 2025
21e8563
Merge remote-tracking branch 'origin/main' into jver/mcp-template
joelverhagen Jul 1, 2025
6e30470
Add icon
joelverhagen Jul 1, 2025
a98b37e
Add snapshot tests for MCP server template
joelverhagen Jul 1, 2025
129faff
Remove return 0
joelverhagen Jul 1, 2025
6be6521
Added comment
joelverhagen Jul 1, 2025
5e9d6f0
Address most of the comments
joelverhagen Jul 1, 2025
eabb037
Address comments
joelverhagen Jul 1, 2025
e29a101
Remove comment that is wrong ☠️
joelverhagen Jul 1, 2025
9b8a767
Address comment
joelverhagen Jul 1, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<ItemGroup>
<!-- Keep the exclude patterns below in sync with those in AIChatWebSnapshotTests.cs -->
<Content
Include="src\*\**\*"
Include="src\ChatWithCustomData\**\*"
Exclude="
**\bin\**;
**\obj\**;
Expand All @@ -61,6 +61,14 @@
**\NuGet.config;
**\Directory.Build.targets;
**\Directory.Build.props;" />
<Content
Include="src\McpServer\**\*"
Exclude="
**\bin\**;
**\obj\**;
**\.vs\**;
**\*.sln;
**\*.in;" />
<None Include="THIRD-PARTY-NOTICES.TXT" Pack="true" PackagePath="." />
<Compile Remove="**\*" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,7 @@
"registry_name": "nuget",
"name": "<your package ID here>",
"version": "0.1.0-beta",
"package_arguments": [
{
"description": "Start the MCP server tool in server mode",
"is_required": true,
"format": "string",
"value": "start-mcp",
"default": "start-mcp",
"type": "positional",
"value_hint": "start-mcp"
}
],
"package_arguments": [],
"environment_variables": [
{
"description": "The maximum number to return from the random number generator",
Expand All @@ -32,4 +22,4 @@
"version_detail": {
"version": "0.1.0-beta"
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
{
"$schema": "http://json.schemastore.org/template",
"author": "Microsoft",
"classifications": [ "Common", "AI", "MCP" ],
"classifications": [
"Common",
"AI",
"MCP"
],
"identity": "Microsoft.Extensions.AI.Templates.McpServer.CSharp",
"name": "Local MCP Server Console App",
"description": "A project template for creating a local MCP server using the .NET MCP SDK.",
"description": "A project template for creating a Model Context Protocol (MCP) server using C# and the ModelContextProtocol package.",
"shortName": "mcpserver",
"defaultName": "McpServer",
"sourceName": "McpServer-CSharp",
Expand All @@ -13,9 +17,30 @@
"language": "C#",
"type": "project"
},
"symbols": {
"hostIdentifier": {
"type": "bind",
"binding": "HostIdentifier"
}
},
"primaryOutputs": [
{
"path": "./README.md"
},
{
"path": "./McpServer-CSharp.csproj"
}
],
"postActions": [
{
"condition": "(hostIdentifier != \"dotnetcli\" && hostIdentifier != \"dotnetcli-preview\")",
"description": "Opens README file in the editor",
"manualInstructions": [],
"actionId": "84C0DA21-51C8-4541-9940-6CA19AF04EE6",
"args": {
"files": "0"
},
"continueOnError": true
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>

<!-- Set up the NuGet package to be an MCP server -->
<PackAsTool>true</PackAsTool>
<PackageType>McpServer</PackageType>
Expand All @@ -17,11 +17,10 @@
<PackageTags>AI; MCP; server; stdio</PackageTags>
<Description>An MCP server using the MCP C# SDK.</Description>
</PropertyGroup>



<!-- Include additional files for browsing the MCP server. -->
<ItemGroup>
<None Include=".mcp/server.json" Pack="true" PackagePath="/.mcp" />
<None Include=".mcp\server.json" Pack="true" PackagePath="/.mcp/" />
<None Include="README.md" Pack="true" PackagePath="/" />
</ItemGroup>

Expand All @@ -30,4 +29,4 @@
<PackageReference Include="ModelContextProtocol" Version="${TemplatePackageVersion_ModelContextProtocol}" />
</ItemGroup>

</Project>
</Project>
Original file line number Diff line number Diff line change
@@ -1,59 +1,32 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;
using McpServer_CSharp.Tools;

var builder = Host.CreateApplicationBuilder(args);

if (args.Length == 0 || args[0] != "start-mcp")
// Uncomment the following lines if you want to enforce the MCP command-line arguments.
// You can use command-line arguments to support multiple modes or commands in your application.
// These would be specified in the "package_arguments" property in the .mcp/server.json to inform client tools.
/*
if (args.Length == 0 || args[0] != "mcp")
{
Console.Error.WriteLine("Error: invalid command. Use the 'start-mcp' command-line argument to start the MCP server.");
return 1;
}

var maxNumberEnv = Environment.GetEnvironmentVariable("MAX_RANDOM_NUMBER");
if (!int.TryParse(maxNumberEnv, out var maxNumber) || maxNumber <= 0)
{
Console.Error.WriteLine("Error: you must set the MAX_RANDOM_NUMBER environment variable to a positive integer.");
Console.Error.WriteLine("Error: invalid command. Use the 'mcp' command-line argument to start the MCP server.");
return 1;
}
*/

builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr (stdout is used for the MCP protocol messages).
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});

// add the MCP services, discover tools from the current assembly
// Add the MCP services: the transport to use (stdio) and the tools to register.
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithTools<RandomNumberTool>();

// add dependencies for the MCP server tools
builder.Services.AddSingleton(_ => new RandomNumberService(maxNumber));
.WithTools<RandomNumberTools>();

await builder.Build().RunAsync();
return 0;

public class RandomNumberService(int max)
{
public int Max => max;
public int GetRandomNumber() => Random.Shared.Next(1, max + 1);
}

public class RandomNumberTool(RandomNumberService service)
{
[McpServerTool, Description("Returns the maximum random number that can be generated by the tool.")]
public int MaxRandomNumber()
{
return service.Max;
}

[McpServerTool, Description("Returns a random number between 1 and the maximum number allowed by the tool.")]
public int GetRandomNumber()
{
return service.GetRandomNumber();
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# MCP Server

This README was created using the .NET MCP server template project. It demonstrates how you can easily create an MCP server using .NET and then package it in a NuGet package.
This README was created using the C# MCP server template project. It demonstrates how you can easily create an MCP server using C# and then package it in a NuGet package.

See [aka.ms/nuget/mcp/guide](https://aka.ms/nuget/mcp/guide) for the full guide.

## Checklist before publishing to NuGet.org

- Update the package metadata in the .csproj file
- Update `.mcp/server.json` to declare your MCP server's inputs
- Test the MCP server locally using the steps below
- Test the MCP server locally using the steps below.
- Update the package metadata in the .csproj file.
- Update `.mcp/server.json` to declare your MCP server's inputs.
- Pack the project using `dotnet pack`.

The `bin/Release` directory will contain the package file (.nupkg), which can be [published to NuGet.org](https://learn.microsoft.com/nuget/nuget-org/publish-a-package).

## Using the MCP Server in VS Code

Expand All @@ -18,7 +21,7 @@ Once the MCP server package is published to NuGet.org, you can use the following
{
"mcp": {
"servers": {
"my-custom-mcp": {
"McpServer-CSharp": {
"type": "stdio",
"command": "dotnet",
"args": [
Expand All @@ -27,9 +30,7 @@ Once the MCP server package is published to NuGet.org, you can use the following
"<your package ID here>",
"--version",
"<your package version here>",
"--yes",
"--",
"start-mcp"
"--yes"
],
"env": {
"MAX_RANDOM_NUMBER": 100
Expand All @@ -40,25 +41,42 @@ Once the MCP server package is published to NuGet.org, you can use the following
}
```

Now you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `GetRandomNumber` tool on the `my-custom-mcp` MCP server and show you the results.
Now you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `my-custom-mcp` MCP server and show you the results.

## Developing locally in VS Code

To test this MCP server from source code (locally) without using a built MCP server package, create a `.vscode/mcp.json` file (a VS Code workspace settings file) in your project directory and add the following configuration:

## Developing locally
```json
{
"servers": {
"McpServer-CSharp": {
"type": "stdio",
"command": "dotnet",
"args": [
"run"
],
"env": {
"MAX_RANDOM_NUMBER": 100
}
}
}
}
```

To test this MCP server from source code (locally) without using a built MCP server package, use the following VS Code configuration:
Alternatively, you can configure your VS Code user settings to use your local project:

```json
{
"mcp": {
"servers": {
"my-custom-mcp": {
"McpServer-CSharp": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"<PATH TO PROJECT DIRECTORY>",
"--",
"start-mcp"
"<PATH TO PROJECT DIRECTORY>"
],
"env": {
"MAX_RANDOM_NUMBER": 100
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.ComponentModel;
using ModelContextProtocol.Server;

namespace McpServer_CSharp.Tools;

/// <summary>
/// Sample MCP tools for demonstration purposes.
/// These tools can be invoked by MCP clients to perform various operations.
/// </summary>
public class RandomNumberTools
{
private readonly int _maxNumber;

public RandomNumberTools()
{
// Process configuration settings from the environment variables.
// These will be provided by the MCP client application, such as VS Code.
// Configuration settings could be provided via dependency injection and the IOptions pattern.
var maxNumberEnv = Environment.GetEnvironmentVariable("MAX_RANDOM_NUMBER");
if (!int.TryParse(maxNumberEnv, out var maxNumber) || maxNumber <= 0)
{
throw new InvalidOperationException("Error: you must set the MAX_RANDOM_NUMBER environment variable to a positive integer.");
}

_maxNumber = maxNumber;
}

/// <summary>
/// Returns the maximum random number that can be generated by the tool.
/// </summary>
/// <returns>The maximum random number.</returns>
[McpServerTool(Name = "get_max_random_number")]
[Description("Returns the maximum random number that can be generated by the tool.")]
public int GetMaxRandomNumber()
{
return _maxNumber;
}

/// <summary>
/// Returns a random number between 1 and the maximum number allowed by the tool (inclusive).
/// </summary>
/// <returns>A random number.</returns>
[McpServerTool(Name = "get_random_number")]
[Description("Returns a random number between 1 and the maximum number allowed by the tool.")]
public int GetRandomNumber()
{
return Random.Shared.Next(1, _maxNumber + 1);
}
}
Loading