Set up package publishing for daily, manual, and release builds (#118)

* Set up a root artifacts folder for all build/test/pack output

Update CI TestResults folder

* Update package Authors and Copyright

* Lower-case extension on README.md

* Move package props to src folder. Use Version prefix and suffix props.

* Set up package publishing for daily, manual, and release builds

* Only run publishing jobs to the modelcontextprotocol/csharp-sdk repo

* Fix condition on docs workflow

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update preview wording in README to apply to the package too

* Verify packaging succeeds in the CI workflow

* Allow a version suffix override in release workflow.

* De-dupe the README between the repo and the NuGet package

* New CI work

* Do not reuse the CI workflow for releases so we can build without tests.

* Add a release process doc

* Fix bug in publishing; needs checkout step. Update comment for publish.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Jeff Handley 2025-03-27 15:08:19 -07:00 • committed by GitHub
commit 259f11af8a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 161 additions and 238 deletions

View file

@ -8,17 +8,17 @@ on:
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
configuration: [Debug, Release]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Clone the repo
uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
@ -29,7 +29,7 @@ jobs:
9.0.x
8.0.x
# Netfx testing on non-Windows requires mono
# NetFX testing on non-Windows requires mono
- name: Setup Mono
if: runner.os == 'Linux'
run: sudo apt-get install -y mono-devel
@ -48,6 +48,9 @@ jobs:
- name: Build
run: dotnet build --configuration ${{ matrix.configuration }}
- name: Pack
run: dotnet pack --configuration ${{ matrix.configuration }}
- name: Test
run: >-
dotnet test

View file

@ -19,6 +19,8 @@ concurrency:
jobs:
publish-docs:
# Only publish from the modelcontextprotocol/csharp-sdk repository
if: ${{ github.repository == 'modelcontextprotocol/csharp-sdk' }}
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

37
.github/workflows/release.md vendored Normal file
View file

@ -0,0 +1,37 @@
# Release Process
The following process is used when publishing new releases to NuGet.org:
1. **Ensure the CI workflow is fully green**
- Some of the integration tests are flaky and require re-running
- Once the state of the branch is known to be good, a release can proceed
- **The release workflow _does not_ run tests**
2. **Create a new Release in GitHub**
- Use the link on the repo home page to [Create a new release](https://github.com/modelcontextprotocol/csharp-sdk/releases/new)
- Click the 'Choose a tag' dropdown button
- Type the name using the `v{major}.{minor}.{patch}-{suffix}` pattern
- Click 'Create new tag: ... on publish'
- Click the 'Target' dropdown button
- Choose the 'Recent Commits' tab
- Select the commit to use for the release, ensuring it's one from above where CI is known to be green
- Click the 'Previous tag' dropdown button
- Choose the previous release to use for generating release notes
- Click the 'Generate release notes button'
- This will add release notes into the Release description
- The generated release notes include what has changed and the list of new contributors
- Verify the Release title
- It will be populated to match the tag name to be created
- This should be retained, using the release title format matching the `v{major}.{minor}.{patch}-{suffix}` format
- Augment the Release description as desired
- This content is presented used on GitHub and is not persisted into any artifacts
- Check the 'Set as a pre-release' button under the release description if appropriate
- Click 'Public release'
3. **Monitor the Release workflow**
- After publishing the release, a workflow will begin for producing the release's build artifacts and publishing the NuGet package to NuGet.org
- If the job fails, troubleshoot and re-run the workflow as needed
- Verify the package version becomes listed on at [https://nuget.org/packages/ModelContextProtocol](https://nuget.org/packages/ModelContextProtocol)
4. **Update the source to increment the version number**
- Immediately after publishing a new release, the [`/src/Directory.Build.Props`](../../src/Directory.Build.props) file needs to be updated to bump the version to the next expected release version

View file

@ -1,20 +1,71 @@
# This workflow is triggered by new releases
# It builds, tests, and publishes to the GitHub NuGet package registry
name: Release package
# Publish new package versions of ModelContextProtocol
#
# Daily and Manual Runs
# - Triggered automatically at 07:00 UTC daily
# - Triggered manually using GitHub Actions workflow_dispatch event
# - Version prefix applied from /src/Directory.Build.props
# - Version suffix set to `ci.{github.run_number}`
# - Package published to GitHub package registry
#
# Official Releases
# - Triggered after a GitHub Release is created
# - Version prefix applied from /src/Directory.Build.props
# - Version suffix applied from /src/Directory.Build.props
# - Package published to GitHub package registry
# - Package published to NuGet.org
# - Version prefix and/or suffix should be updated after each release
name: Release Publishing
on:
schedule:
- cron: '0 7 * * *'
workflow_dispatch:
inputs:
version_suffix_override:
description: Version suffix override
type: string
release:
types: [published]
jobs:
build:
build-all-configs:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
configuration: [Debug, Release]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
- name: Clone the repo
uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Build
run: dotnet build --configuration ${{ matrix.configuration }}
- name: Pack
run: dotnet pack --configuration ${{ matrix.configuration }}
build-package:
runs-on: windows-latest
needs: build-all-configs
env:
version_suffix_args: ${{ github.event_name != 'release' && format('--version-suffix "{0}"', inputs.version_suffix_override || format('ci.{0}', github.run_number)) || '' }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Setup .NET
uses: actions/setup-dotnet@v2
@ -23,25 +74,11 @@ jobs:
9.0.x
8.0.x
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
- name: Install dependencies for tests
run: npm install @modelcontextprotocol/server-everything
- name: Install dependencies for tests
run: npm install @modelcontextprotocol/server-memory
- name: Build
run: dotnet build --configuration Release
- name: Test
run: dotnet test --configuration Release --no-build --filter '(Execution!=Manual)'
- name: Pack
run: dotnet pack --configuration Release --output "${{ github.workspace }}/artifacts/packages"
run: dotnet pack
${{ env.version_suffix_args }}
--configuration Release
--output "${{ github.workspace }}/artifacts/packages"
- name: Upload artifact
uses: actions/upload-artifact@v4
@ -50,20 +87,16 @@ jobs:
name: build-artifacts
path: ${{ github.workspace }}/artifacts
publish:
name: Publish Package
needs: build
publish-package:
needs: build-package
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: |
9.0.x
8.0.x
dotnet-version: 9.0.x
- name: Download build artifacts
uses: actions/download-artifact@v4
@ -75,7 +108,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: NuGet authentication for GitHub
- name: Authenticate to GitHub registry
run: dotnet nuget add source
"https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json"
--name "github"
@ -89,3 +122,12 @@ jobs:
--source "github"
--api-key ${{ secrets.GITHUB_TOKEN }}
--skip-duplicate
- name: Publish to NuGet.org (Releases only)
# Only publish to NuGet.org from the modelcontextprotocol/csharp-sdk repository
if: ${{ github.event_name == 'release' && github.repository == 'modelcontextprotocol/csharp-sdk' }}
run: dotnet nuget push
${{github.workspace}}/build-artifacts/packages/*.nupkg
--source https://api.nuget.org/v3/index.json
--api-key ${{ secrets.NUGET_KEY_MODELCONTEXTPROTOCOL }}
--skip-duplicate

View file

@ -5,15 +5,32 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<PackageVersion>0.1.0-preview</PackageVersion>
<Authors>Microsoft</Authors>
<Copyright>© Microsoft Corporation. All rights reserved.</Copyright>
<RepoRoot>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))</RepoRoot>
<VSTestLogger>trx%3bLogFileName=$(MSBuildProjectName).$(TargetFramework).$(OS).trx</VSTestLogger>
<VSTestResultsDirectory>$(RepoRoot)/artifacts/TestResults</VSTestResultsDirectory>
<WarnOnPackingNonPackableProject>false</WarnOnPackingNonPackableProject>
</PropertyGroup>
<PropertyGroup>
<RepoRoot>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))</RepoRoot>
<ArtifactsDir Condition="'$(ArtifactsDir)' == ''">$([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'artifacts'))</ArtifactsDir>
<ArtifactsObjDir>$([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'obj'))</ArtifactsObjDir>
<ArtifactsBinDir>$([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'bin'))</ArtifactsBinDir>
<ArtifactsTestResultsDir>$([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'TestResults', '$(Configuration)'))</ArtifactsTestResultsDir>
<ArtifactsPackagesDir>$([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'packages', '$(Configuration)'))</ArtifactsPackagesDir>
<OutDirName>$(MSBuildProjectName)</OutDirName>
<BaseIntermediateOutputPath>$([System.IO.Path]::GetFullPath('$(ArtifactsObjDir)$(OutDirName)\'))</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
<BaseOutputPath>$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)$(OutDirName)\'))</BaseOutputPath>
<OutputPath>$(BaseOutputPath)$(Configuration)\</OutputPath>
<PackageOutputPath>$(ArtifactsPackagesDir)</PackageOutputPath>
</PropertyGroup>
<PropertyGroup>
<VSTestLogger Condition="'$(VSTestLogger)' == ''">trx%3bLogFileName=$(MSBuildProjectName).$(TargetFramework).$(OS).trx</VSTestLogger>
<VSTestResultsDirectory Condition="'$(VSTestResultsDirectory)' == ''">$(ArtifactsTestResultsDir)</VSTestResultsDirectory>
</PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>

View file

@ -1,9 +1,11 @@
# MCP C# SDK
The official C# SDK for the [Model Context Protocol](https://modelcontextprotocol.io/), enabling .NET applications to connect to and interact with MCP clients and servers.
[![NuGet preview version](https://img.shields.io/nuget/vpre/ModelContextProtocol.svg)](https://www.nuget.org/packages/ModelContextProtocol/absoluteLatest)
The official C# SDK for the [Model Context Protocol](https://modelcontextprotocol.io/), enabling .NET applications, services, and libraries to implement and interact with MCP clients and servers. Please visit our [API documentation](https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.html) for more details on available functionality.
> [!NOTE]
> This repo is still in preview, breaking changes can be introduced without prior notice.
> This project is in preview; breaking changes can be introduced without prior notice.
## About MCP
@ -15,17 +17,21 @@ For more information about MCP:
- [Protocol Specification](https://spec.modelcontextprotocol.io/)
- [GitHub Organization](https://github.com/modelcontextprotocol)
## Installation
To get started, install the package from NuGet
```
dotnet add package ModelContextProtocol --prerelease
```
## Getting Started (Client)
Then create a client and start using tools, or other capabilities, from the servers you configure:
To get started writing a client, the `McpClientFactory.CreateAsync` method is used to instantiate and connect an `IMcpClient`
to a server. Once you have an `IMcpClient`, you can interact with it, such as to enumerate all available tools and invoke tools.
```csharp
McpClientOptions options = new()
{
ClientInfo = new() { Name = "TestClient", Version = "1.0.0" }
};
McpServerConfig config = new()
var client = await McpClientFactory.CreateAsync(new()
{
Id = "everything",
Name = "Everything",
@ -35,9 +41,7 @@ McpServerConfig config = new()
["command"] = "npx",
["arguments"] = "-y @modelcontextprotocol/server-everything",
}
};
var client = await McpClientFactory.CreateAsync(config, options);
});
// Print the list of tools available from the server.
await foreach (var tool in client.ListToolsAsync())
@ -48,37 +52,28 @@ await foreach (var tool in client.ListToolsAsync())
// Execute a tool (this would normally be driven by LLM tool invocations).
var result = await client.CallToolAsync(
"echo",
new() { ["message"] = "Hello MCP!" },
new Dictionary<string, object?>() { ["message"] = "Hello MCP!" },
CancellationToken.None);
// echo always returns one and only one text content object
Console.WriteLine(result.Content.First(c => c.Type == "text").Text);
```
Note that you should pass CancellationToken objects suitable for your use case, to enable proper error handling, timeouts, etc. This example also does not paginate the tools list, which may be necessary for large tool sets. See the IntegrationTests project for an example of pagination, as well as examples of how to handle Prompts and Resources.
You can find samples demonstrating how to use ModelContextProtocol with an LLM SDK in the [samples](samples) directory, and also refer to the [tests](tests/ModelContextProtocol.Tests) project for more examples. Additional examples and documentation will be added as in the near future.
It is also highly recommended that you pass a proper LoggerFactory instance to the factory constructor, to enable logging of MCP client operations.
You can find samples demonstrating how to use ModelContextProtocol with an LLM SDK in the [samples](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples) directory, and also refer to the [tests](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/tests/ModelContextProtocol.Tests) project for more examples.
Additional examples and documentation will be added as in the near future.
Remember you can connect to any MCP server, not just ones created using ModelContextProtocol. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server.
Clients can connect to any MCP server, not just ones created using this library. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server.
Tools can be exposed easily as `AIFunction` instances so that they are immediately usable with `IChatClient`s.
```csharp
// Get available functions.
IList<AIFunction> tools = await client.GetAIFunctionsAsync();
IList<McpClientTool> tools = await client.ListToolsAsync();
// Call the chat client using the tools.
IChatClient chatClient = ...;
var response = await chatClient.GetResponseAsync(
"your prompt here",
new()
{
Tools = [.. tools],
});
new() { Tools = [.. tools] },
```
## Getting Started (Server)
@ -98,17 +93,47 @@ var builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithTools();
.WithToolsFromAssembly();
await builder.Build().RunAsync();
[McpServerToolType]
public static class EchoTool
{
[McpTool, Description("Echoes the message back to the client.")]
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"hello {message}";
}
```
Tools can have the `IMcpServer` representing the server injected via a parameter to the method, and can use that for interaction with
the connected client. Similarly, arguments may be injected via dependency injection. For example, this tool will use the supplied
`IMcpServer` to make sampling requests back to the client in order to summarize content it downloads from the specified url via
an `HttpClient` injected via dependency injection.
```csharp
[McpServerTool("SummarizeContentFromUrl"), Description("Summarizes content downloaded from a specific URI")]
public static async Task<string> SummarizeDownloadedContent(
IMcpServer thisServer,
HttpClient httpClient,
[Description("The url from which to download the content to summarize")] string url,
CancellationToken cancellationToken)
{
string content = await httpClient.GetStringAsync(url);
ChatMessage[] messages =
[
new(ChatRole.User, "Briefly summarize the following downloaded content:"),
new(ChatRole.User, content),
]
ChatOptions options = new()
{
MaxOutputTokens = 256,
Temperature = 0.3f,
};
return $"Summary: {await thisServer.AsSamplingChatClient().GetResponseAsync(messages, options, cancellationToken)}";
}
```
More control is also available, with fine-grained control over configuring the server and how it should handle client requests. For example:
```csharp
@ -134,14 +159,18 @@ McpServerOptions options = new()
{
Name = "echo",
Description = "Echoes the input back to the client.",
InputSchema = new JsonSchema()
InputSchema = JsonSerializer.Deserialize<JsonElement>("""
{
Type = "object",
Properties = new Dictionary<string, JsonSchemaProperty>()
{
["message"] = new JsonSchemaProperty() { Type = "string", Description = "The input to echo back." }
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The input to echo back"
}
},
"required": ["message"]
}
"""),
}
]
};
@ -176,6 +205,10 @@ await server.StartAsync();
await Task.Delay(Timeout.Infinite);
```
## Acknowledgements
The starting point for this library was a project called [mcpdotnet](https://github.com/PederHP/mcpdotnet), initiated by [Peder Holdgaard Pederson](https://github.com/PederHP). We are grateful for the work done by Peder and other contributors to that repository, which created a solid foundation for this library.
## License
This project is licensed under the [MIT License](https://github.com/modelcontextprotocol/csharp-sdk/blob/main/LICENSE).
This project is licensed under the [MIT License](LICENSE).

View file

@ -5,12 +5,15 @@
<PackageProjectUrl>https://github.com/modelcontextprotocol/csharp-sdk</PackageProjectUrl>
<RepositoryUrl>https://github.com/modelcontextprotocol/csharp-sdk</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<VersionPrefix>0.1.0</VersionPrefix>
<VersionSuffix>preview.2</VersionSuffix>
<Authors>ModelContextProtocolOfficial</Authors>
<Copyright>© Anthropic and Contributors.</Copyright>
<PackageTags>ModelContextProtocol;mcp;ai;llm</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageIcon>logo.png</PackageIcon>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageOutputPath>$(RepoRoot)artifacts/</PackageOutputPath>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AssemblyOriginatorKeyFile>$(RepoRoot)\Open.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>

View file

@ -29,7 +29,7 @@
</ItemGroup>
<ItemGroup>
<None Include="README.md" pack="true" PackagePath="." />
<None Include="..\..\README.md" pack="true" PackagePath="\" />
</ItemGroup>
</Project>

View file

@ -40,10 +40,10 @@
</ItemGroup>
<ItemGroup>
<Content Condition="$([MSBuild]::IsOSPlatform('Windows'))" Include="..\ModelContextProtocol.TestServer\bin\$(Configuration)\net8.0\TestServer.exe">
<Content Condition="$([MSBuild]::IsOSPlatform('Windows'))" Include="$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)ModelContextProtocol.TestServer\$(Configuration)'))\$(TargetFramework)\TestServer.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Condition="$([MSBuild]::IsOSPlatform('Linux'))" Include="..\ModelContextProtocol.TestServer\bin\$(Configuration)\net8.0\TestServer.dll">
<Content Condition="$([MSBuild]::IsOSPlatform('Linux'))" Include="$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)ModelContextProtocol.TestServer\$(Configuration)'))\$(TargetFramework)\TestServer.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>