Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
75 changes: 75 additions & 0 deletions src/Nerdbank.GitVersioning.Tasks/StampMcpServerJson.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Nerdbank.GitVersioning.Tasks;

/// <summary>
/// MSBuild task that stamps version information into an MCP server.json file.
/// </summary>
public class StampMcpServerJson : Microsoft.Build.Utilities.Task
{
/// <summary>
/// Gets or sets the path to the source server.json file.
/// </summary>
[Required]
public string SourceServerJson { get; set; }

/// <summary>
/// Gets or sets the path where the stamped server.json file should be written.
/// </summary>
[Required]
public string OutputServerJson { get; set; }

/// <summary>
/// Gets or sets the version to stamp into the server.json file.
/// </summary>
[Required]
public string Version { get; set; }

/// <summary>
/// Executes the task to stamp version information into the MCP server.json file.
/// </summary>
/// <returns><see langword="true"/> if the task succeeded; <see langword="false"/> otherwise.</returns>
public override bool Execute()
{
try
{
if (string.IsNullOrEmpty(this.SourceServerJson) || string.IsNullOrEmpty(this.OutputServerJson) || string.IsNullOrEmpty(this.Version))
{
this.Log.LogError("SourceServerJson, OutputServerJson, and Version are required parameters.");
return !this.Log.HasLoggedErrors;
}

if (!File.Exists(this.SourceServerJson))
{
this.Log.LogError($"Source server.json file not found: {this.SourceServerJson}");
return !this.Log.HasLoggedErrors;
}

// Ensure output directory exists
string outputDir = Path.GetDirectoryName(this.OutputServerJson);
if (!string.IsNullOrEmpty(outputDir))
{
Directory.CreateDirectory(outputDir);
}

// Read the server.json file and replace version placeholders
string jsonContent = File.ReadAllText(this.SourceServerJson);
jsonContent = jsonContent.Replace("\"0.0.0-placeholder\"", $"\"{this.Version}\"");

File.WriteAllText(this.OutputServerJson, jsonContent);
this.Log.LogMessage(MessageImportance.Low, $"Stamped version '{this.Version}' into server.json: {this.OutputServerJson}");
}
catch (Exception ex)
{
this.Log.LogErrorFromException(ex);
}

return !this.Log.HasLoggedErrors;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
<UsingTask AssemblyFile="$(NerdbankGitVersioningTasksPath)Nerdbank.GitVersioning.Tasks.dll" TaskName="Nerdbank.GitVersioning.Tasks.NativeVersionInfo"/>
<UsingTask AssemblyFile="$(NerdbankGitVersioningTasksPath)Nerdbank.GitVersioning.Tasks.dll" TaskName="Nerdbank.GitVersioning.Tasks.SetCloudBuildVariables"/>
<UsingTask AssemblyFile="$(NerdbankGitVersioningTasksPath)Nerdbank.GitVersioning.Tasks.dll" TaskName="Nerdbank.GitVersioning.Tasks.CompareFiles"/>
<UsingTask AssemblyFile="$(NerdbankGitVersioningTasksPath)Nerdbank.GitVersioning.Tasks.dll" TaskName="Nerdbank.GitVersioning.Tasks.StampMcpServerJson"/>

<Target Name="NBGV_SetDefaults">
<!-- Workarounds for https://github.com/dotnet/Nerdbank.GitVersioning/issues/404 -->
Expand Down Expand Up @@ -310,6 +311,34 @@
</PropertyGroup>
</Target>

<!-- Support for MCP servers: stamp version in server.json -->
<Target Name="NBGV_StampMcpServerJson"
Condition="'$(PackageType)' == 'McpServer'"
BeforeTargets="GenerateNuspec;_GetPackageFiles"
DependsOnTargets="GetBuildVersion">
<ItemGroup>
<_NBGV_OriginalServerJson Include="$(MSBuildProjectDirectory)\server.json" Condition="Exists('$(MSBuildProjectDirectory)\server.json')" />
</ItemGroup>

<PropertyGroup>
<_NBGV_StampedServerJsonPath>$(IntermediateOutputPath)server.json</_NBGV_StampedServerJsonPath>
</PropertyGroup>

<!-- Transform server.json with versioned content -->
<Nerdbank.GitVersioning.Tasks.StampMcpServerJson
Condition="'@(_NBGV_OriginalServerJson)' != ''"
SourceServerJson="%(_NBGV_OriginalServerJson.Identity)"
OutputServerJson="$(_NBGV_StampedServerJsonPath)"
Version="$(Version)" />

<!-- Remove original server.json from packaging and add stamped version -->
<ItemGroup Condition="'$(_NBGV_StampedServerJsonPath)' != ''">
<Content Remove="server.json" />
<None Remove="server.json" />
<Content Include="$(_NBGV_StampedServerJsonPath)" PackagePath="server.json" Pack="true" />
</ItemGroup>
</Target>

<!-- Workaround till https://github.com/NuGet/NuGet.Client/issues/1064 is merged and used. -->
<Target Name="_NBGV_CalculateNuSpecVersionHelper"
BeforeTargets="GenerateNuspec"
Expand Down
81 changes: 81 additions & 0 deletions test/Nerdbank.GitVersioning.Tests/BuildIntegrationManagedTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Text.Json.Nodes;
using Microsoft.Build.Construction;
using Microsoft.Build.Framework;
using Nerdbank.GitVersioning;
using Xunit;

Expand All @@ -15,6 +18,84 @@ public BuildIntegrationManagedTests(ITestOutputHelper logger)
{
}

/// <summary>
/// Verifies that MCP server.json files get version stamping when PackageType=McpServer.
/// </summary>
[Fact]
public async Task McpServerJson_VersionStamping()
{
// Create a sample server.json file based on the real MCP server template
string serverJsonContent = /* lang=c#-test */ """
{
"$schema": "https://modelcontextprotocol.io/schemas/draft/2025-07-09/server.json",
"description": "Test .NET MCP Server",
"name": "io.github.test/testmcpserver",
"version": "0.0.0-placeholder",
"packages": [
{
"registry_type": "nuget",
"identifier": "Test.McpServer",
"version": "0.0.0-placeholder",
"transport": {
"type": "stdio"
},
"package_arguments": [],
"environment_variables": []
}
],
"repository": {
"url": "https://github.com/test/testmcpserver",
"source": "github"
}
}
""";

string serverJsonPath = Path.Combine(this.projectDirectory, "server.json");
File.WriteAllText(serverJsonPath, serverJsonContent);

// Set PackageType to McpServer
ProjectPropertyGroupElement propertyGroup = this.testProject.CreatePropertyGroupElement();
this.testProject.AppendChild(propertyGroup);
propertyGroup.AddProperty("PackageType", "McpServer");

this.WriteVersionFile();
BuildResults result = await this.BuildAsync("NBGV_StampMcpServerJson", logVerbosity: LoggerVerbosity.Detailed);

// Verify the build succeeded
Assert.Empty(result.LoggedEvents.OfType<BuildErrorEventArgs>());

// Verify the stamped server.json was created
string stampedServerJsonPath = Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("IntermediateOutputPath"), "server.json");
Assert.True(File.Exists(stampedServerJsonPath), $"Expected stamped server.json at: {stampedServerJsonPath}");

// Verify the version was correctly stamped
string stampedContent = File.ReadAllText(stampedServerJsonPath);
var stampedJson = JsonNode.Parse(stampedContent) as JsonObject;
Assert.NotNull(stampedJson);

string expectedVersion = result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("Version");

// Verify root version was stamped
Assert.Equal(expectedVersion, stampedJson["version"]?.ToString());

// Verify package version was also stamped
JsonArray packages = stampedJson["packages"]?.AsArray();
Assert.NotNull(packages);
Assert.Single(packages);

JsonObject package = packages[0]?.AsObject();
Assert.NotNull(package);
Assert.Equal(expectedVersion, package["version"]?.ToString());

// Verify other properties were preserved
Assert.Equal("io.github.test/testmcpserver", stampedJson["name"]?.ToString());
Assert.Equal("Test .NET MCP Server", stampedJson["description"]?.ToString());
Assert.Equal("Test.McpServer", package["identifier"]?.ToString());

// Verify that no placeholder remain in the entire JSON
Assert.DoesNotContain("0.0.0-placeholder", stampedContent);
}

protected override GitContext CreateGitContext(string path, string committish = null)
=> GitContext.Create(path, committish, GitContext.Engine.ReadOnly);

Expand Down
Loading