Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions src/ProjectTemplates/GeneratedContent.targets
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<_LocalChatTemplateVariant>aspire</_LocalChatTemplateVariant>

<_ChatWithCustomDataContentRoot>$(MSBuildThisFileDirectory)Microsoft.Extensions.AI.Templates\src\ChatWithCustomData\</_ChatWithCustomDataContentRoot>
<_McpServerContentRoot>$(MSBuildThisFileDirectory)Microsoft.Extensions.AI.Templates\src\McpServer\</_McpServerContentRoot>
</PropertyGroup>

<Target Name="ComputeGeneratedContentProperties">
Expand All @@ -34,9 +35,11 @@
<TemplatePackageVersion_AzureIdentity>1.14.0</TemplatePackageVersion_AzureIdentity>
<TemplatePackageVersion_AzureSearchDocuments>11.6.0</TemplatePackageVersion_AzureSearchDocuments>
<TemplatePackageVersion_CommunityToolkitAspire>9.4.1-beta.291</TemplatePackageVersion_CommunityToolkitAspire>
<TemplatePackageVersion_MicrosoftExtensionsHosting>10.0.0-preview.5.25277.114</TemplatePackageVersion_MicrosoftExtensionsHosting>
<TemplatePackageVersion_MicrosoftExtensionsServiceDiscovery>9.3.0</TemplatePackageVersion_MicrosoftExtensionsServiceDiscovery>
<TemplatePackageVersion_MicrosoftSemanticKernel>1.53.0</TemplatePackageVersion_MicrosoftSemanticKernel>
<TemplatePackageVersion_MicrosoftSemanticKernel_Preview>1.53.0-preview</TemplatePackageVersion_MicrosoftSemanticKernel_Preview>
<TemplatePackageVersion_ModelContextProtocol>0.3.0-preview.1</TemplatePackageVersion_ModelContextProtocol>
<TemplatePackageVersion_OllamaSharp>5.1.18</TemplatePackageVersion_OllamaSharp>
<TemplatePackageVersion_OpenTelemetry>1.12.0</TemplatePackageVersion_OpenTelemetry>
<TemplatePackageVersion_PdfPig>0.1.10</TemplatePackageVersion_PdfPig>
Expand Down Expand Up @@ -64,9 +67,11 @@
TemplatePackageVersion_AzureIdentity=$(TemplatePackageVersion_AzureIdentity);
TemplatePackageVersion_AzureSearchDocuments=$(TemplatePackageVersion_AzureSearchDocuments);
TemplatePackageVersion_CommunityToolkitAspire=$(TemplatePackageVersion_CommunityToolkitAspire);
TemplatePackageVersion_MicrosoftExtensionsHosting=$(TemplatePackageVersion_MicrosoftExtensionsHosting);
TemplatePackageVersion_MicrosoftExtensionsServiceDiscovery=$(TemplatePackageVersion_MicrosoftExtensionsServiceDiscovery);
TemplatePackageVersion_MicrosoftSemanticKernel=$(TemplatePackageVersion_MicrosoftSemanticKernel);
TemplatePackageVersion_MicrosoftSemanticKernel_Preview=$(TemplatePackageVersion_MicrosoftSemanticKernel_Preview);
TemplatePackageVersion_ModelContextProtocol=$(TemplatePackageVersion_ModelContextProtocol);
TemplatePackageVersion_OllamaSharp=$(TemplatePackageVersion_OllamaSharp);
TemplatePackageVersion_OpenTelemetry=$(TemplatePackageVersion_OpenTelemetry);
TemplatePackageVersion_PdfPig=$(TemplatePackageVersion_PdfPig);
Expand Down Expand Up @@ -100,6 +105,9 @@
<GeneratedContent
Include="$(_ChatWithCustomDataContentRoot)ChatWithCustomData-CSharp.ServiceDefaults\ChatWithCustomData-CSharp.ServiceDefaults.csproj.in"
OutputPath="$(_ChatWithCustomDataContentRoot)ChatWithCustomData-CSharp.ServiceDefaults\ChatWithCustomData-CSharp.ServiceDefaults.csproj" />
<GeneratedContent
Include="$(_McpServerContentRoot)McpServer-CSharp\McpServer-CSharp.csproj.in"
OutputPath="$(_McpServerContentRoot)McpServer-CSharp\McpServer-CSharp.csproj" />

<!-- The following content only gets generated when using just-built packages -->
<_GeneratedContentEnablingJustBuiltPackages
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@
**\NuGet.config;
**\Directory.Build.targets;
**\Directory.Build.props;" />

