Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
158 changes: 158 additions & 0 deletions src/Nerdbank.GitVersioning.Tasks/StampMcpServerJson.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// 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 System.Text.Json;
using System.Text.Json.Nodes;
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 and parse the server.json file
string jsonContent = File.ReadAllText(this.SourceServerJson);
JsonNode jsonNode = JsonNode.Parse(jsonContent);

if (jsonNode is JsonObject jsonObject)
{
// Replace all __VERSION__ placeholders in the JSON tree
this.ReplaceVersionPlaceholders(jsonNode, this.Version);

// Write the updated JSON with indentation for readability
var options = new JsonSerializerOptions
{
WriteIndented = true,
};

string updatedJson = JsonSerializer.Serialize(jsonObject, options);
File.WriteAllText(this.OutputServerJson, updatedJson);

this.Log.LogMessage(MessageImportance.Low, $"Stamped version '{this.Version}' into server.json: {this.OutputServerJson}");
}
else
{
this.Log.LogError($"server.json does not contain a valid JSON object: {this.SourceServerJson}");
}
}
catch (Exception ex)
{
this.Log.LogErrorFromException(ex);
}

return !this.Log.HasLoggedErrors;
}

/// <summary>
/// Recursively walks the JSON tree and replaces any string values containing "__VERSION__" with the actual version.
/// </summary>
/// <param name="node">The JSON node to process.</param>
/// <param name="version">The version string to replace "__VERSION__" with.</param>
private void ReplaceVersionPlaceholders(JsonNode node, string version)
{
switch (node)
{
case JsonObject jsonObject:
foreach (var property in jsonObject.ToArray())
{
if (property.Value != null)
{
this.ReplaceVersionPlaceholders(property.Value, version);
}
}
break;

case JsonArray jsonArray:
for (int i = 0; i < jsonArray.Count; i++)
{
if (jsonArray[i] != null)
{
this.ReplaceVersionPlaceholders(jsonArray[i], version);
}
}
break;

case JsonValue jsonValue:
if (jsonValue.TryGetValue<string>(out string stringValue) && stringValue.Contains("__VERSION__"))
{
string replacedValue = stringValue.Replace("__VERSION__", version);
JsonNode parent = jsonValue.Parent;
if (parent is JsonObject parentObject)
{
// Find the property key for this value
foreach (var kvp in parentObject)
{
if (ReferenceEquals(kvp.Value, jsonValue))
{
parentObject[kvp.Key] = replacedValue;
break;
}
}
}
else if (parent is JsonArray parentArray)
{
// Find the index for this value
for (int i = 0; i < parentArray.Count; i++)
{
if (ReferenceEquals(parentArray[i], jsonValue))
{
parentArray[i] = replacedValue;
break;
}
}
}
}
break;
}
}
}
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
79 changes: 79 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,82 @@ 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 = @"{
""$schema"": ""https://modelcontextprotocol.io/schemas/draft/2025-07-09/server.json"",
""description"": ""Test .NET MCP Server"",
""name"": ""io.github.test/testmcpserver"",
""version"": ""__VERSION__"",
""packages"": [
{
""registry_type"": ""nuget"",
""identifier"": ""Test.McpServer"",
""version"": ""__VERSION__"",
""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 __VERSION__ placeholders remain in the entire JSON
Assert.DoesNotContain("__VERSION__", stampedContent);
}

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

Expand Down
1 change: 1 addition & 0 deletions test/Nerdbank.GitVersioning.Tests/BuildIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.Json.Nodes;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
Expand Down
Loading