<!-- Keep the exclude patterns below in sync with those in McpServerSnapshotTests.cs -->
<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
@@ -0,0 +1,20 @@
{
"description": "<your description here>",
"name": "io.github.<your GitHub username here>/<your repo name>",
"packages": [
{
"registry_name": "nuget",
"name": "<your package ID here>",
"version": "0.1.0-beta",
"package_arguments": [],
"environment_variables": []
}
],
"repository": {
"url": "https://github.com/<your GitHub username here>/<your repo name>",
"source": "github"
},
"version_detail": {
"version": "0.1.0-beta"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json.schemastore.org/dotnetcli.host",
"symbolInfo": {},
"usageExamples": [
""
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/ide.host",
"order": 0,
"icon": "ide/icon.ico",
"symbolInfo": []
}
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"$schema": "http://json.schemastore.org/template",
"author": "Microsoft",
"classifications": [
"Common",
"AI",
"MCP"
],
"identity": "Microsoft.Extensions.AI.Templates.McpServer.CSharp",
"name": "Local MCP Server Console App",
"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",
"preferNameDirectory": true,
"tags": {
"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
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<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>

<!-- Set recommended package metadata -->
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageId>SampleMcpServer</PackageId>
<PackageVersion>0.1.0-beta</PackageVersion>
<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="README.md" Pack="true" PackagePath="/" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="${TemplatePackageVersion_MicrosoftExtensionsHosting}" />
<PackageReference Include="ModelContextProtocol" Version="${TemplatePackageVersion_ModelContextProtocol}" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var builder = Host.CreateApplicationBuilder(args);

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

// Add the MCP services: the transport to use (stdio) and the tools to register.
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithTools<RandomNumberTools>();

await builder.Build().RunAsync();
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# MCP Server

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

- Test the MCP server locally using the steps below.
- Update the package metadata in the .csproj file, in particular the `<PackageId>`.
- Update `.mcp/server.json` to declare your MCP server's inputs.
- See [configuring inputs](https://aka.ms/nuget/mcp/guide/configuring-inputs) for more details.
- 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

Once the MCP server package is published to NuGet.org, you can use the following VS Code user configuration to download and install the MCP server package. See [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) for more information about using MCP servers in VS Code.

```json
{
"mcp": {
"servers": {
"McpServer-CSharp": {
"type": "stdio",
"command": "dotnet",
"args": [
"tool",
"exec",
"<your package ID here>",
"--version",
"<your package version here>",
"--yes"
]
}
}
}
}
```

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 `McpServer-CSharp` 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:

```json
{
"servers": {
"McpServer-CSharp": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"<RELATIVE PATH TO PROJECT DIRECTORY>"
]
}
}
}
```

Alternatively, you can configure your VS Code user settings to use your local project:

```json
{
"mcp": {
"servers": {
"McpServer-CSharp": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"<FULL PATH TO PROJECT DIRECTORY>"
]
}
}
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System.ComponentModel;
using ModelContextProtocol.Server;

/// <summary>
/// Sample MCP tools for demonstration purposes.
/// These tools can be invoked by MCP clients to perform various operations.
/// </summary>
internal class RandomNumberTools
{
[McpServerTool(Name = "get_random_number")]
[Description("Generates a random number between the specified minimum and maximum values.")]
public int GetRandomNumber(
[Description("Minimum value (inclusive)")] int min = 0,
[Description("Maximum value (exclusive)")] int max = 100)
{
return Random.Shared.Next(min, max);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.AI.Templates.Tests;
using Microsoft.Extensions.Logging;
using Microsoft.TemplateEngine.Authoring.TemplateVerifier;
using Microsoft.TemplateEngine.TestHelper;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.Extensions.AI.Templates.Tests;

public class McpServerSnapshotTests
{
// Keep the exclude patterns below in sync with those in Microsoft.Extensions.AI.Templates.csproj.
private static readonly string[] _verificationExcludePatterns = [
"**/bin/**",
"**/obj/**",
"**/.vs/**",
"**/*.sln",
"**/*.in",
];

private readonly ILogger _log;

public McpServerSnapshotTests(ITestOutputHelper log)
{
#pragma warning disable CA2000 // Dispose objects before losing scope
_log = new XunitLoggerProvider(log).CreateLogger("TestRun");
#pragma warning restore CA2000 // Dispose objects before losing scope
}

[Fact]
public async Task BasicTest()
{
await TestTemplateCoreAsync(scenarioName: "Basic");
}

private async Task TestTemplateCoreAsync(string scenarioName, IEnumerable<string>? templateArgs = null)
{
string workingDir = TestUtils.CreateTemporaryFolder();
string templateShortName = "mcpserver";

// Get the template location
string templateLocation = Path.Combine(WellKnownPaths.TemplateFeedLocation, "Microsoft.Extensions.AI.Templates", "src", "McpServer");

var verificationExcludePatterns = Path.DirectorySeparatorChar is '/'
? _verificationExcludePatterns
: _verificationExcludePatterns.Select(p => p.Replace('/', Path.DirectorySeparatorChar)).ToArray();

TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: templateShortName)
{
TemplatePath = templateLocation,
TemplateSpecificArgs = templateArgs,
SnapshotsDirectory = "Snapshots",
OutputDirectory = workingDir,
DoNotPrependCallerMethodNameToScenarioName = true,
DoNotAppendTemplateArgsToScenarioName = true,
ScenarioName = scenarioName,
VerificationExcludePatterns = verificationExcludePatterns,
}
.WithCustomScrubbers(
ScrubbersDefinition.Empty.AddScrubber((path, content) =>
{
string filePath = path.UnixifyDirSeparators();

if (filePath.EndsWith(".csproj"))
{
// Scrub references to just-built packages and remove the suffix, if it exists.
// This allows the snapshots to remain the same regardless of where the repo is built (e.g., locally, public CI, internal CI).
var pattern = @"(?<=<PackageReference\s+Include=""Microsoft\.Extensions\..*""\s+Version="")(\d+\.\d+\.\d+)(?:-[^""]*)?(?=""\s*/>)";
content.ScrubByRegex(pattern, replacement: "$1");
}
}));

VerificationEngine engine = new VerificationEngine(_log);
await engine.Execute(options);

#pragma warning disable CA1031 // Do not catch general exception types
try
{
Directory.Delete(workingDir, recursive: true);
}
catch
{
/* don't care */
}
#pragma warning restore CA1031 // Do not catch general exception types
}
}
Loading
Loading