From 970d039323120eed4731ddc7702bba24f9dced0d Mon Sep 17 00:00:00 2001 From: Jon Galloway Date: Wed, 4 Nov 2026 23:27:06 -0800 Subject: [PATCH] Support bounded .NET 11 SDK feature set Add solution filters, Run environment variables, Format framework selection, prerelease template installs, and SDK-aware test runner detection. Preserve existing defaults and document verified RC3 behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Scenarios/Sdk11FeatureScenarioTests.cs | 91 ++++ DotNetMcp.Tests/Server/ToolAnnotationTests.cs | 13 + DotNetMcp.Tests/Tools/Sdk11FeatureTests.cs | 418 ++++++++++++++++++ DotNetMcp/Execution/CommandLineArgument.cs | 27 ++ DotNetMcp/Execution/DotNetCommandExecutor.cs | 3 + DotNetMcp/Execution/SdkFeatureSupport.cs | 30 ++ .../SdkIntegration/TestRunnerDetector.cs | 22 +- DotNetMcp/Tools/Cli/DotNetCliTools.Misc.cs | 10 +- .../DotNetCliTools.Project.Consolidated.cs | 111 ++++- .../Tools/Cli/DotNetCliTools.Solution.cs | 165 ++++++- .../Sdk/DotNetCliTools.Sdk.Consolidated.cs | 25 +- README.md | 51 ++- doc/ai-assistant-guide.md | 20 +- doc/error-diagnostics.md | 6 + doc/sdk-integration.md | 16 + 15 files changed, 953 insertions(+), 55 deletions(-) create mode 100644 DotNetMcp.Tests/Scenarios/Sdk11FeatureScenarioTests.cs create mode 100644 DotNetMcp.Tests/Tools/Sdk11FeatureTests.cs create mode 100644 DotNetMcp/Execution/CommandLineArgument.cs create mode 100644 DotNetMcp/Execution/SdkFeatureSupport.cs diff --git a/DotNetMcp.Tests/Scenarios/Sdk11FeatureScenarioTests.cs b/DotNetMcp.Tests/Scenarios/Sdk11FeatureScenarioTests.cs new file mode 100644 index 00000000..4522455d --- /dev/null +++ b/DotNetMcp.Tests/Scenarios/Sdk11FeatureScenarioTests.cs @@ -0,0 +1,91 @@ +using System.Text.Json; + +namespace DotNetMcp.Tests.Scenarios; + +public sealed class Sdk11FeatureScenarioTests(ITestOutputHelper output) +{ + [ScenarioFact] + public async Task NewTestTemplates_ExposeMtpOptionsThroughMcp() + { + using var root = await Sdk11FeatureTests.CreateFixtureAsync(); + await using var client = await McpScenarioClient.CreateAsync(TestContext.Current.CancellationToken, output); + foreach (var (template, options, expectedPackage) in new[] + { + ("xunit", "--xunit-version v3 --no-restore", "xunit.v3"), + ("nunit", "--test-runner Microsoft.Testing.Platform --no-restore", "NUnit3TestAdapter") + }) + { + var destination = Path.Join(root.Path, template); + var result = await client.CallToolAsync("dotnet_project", new() + { + ["action"] = "New", ["template"] = template, ["name"] = "GeneratedTests", + ["output"] = destination, ["framework"] = "net11.0", ["additionalOptions"] = options, + ["workingDirectory"] = root.Path + }, TestContext.Current.CancellationToken); + Assert.True(result.IsError != true, result.GetText()); + var project = await File.ReadAllTextAsync(Path.Join(destination, "GeneratedTests.csproj"), TestContext.Current.CancellationToken); + Assert.Contains(expectedPackage, project); + Assert.Contains("TestingPlatform", project); + using var global = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Join(root.Path, "global.json"), TestContext.Current.CancellationToken)); + Assert.Equal("Microsoft.Testing.Platform", global.RootElement.GetProperty("test").GetProperty("runner").GetString()); + } + } + + [ScenarioFact] + public async Task RunEnvironment_IsAcceptedByStdioSchemaAndReachesApp() + { + using var root = await Sdk11FeatureTests.CreateFixtureAsync(); + var project = await Sdk11FeatureTests.WriteConsoleAsync(root.Path, + """Console.WriteLine("MCP_ENV:" + Environment.GetEnvironmentVariable("MCP_FIXTURE"));"""); + await using var client = await McpScenarioClient.CreateAsync(TestContext.Current.CancellationToken, output); + var result = await client.CallToolAsync("dotnet_project", new() + { + ["action"] = "Run", ["project"] = project, ["workingDirectory"] = root.Path, + ["environmentVariables"] = new Dictionary { ["MCP_FIXTURE"] = "space = \"quote\"" } + }, TestContext.Current.CancellationToken); + Assert.True(result.IsError != true, result.GetText()); + Assert.Contains("MCP_ENV:space = \"quote\"", result.GetText()); + Assert.NotNull(result.StructuredContent); + var tools = await client.Client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken); + var environment = tools.Single(tool => tool.Name == "dotnet_project").ProtocolTool.InputSchema + .GetProperty("properties").GetProperty("environmentVariables"); + Assert.Contains("string", environment.GetRawText()); + } + + [ScenarioFact] + public async Task SolutionFilter_CreateAndMembershipRoundTripThroughStdio() + { + using var root = await Sdk11FeatureTests.CreateFixtureAsync(); + var project = await Sdk11FeatureTests.WriteConsoleAsync(root.Path); + var parent = Path.Join(root.Path, "Parent.slnx"); + var filterDirectory = Directory.CreateDirectory(Path.Join(root.Path, "filters")).FullName; + var filter = Path.Join(filterDirectory, "Subset.slnf"); + await using var client = await McpScenarioClient.CreateAsync(TestContext.Current.CancellationToken, output); + foreach (var args in new Dictionary[] + { + new() { ["action"] = "Create", ["name"] = "Parent", ["output"] = root.Path, ["format"] = "slnx" }, + new() { ["action"] = "Add", ["solution"] = parent, ["projects"] = new[] { project } }, + new() { ["action"] = "Create", ["name"] = "Subset", ["output"] = filterDirectory, + ["format"] = "slnf", ["parentSolution"] = Path.Join("..", "Parent.slnx") }, + new() { ["action"] = "Add", ["solution"] = filter, ["projects"] = new[] { project } } + }) + { + var result = await client.CallToolAsync("dotnet_solution", args, TestContext.Current.CancellationToken); + Assert.True(result.IsError != true, result.GetText()); + } + var listed = await client.CallToolAsync("dotnet_solution", new() + { + ["action"] = "List", ["solution"] = filter + }, TestContext.Current.CancellationToken); + Assert.True(listed.IsError != true, listed.GetText()); + Assert.Contains("App.csproj", listed.GetText()); + Assert.NotNull(listed.StructuredContent); + var removed = await client.CallToolAsync("dotnet_solution", new() + { + ["action"] = "Remove", ["solution"] = filter, ["projects"] = new[] { project } + }, TestContext.Current.CancellationToken); + Assert.True(removed.IsError != true, removed.GetText()); + using var content = JsonDocument.Parse(await File.ReadAllTextAsync(filter, TestContext.Current.CancellationToken)); + Assert.Empty(content.RootElement.GetProperty("solution").GetProperty("projects").EnumerateArray()); + } +} diff --git a/DotNetMcp.Tests/Server/ToolAnnotationTests.cs b/DotNetMcp.Tests/Server/ToolAnnotationTests.cs index 747ee793..457c5f90 100644 --- a/DotNetMcp.Tests/Server/ToolAnnotationTests.cs +++ b/DotNetMcp.Tests/Server/ToolAnnotationTests.cs @@ -33,6 +33,19 @@ public async Task Discovery_ExplicitHintsCoverEveryProductionTool(string protoco var expectedNames = OpenWorldTools.Concat(readOnlyTools).Append("dotnet_server_metrics").Order().ToArray(); Assert.Equal(expectedNames, tools.Select(tool => tool.Name).Order().ToArray()); + foreach (var (name, parameter) in new[] + { + ("dotnet_project", "environmentVariables"), + ("dotnet_solution", "parentSolution"), + ("dotnet_sdk", "prerelease") + }) + { + var tool = tools.Single(tool => tool.Name == name).ProtocolTool; + Assert.True(tool.InputSchema.GetProperty("properties").TryGetProperty(parameter, out var schema)); + Assert.False(string.IsNullOrWhiteSpace(schema.GetProperty("description").GetString())); + Assert.DoesNotContain(parameter, tool.InputSchema.GetProperty("required").EnumerateArray().Select(value => value.GetString())); + } + foreach (var tool in tools) { var json = JsonSerializer.SerializeToElement(tool.ProtocolTool, McpJsonUtilities.DefaultOptions); diff --git a/DotNetMcp.Tests/Tools/Sdk11FeatureTests.cs b/DotNetMcp.Tests/Tools/Sdk11FeatureTests.cs new file mode 100644 index 00000000..87a512c5 --- /dev/null +++ b/DotNetMcp.Tests/Tools/Sdk11FeatureTests.cs @@ -0,0 +1,418 @@ +using System.Diagnostics; +using System.IO.Compression; +using System.Text.Json; +using DotNetMcp.Actions; +using DotNetMcp.SdkIntegration; +using DotNetMcp.Tests.Scenarios; +using Microsoft.Extensions.Logging.Abstractions; + +namespace DotNetMcp.Tests; + +[Collection("ProcessWideStateTests")] +public sealed class Sdk11FeatureTests +{ + private static DotNetCliTools CreateTools(ProcessSessionManager? sessions = null) + => new(NullLogger.Instance, new ConcurrencyManager(), sessions ?? new ProcessSessionManager()); + + [Theory] + [InlineData("Microsoft.Testing.Platform", TestRunner.MicrosoftTestingPlatform)] + [InlineData("mIcRoSoFt.TeStInG.pLaTfOrM", TestRunner.MicrosoftTestingPlatform)] + [InlineData("VSTest", TestRunner.VSTest)] + [InlineData("vstest", TestRunner.VSTest)] + public async Task EnvironmentRunner_OverridesGlobalJsonOnlyOnSupportedSdk(string value, TestRunner expected) + { + using var root = await CreateFixtureAsync(); + await File.WriteAllTextAsync(Path.Join(root.Path, "global.json"), """{"test":{"runner":"Microsoft.Testing.Platform"}}""", TestContext.Current.CancellationToken); + var previous = Environment.GetEnvironmentVariable("DOTNET_TEST_RUNNER"); + try + { + Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", value); + Assert.Equal((expected, "DOTNET_TEST_RUNNER"), TestRunnerDetector.DetectTestRunner(root.Path)); + Assert.Equal((TestRunner.MicrosoftTestingPlatform, "global.json"), + TestRunnerDetector.DetectTestRunner(root.Path, supportsEnvironmentRunner: false)); + } + finally { Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", previous); } + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("unknown")] + [InlineData(" VSTest ")] + public async Task EnvironmentRunner_UnrecognizedValueFallsThrough(string? value) + { + using var root = await CreateFixtureAsync(); + await File.WriteAllTextAsync(Path.Join(root.Path, "global.json"), """{"test":{"runner":"Microsoft.Testing.Platform"}}""", TestContext.Current.CancellationToken); + var previous = Environment.GetEnvironmentVariable("DOTNET_TEST_RUNNER"); + try + { + Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", value); + Assert.Equal((TestRunner.MicrosoftTestingPlatform, "global.json"), TestRunnerDetector.DetectTestRunner(root.Path)); + } + finally { Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", previous); } + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("KEY=VALUE")] + [InlineData("KEY\n")] + public async Task Run_InvalidEnvironmentNameIsAnApplicationError(string name) + { + foreach (var mode in new[] { StartMode.Foreground, StartMode.Background }) + { + var result = await CreateTools().DotnetProject(DotnetProjectAction.Run, startMode: mode, + environmentVariables: new() { [name] = "value" }); + Assert.True(result.IsError); + Assert.Contains("environmentVariables", result.GetText()); + } + } + + [Fact] + public async Task NewParameters_RejectIrrelevantActionsAndInvalidValues() + { + var tools = CreateTools(); + Assert.True((await tools.DotnetProject(DotnetProjectAction.Build, environmentVariables: new())).IsError); + Assert.True((await tools.DotnetSdk(DotnetSdkAction.Version, prerelease: true)).IsError); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.List, parentSolution: "Parent.slnx")).IsError); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Create, name: "Filter", format: "slnf")).IsError); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Create, name: "Filter", format: "slnf", + parentSolution: "Other.slnf")).IsError); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Create, name: "Filter", + parentSolution: "Parent.slnx")).IsError); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Analyze, solution: "Filter.slnf")).IsError); + Assert.True((await tools.DotnetProject(DotnetProjectAction.Format, framework: "invalid")).IsError); + Assert.True((await tools.DotnetProject(DotnetProjectAction.Run, + environmentVariables: new() { ["KEY"] = "bad\nvalue" })).IsError); + } + + [Fact] + public void RunArguments_EscapeEnvironmentBeforeApplicationArguments() + { + var arguments = DotNetCliTools.BuildRunArguments(null, null, "--sample", true, + new() { ["EMPTY"] = "", ["TEXT"] = "a=b \"quoted\" C:\\path\\" }).ToString(); + var parsed = new ProcessStartInfo("dotnet") { Arguments = arguments }; + Assert.Contains("--environment \"EMPTY=\"", parsed.Arguments); + Assert.Contains("--environment \"TEXT=a=b \\\"quoted\\\" C:\\path\\\\\"", parsed.Arguments); + Assert.EndsWith(" -- --sample", arguments); + } + + [Fact] + public async Task SolutionFilter_RealMembershipAndStructuredList() + { + using var root = await CreateFixtureAsync(); + var tools = CreateTools(); + var parent = Path.Join(root.Path, "Parent solution.slnx"); + var project = await WriteConsoleAsync(root.Path); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Create, name: "Parent solution", + output: root.Path, format: "slnx")).IsError != true); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Add, solution: parent, projects: [project])).IsError != true); + var filters = Directory.CreateDirectory(Path.Join(root.Path, "filters")).FullName; + var filter = Path.Join(filters, "Selected projects.slnf"); + var created = await tools.DotnetSolution(DotnetSolutionAction.Create, name: "Selected projects", + output: filters, format: "slnf", parentSolution: Path.Join("..", "Parent solution.slnx")); + Assert.True(created.IsError != true, created.GetText()); + using (var json = JsonDocument.Parse(await File.ReadAllTextAsync(filter, TestContext.Current.CancellationToken))) + Assert.EndsWith("Parent solution.slnx", json.RootElement.GetProperty("solution").GetProperty("path").GetString()); + var added = await tools.DotnetSolution(DotnetSolutionAction.Add, solution: filter, projects: [project]); + Assert.True(added.IsError != true, added.GetText()); + var listed = await tools.DotnetSolution(DotnetSolutionAction.List, solution: filter); + Assert.True(listed.IsError != true, listed.GetText()); + Assert.NotNull(listed.StructuredContent); + Assert.Contains("App.csproj", listed.GetText()); + var removed = await tools.DotnetSolution(DotnetSolutionAction.Remove, solution: filter, projects: [project]); + Assert.True(removed.IsError != true, removed.GetText()); + using var after = JsonDocument.Parse(await File.ReadAllTextAsync(filter, TestContext.Current.CancellationToken)); + Assert.True(after.RootElement.GetProperty("solution").GetProperty("projects").GetArrayLength() == 0, + removed.GetText() + "\n" + after.RootElement.GetRawText()); + } + + [Fact] + public async Task SolutionFilter_InvalidRemovalIsUnchangedAndSuccessfulRemovalPreservesMetadata() + { + using var root = await CreateFixtureAsync(); + var tools = CreateTools(); + var parent = Path.Join(root.Path, "Parent.slnx"); + await File.WriteAllTextAsync(parent, "", TestContext.Current.CancellationToken); + var filter = Path.Join(root.Path, "Subset.slnf"); + const string original = """ + {"custom":"preserve","solution":{"path":"Parent.slnx","custom":42,"projects":["App.csproj"]}} + """; + await File.WriteAllTextAsync(filter, original, TestContext.Current.CancellationToken); + var invalid = await tools.DotnetSolution(DotnetSolutionAction.Remove, solution: filter, + projects: [Path.Join(root.Path, "App.csproj"), Path.Join(root.Path, "Missing.csproj")]); + Assert.True(invalid.IsError); + Assert.Equal(original, await File.ReadAllTextAsync(filter, TestContext.Current.CancellationToken)); + var valid = await tools.DotnetSolution(DotnetSolutionAction.Remove, solution: filter, + projects: [Path.Join(root.Path, "App.csproj")]); + Assert.True(valid.IsError != true, valid.GetText()); + using var json = JsonDocument.Parse(await File.ReadAllTextAsync(filter, TestContext.Current.CancellationToken)); + Assert.Equal("preserve", json.RootElement.GetProperty("custom").GetString()); + Assert.Equal(42, json.RootElement.GetProperty("solution").GetProperty("custom").GetInt32()); + Assert.Empty(Directory.GetFiles(root.Path, "*.tmp")); + Assert.True((await tools.DotnetSolution(DotnetSolutionAction.Create, name: "Broken", output: root.Path, + format: "slnf", parentSolution: "Missing.slnx")).IsError); + Assert.False(File.Exists(Path.Join(root.Path, "Broken.slnf"))); + } + + [Fact] + public async Task RunEnvironment_ReachesForegroundAndBackgroundAppWithoutChangingServer() + { + using var root = await CreateFixtureAsync(); + var project = await WriteConsoleAsync(root.Path, """ + Console.WriteLine("TEXT:" + Environment.GetEnvironmentVariable("MCP_FIXTURE_TEXT")); + Console.WriteLine("EMPTY:" + Environment.GetEnvironmentVariable("MCP_FIXTURE_EMPTY")); + Console.WriteLine("ARG:" + args[0]); + if (args.Length > 1) await Task.Delay(TimeSpan.FromMinutes(1)); + """); + var variables = new Dictionary { ["MCP_FIXTURE_TEXT"] = "a=b \"quoted\" C:\\path\\", ["MCP_FIXTURE_EMPTY"] = "" }; + var previous = Environment.GetEnvironmentVariable("MCP_FIXTURE_TEXT"); + var sessions = new ProcessSessionManager(); + var tools = CreateTools(sessions); + try + { + var foreground = await tools.DotnetProject(DotnetProjectAction.Run, project: project, + workingDirectory: root.Path, appArgs: "sample", environmentVariables: variables); + Assert.True(foreground.IsError != true, foreground.GetText()); + Assert.Contains("TEXT:" + variables["MCP_FIXTURE_TEXT"], foreground.GetText()); + Assert.Contains("ARG:sample", foreground.GetText()); + var background = await tools.DotnetProject(DotnetProjectAction.Run, project: project, + workingDirectory: root.Path, noBuild: true, appArgs: "sample wait", startMode: StartMode.Background, + environmentVariables: variables); + Assert.True(background.IsError != true, background.GetText()); + var id = background.GetText().Split('\n').Single(line => line.StartsWith("Session ID:")).Split(':')[1].Trim(); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + deadline.CancelAfter(TimeSpan.FromSeconds(20)); + while (true) + { + var logs = (await tools.DotnetProject(DotnetProjectAction.Logs, sessionId: id)).GetText(); + if (logs.Contains("TEXT:" + variables["MCP_FIXTURE_TEXT"], StringComparison.Ordinal) + && logs.Contains("ARG:sample", StringComparison.Ordinal)) + break; + await Task.Delay(100, deadline.Token); + } + Assert.True((await tools.DotnetProject(DotnetProjectAction.Stop, sessionId: id)).IsError != true); + Assert.Equal(previous, Environment.GetEnvironmentVariable("MCP_FIXTURE_TEXT")); + } + finally { sessions.Clear(); } + } + + [Fact] + public async Task FormatFramework_LoadsOnlySelectedTarget() + { + using var root = await CreateFixtureAsync(); + var project = await WriteConsoleAsync(root.Path, "Console.WriteLine( \"ok\" );"); + var xml = await File.ReadAllTextAsync(project, TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(project, xml.Replace("net10.0", + "net10.0;net11.0").Replace("", """ + + + + """), TestContext.Current.CancellationToken); + var otherTarget = Path.Join(root.Path, "OnlyNet11.cs"); + const string unformatted = "class OnlyNet11 { public int Value=> 42; }"; + await File.WriteAllTextAsync(otherTarget, unformatted, TestContext.Current.CancellationToken); + var result = await CreateTools().DotnetProject(DotnetProjectAction.Format, project: project, + workingDirectory: root.Path, framework: "net10.0"); + Assert.True(result.IsError != true, result.GetText()); + Assert.Contains("--framework net10.0", result.GetText()); + Assert.DoesNotContain(" ", await File.ReadAllTextAsync(Path.Join(root.Path, "Program.cs"), TestContext.Current.CancellationToken)); + Assert.Equal(unformatted, await File.ReadAllTextAsync(otherTarget, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task PrereleaseTemplates_SelectLatestAndPreserveExplicitVersion() + { + using var root = await CreateFixtureAsync(); + var feed = Directory.CreateDirectory(Path.Join(root.Path, "feed")).FullName; + var id = "Mcp.Feature.Templates." + Guid.NewGuid().ToString("N"); + foreach (var version in new[] { "1.0.0", "2.0.0-preview.1" }) + { + using var archive = ZipFile.Open(Path.Join(feed, $"{id}.{version}.nupkg"), ZipArchiveMode.Create); + WriteEntry(archive, $"{id}.nuspec", $""" + {id}{version}Test + Local template fixture + + """); + WriteEntry(archive, "content/.template.config/template.json", $$""" + {"$schema":"http://json.schemastore.org/template","author":"Test","identity":"{{id}}", + "name":"Feature fixture","shortName":"{{id}}","sourceName":"Fixture"} + """); + WriteEntry(archive, "content/version.txt", version); + } + var tools = CreateTools(); + try + { + foreach (var (prerelease, explicitVersion, expected) in new[] + { + (false, (string?)null, "1.0.0"), + (true, (string?)null, "2.0.0-preview.1"), + (true, (string?)"1.0.0", "1.0.0") + }) + { + var result = await tools.DotnetSdk(DotnetSdkAction.InstallTemplatePack, templatePackage: id, + templateVersion: explicitVersion, nugetSource: feed, workingDirectory: root.Path, prerelease: prerelease); + Assert.True(result.IsError != true, result.GetText()); + Assert.Contains(expected, result.GetText()); + var output = Path.Join(root.Path, expected + (prerelease ? "-preview" : "-stable")); + var generated = await ScenarioHelpers.RunDotNetAsync( + $"new {id} -o {CommandLineArgument.Quote(output)} --no-update-check", root.Path, TestContext.Current.CancellationToken); + Assert.Equal(0, generated.exitCode); + Assert.Equal(expected, await File.ReadAllTextAsync(Path.Join(output, "version.txt"), TestContext.Current.CancellationToken)); + Assert.True((await tools.DotnetSdk(DotnetSdkAction.UninstallTemplatePack, templatePackage: id, + workingDirectory: root.Path)).IsError != true); + } + } + finally + { + await tools.DotnetSdk(DotnetSdkAction.UninstallTemplatePack, templatePackage: id, workingDirectory: root.Path); + } + } + + [Fact] + public async Task OlderSdk_RejectsNewOptInsAndIgnoresEnvironmentRunner() + { + var installed = await ScenarioHelpers.RunDotNetAsync("--list-sdks", AppContext.BaseDirectory, TestContext.Current.CancellationToken); + var sdk10 = installed.stdout.Split('\n').LastOrDefault(line => line.StartsWith("10.", StringComparison.Ordinal))?.Split(' ')[0]; + if (sdk10 is null) Assert.Skip("Requires an installed .NET 10 SDK."); + using var root = await CreateFixtureAsync(sdk10); + var project = await WriteConsoleAsync(root.Path); + var tools = CreateTools(); + foreach (var result in new[] + { + await tools.DotnetProject(DotnetProjectAction.Run, project: project, workingDirectory: root.Path, + environmentVariables: new() { ["KEY"] = "value" }), + await tools.DotnetProject(DotnetProjectAction.Format, project: project, workingDirectory: root.Path, framework: "net10.0"), + await tools.DotnetSdk(DotnetSdkAction.InstallTemplatePack, templatePackage: "Example.Templates", + workingDirectory: root.Path, prerelease: true) + }) + { + Assert.True(result.IsError); + Assert.Contains("requires .NET SDK 11", result.GetText()); + } + + var previous = Environment.GetEnvironmentVariable("DOTNET_TEST_RUNNER"); + try + { + Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", "Microsoft.Testing.Platform"); + var vstestProject = Path.Join(root.Path, "Selector.csproj"); + await File.WriteAllTextAsync(vstestProject, + """""", + TestContext.Current.CancellationToken); + string result; + var previousDirectory = DotNetCommandExecutor.WorkingDirectoryOverride.Value; + try + { + DotNetCommandExecutor.WorkingDirectoryOverride.Value = root.Path; + result = await tools.DotnetProjectTest(project: vstestProject, verbosity: "normal"); + } + finally { DotNetCommandExecutor.WorkingDirectoryOverride.Value = previousDirectory; } + Assert.Contains("VSTEST_SELECTED", result); + Assert.DoesNotContain("--project", result); + } + finally { Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", previous); } + } + + [Fact] + public async Task ExplicitRunner_OverridesInheritedRunnerOnlyInChildProcess() + { + using var root = await CreateFixtureAsync(); + var project = Path.Join(root.Path, "Selector.csproj"); + await File.WriteAllTextAsync(project, + """""", + TestContext.Current.CancellationToken); + var previousEnvironment = Environment.GetEnvironmentVariable("DOTNET_TEST_RUNNER"); + var previousDirectory = DotNetCommandExecutor.WorkingDirectoryOverride.Value; + try + { + Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", "Microsoft.Testing.Platform"); + DotNetCommandExecutor.WorkingDirectoryOverride.Value = root.Path; + foreach (var legacy in new[] { false, true }) + { + var result = await CreateTools().DotnetProjectTest(project: project, verbosity: "normal", + testRunner: TestRunner.VSTest, useLegacyProjectArgument: legacy); + Assert.Contains("VSTEST_SELECTED", result); + Assert.Contains("Exit Code: 0", result); + Assert.Equal("Microsoft.Testing.Platform", Environment.GetEnvironmentVariable("DOTNET_TEST_RUNNER")); + Assert.Null(DotNetCommandExecutor.TestRunnerEnvironmentOverride.Value); + } + } + finally + { + Environment.SetEnvironmentVariable("DOTNET_TEST_RUNNER", previousEnvironment); + DotNetCommandExecutor.WorkingDirectoryOverride.Value = previousDirectory; + } + } + + [Fact] + public async Task ConfigurationEnvironment_DefaultAndExplicitOverrideRemainSdkOwned() + { + using var root = await CreateFixtureAsync(); + var project = await WriteConsoleAsync(root.Path); + var previous = Environment.GetEnvironmentVariable("Configuration"); + try + { + Environment.SetEnvironmentVariable("Configuration", "Release"); + var tools = CreateTools(); + var inherited = await tools.DotnetProject(DotnetProjectAction.Build, project: project, workingDirectory: root.Path); + Assert.True(inherited.IsError != true, inherited.GetText()); + Assert.True(File.Exists(Path.Join(root.Path, "bin", "Release", "net10.0", "App.dll"))); + Assert.DoesNotContain(" -c ", inherited.GetText()); + var explicitResult = await tools.DotnetProject(DotnetProjectAction.Build, project: project, + workingDirectory: root.Path, configuration: "Debug"); + Assert.True(explicitResult.IsError != true, explicitResult.GetText()); + Assert.True(File.Exists(Path.Join(root.Path, "bin", "Debug", "net10.0", "App.dll"))); + } + finally { Environment.SetEnvironmentVariable("Configuration", previous); } + } + + [Fact] + public async Task Pack_CustomToolNuspecPreservesNetSdk1235WarningAsSuccess() + { + using var root = await CreateFixtureAsync(); + var project = await WriteConsoleAsync(root.Path); + var xml = await File.ReadAllTextAsync(project, TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(project, xml.Replace("", + "truecustom.nuspec"), + TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Join(root.Path, "custom.nuspec"), """ + SdkFeature.CustomTool1.0.0Test + Warning fixture + """, TestContext.Current.CancellationToken); + var result = await CreateTools().DotnetProject(DotnetProjectAction.Pack, project: project, workingDirectory: root.Path); + Assert.True(result.IsError != true, result.GetText()); + Assert.Contains("NETSDK1235", result.GetText()); + Assert.Single(Directory.GetFiles(Path.Join(root.Path, "bin", "Release"), "*.nupkg")); + } + + private static void WriteEntry(ZipArchive archive, string path, string content) + { + using var writer = new StreamWriter(archive.CreateEntry(path).Open()); + writer.Write(content); + } + + internal static async Task CreateFixtureAsync(string? sdkVersion = null) + { + var root = ScenarioHelpers.CreateTempDirectory(nameof(Sdk11FeatureTests)); + var sdk = await ScenarioHelpers.RunDotNetAsync("--version", AppContext.BaseDirectory, TestContext.Current.CancellationToken); + Assert.Equal(0, sdk.exitCode); + await File.WriteAllTextAsync(Path.Join(root.Path, "global.json"), JsonSerializer.Serialize(new + { + sdk = new { version = sdkVersion ?? sdk.stdout.Trim(), rollForward = "disable", allowPrerelease = true } + }), TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Join(root.Path, "NuGet.Config"), + "", TestContext.Current.CancellationToken); + return root; + } + + internal static async Task WriteConsoleAsync(string directory, string source = "Console.WriteLine(\"ok\");") + { + var project = Path.Join(directory, "App.csproj"); + await File.WriteAllTextAsync(project, """ + net10.0 + Exeenable + """, TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Join(directory, "Program.cs"), source, TestContext.Current.CancellationToken); + return project; + } +} diff --git a/DotNetMcp/Execution/CommandLineArgument.cs b/DotNetMcp/Execution/CommandLineArgument.cs new file mode 100644 index 00000000..d8b533df --- /dev/null +++ b/DotNetMcp/Execution/CommandLineArgument.cs @@ -0,0 +1,27 @@ +using System.Text; + +namespace DotNetMcp; + +internal static class CommandLineArgument +{ + internal static string Quote(string value) + { + var result = new StringBuilder("\""); + var backslashes = 0; + foreach (var character in value) + { + if (character == '\\') + { + backslashes++; + continue; + } + + result.Append('\\', character == '"' ? backslashes * 2 + 1 : backslashes); + result.Append(character); + backslashes = 0; + } + + result.Append('\\', backslashes * 2); + return result.Append('"').ToString(); + } +} diff --git a/DotNetMcp/Execution/DotNetCommandExecutor.cs b/DotNetMcp/Execution/DotNetCommandExecutor.cs index d1291c08..9ef23d40 100644 --- a/DotNetMcp/Execution/DotNetCommandExecutor.cs +++ b/DotNetMcp/Execution/DotNetCommandExecutor.cs @@ -16,6 +16,7 @@ public static class DotNetCommandExecutor internal static readonly AsyncLocal WorkingDirectoryOverride = new(); internal static readonly AsyncLocal RequestCancellationToken = new(); + internal static readonly AsyncLocal TestRunnerEnvironmentOverride = new(); internal static async ValueTask WithRequestCancellationAsync(CancellationToken cancellationToken, Func> action) { @@ -80,6 +81,8 @@ public static async Task ExecuteCommandAsync(string arguments, ILogger? UseShellExecute = false, CreateNoWindow = true }; + if (TestRunnerEnvironmentOverride.Value is { } runner) + psi.Environment["DOTNET_TEST_RUNNER"] = runner; if (requiresCancellation) { diff --git a/DotNetMcp/Execution/SdkFeatureSupport.cs b/DotNetMcp/Execution/SdkFeatureSupport.cs new file mode 100644 index 00000000..3483ae88 --- /dev/null +++ b/DotNetMcp/Execution/SdkFeatureSupport.cs @@ -0,0 +1,30 @@ +using Microsoft.Extensions.Logging; + +namespace DotNetMcp; + +internal static class SdkFeatureSupport +{ + internal static async Task<(int? Major, string? Error)> GetMajorVersionAsync(ILogger? logger = null) + { + try + { + var text = (await DotNetCommandExecutor.ExecuteCommandForResourceAsync("--version", logger, + cancellationToken: DotNetCommandExecutor.RequestCancellationToken.Value)).Trim(); + if (Version.TryParse(text.Split('-')[0], out var version)) + return (version.Major, null); + + return (null, $"Error: Could not determine the active SDK version from '{text}'."); + } + catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or IOException) + { + logger?.LogWarning(ex, "Could not determine the active SDK version"); + return (null, $"Error: Could not determine the active SDK version: {ex.Message}"); + } + } + + internal static async Task RequireSdk11Async(string feature, ILogger? logger = null) + { + var (major, error) = await GetMajorVersionAsync(logger); + return error ?? (major < 11 ? $"Error: {feature} requires .NET SDK 11 or later in the command's working directory." : null); + } +} diff --git a/DotNetMcp/SdkIntegration/TestRunnerDetector.cs b/DotNetMcp/SdkIntegration/TestRunnerDetector.cs index 1e7b5883..192ebaf2 100644 --- a/DotNetMcp/SdkIntegration/TestRunnerDetector.cs +++ b/DotNetMcp/SdkIntegration/TestRunnerDetector.cs @@ -4,7 +4,7 @@ namespace DotNetMcp.SdkIntegration; /// -/// Helper class for detecting the active test runner (MTP vs VSTest) from global.json configuration. +/// Helper class for detecting the active test runner from SDK-supported environment settings and global.json. /// public static class TestRunnerDetector { @@ -14,12 +14,19 @@ public static class TestRunnerDetector /// The working directory to start searching from (optional) /// The project path to search from if working directory is not provided (optional) /// Optional logger for diagnostic messages + /// Whether the active CLI SDK supports DOTNET_TEST_RUNNER (SDK 11+) /// A tuple containing the detected runner and the source of detection public static (Actions.TestRunner runner, string source) DetectTestRunner( string? workingDirectory = null, string? projectPath = null, - ILogger? logger = null) + ILogger? logger = null, + bool supportsEnvironmentRunner = true) { + if (supportsEnvironmentRunner && GetEnvironmentRunner() is { } environmentRunner) + { + logger?.LogDebug("Detected test runner from DOTNET_TEST_RUNNER"); + return (environmentRunner, "DOTNET_TEST_RUNNER"); + } // Determine starting directory for global.json search string? searchDirectory = DetermineSearchDirectory(workingDirectory, projectPath); @@ -36,6 +43,7 @@ public static (Actions.TestRunner runner, string source) DetectTestRunner( logger?.LogDebug(ex, "Failed to get current directory for test runner detection, defaulting to VSTest"); return (Actions.TestRunner.VSTest, "default"); } + } // Walk up directory tree looking for global.json @@ -76,6 +84,16 @@ public static (Actions.TestRunner runner, string source) DetectTestRunner( return (Actions.TestRunner.VSTest, "default"); } + internal static Actions.TestRunner? GetEnvironmentRunner() + { + var value = Environment.GetEnvironmentVariable("DOTNET_TEST_RUNNER"); + if (string.Equals(value, "Microsoft.Testing.Platform", StringComparison.OrdinalIgnoreCase)) + return Actions.TestRunner.MicrosoftTestingPlatform; + if (string.Equals(value, "VSTest", StringComparison.OrdinalIgnoreCase)) + return Actions.TestRunner.VSTest; + return null; + } + /// /// Determine the directory to start searching for global.json. /// Prioritizes workingDirectory, then projectPath's directory. diff --git a/DotNetMcp/Tools/Cli/DotNetCliTools.Misc.cs b/DotNetMcp/Tools/Cli/DotNetCliTools.Misc.cs index 3e235cd4..7f7abe2f 100644 --- a/DotNetMcp/Tools/Cli/DotNetCliTools.Misc.cs +++ b/DotNetMcp/Tools/Cli/DotNetCliTools.Misc.cs @@ -244,19 +244,27 @@ public partial Task DotnetServerInfo() /// Include generated code files /// Comma-separated list of diagnostic IDs to fix /// Severity level to fix (info, warn, error) + /// Target framework to load (SDK 11+) internal async Task DotnetFormat( string? project = null, bool verify = false, bool includeGenerated = false, string? diagnostics = null, - string? severity = null) + string? severity = null, + string? framework = null) { + if (!ParameterValidator.ValidateFramework(framework, out var frameworkError)) + return $"Error: {frameworkError}"; + if (!string.IsNullOrEmpty(framework) + && await SdkFeatureSupport.RequireSdk11Async("Format framework selection", _logger) is { } sdkError) + return sdkError; var args = new StringBuilder("format"); if (!string.IsNullOrEmpty(project)) args.Append($" \"{project}\""); if (verify) args.Append(" --verify-no-changes"); if (includeGenerated) args.Append(" --include-generated"); if (!string.IsNullOrEmpty(diagnostics)) args.Append($" --diagnostics {diagnostics}"); if (!string.IsNullOrEmpty(severity)) args.Append($" --severity {severity}"); + if (!string.IsNullOrEmpty(framework)) args.Append($" --framework {framework}"); return await ExecuteDotNetCommand(args.ToString()); } diff --git a/DotNetMcp/Tools/Cli/DotNetCliTools.Project.Consolidated.cs b/DotNetMcp/Tools/Cli/DotNetCliTools.Project.Consolidated.cs index 230d659f..d952185b 100644 --- a/DotNetMcp/Tools/Cli/DotNetCliTools.Project.Consolidated.cs +++ b/DotNetMcp/Tools/Cli/DotNetCliTools.Project.Consolidated.cs @@ -29,6 +29,7 @@ public sealed partial class DotNetCliTools /// Target runtime identifier for publish action (e.g., 'linux-x64', 'win-x64') /// Template-specific options for new action (e.g., '--use-program-main', '--aot') /// Arguments to pass to the application for run action + /// Application environment variables for Run (SDK 11+), passed with repeated --environment options. Does not change the server environment. /// Test filter expression for test action /// Data collector friendly name for test action (e.g., 'XPlat Code Coverage') /// Directory for test results @@ -48,7 +49,7 @@ public sealed partial class DotNetCliTools /// Comma-separated list of diagnostic IDs to fix for format action /// Severity level to fix for format action (info, warn, error) /// Working directory for command execution - /// Test runner selection for test action (Auto, MicrosoftTestingPlatform, or VSTest). Auto detects from global.json. Default: Auto + /// Test runner selection for Test (Auto, MicrosoftTestingPlatform, or VSTest). Auto uses DOTNET_TEST_RUNNER on SDK 11+, then global.json. Default: Auto /// DEPRECATED: Use testRunner parameter instead. When true, uses positional project argument (VSTest mode) /// Session ID for stop/logs actions (required when action is Stop or Logs) /// Start mode for run/watch actions (Foreground or Background). Foreground blocks until exit, Background returns immediately with sessionId. Default: Foreground @@ -117,6 +118,7 @@ public async partial Task DotnetProject( string? configFile = null, string? itemType = null, string? include = null, + Dictionary? environmentVariables = null, IProgress? progress = null, McpServer? server = null, RequestContext? context = null) @@ -144,6 +146,8 @@ DotnetProjectAction.RemoveProperty or DotnetProjectAction.AddItem or { return $"Error: {errorMessage}"; } + if (environmentVariables is not null && action != DotnetProjectAction.Run) + return "Error: environmentVariables is only used with Run."; // Route to appropriate handler based on action return action switch @@ -151,7 +155,7 @@ DotnetProjectAction.RemoveProperty or DotnetProjectAction.AddItem or DotnetProjectAction.New => await HandleNewAction(template, name, output, framework, additionalOptions), DotnetProjectAction.Restore => await ExecuteWithProgress(progress, "Restoring packages...", "Restore complete", () => HandleRestoreAction(effectiveProject, verbosity, source, lockedMode, configFile, server, context)), DotnetProjectAction.Build => await ExecuteWithProgress(progress, "Building project...", "Build complete", () => HandleBuildAction(effectiveProject, configuration, framework, noRestore, verbosity, output, server, context)), - DotnetProjectAction.Run => await ExecuteWithProgress(progress, "Building and starting application...", "Run complete", () => HandleRunAction(effectiveProject, configuration, appArgs, noBuild, startMode)), + DotnetProjectAction.Run => await ExecuteWithProgress(progress, "Building and starting application...", "Run complete", () => HandleRunAction(effectiveProject, configuration, appArgs, noBuild, startMode, environmentVariables)), DotnetProjectAction.Test => await ExecuteWithProgress(progress, "Running tests...", "Tests complete", () => HandleTestAction(effectiveProject, configuration, filter, collect, resultsDirectory, logger, noBuild, noRestore, verbosity, framework, blame, listTests, testRunner, useLegacyProjectArgument, server, context)), DotnetProjectAction.Publish => await ExecuteWithProgress(progress, "Publishing project...", "Publish complete", () => HandlePublishAction(effectiveProject, configuration, output, runtime, framework, noRestore, noBuild, selfContained, arch, os, verbosity, server, context)), DotnetProjectAction.Clean => await ExecuteWithProgress(progress, "Cleaning output directories...", "Clean complete", () => HandleCleanAction(effectiveProject, configuration, framework, verbosity, server, context)), @@ -160,7 +164,7 @@ DotnetProjectAction.RemoveProperty or DotnetProjectAction.AddItem or DotnetProjectAction.Validate => await HandleValidateAction(projectPath), DotnetProjectAction.Pack => await ExecuteWithProgress(progress, "Packing project...", "Pack complete", () => HandlePackAction(effectiveProject, configuration, output, includeSymbols, includeSource)), DotnetProjectAction.Watch => await HandleWatchAction(watchAction, effectiveProject, configuration, appArgs, filter, noHotReload, startMode), - DotnetProjectAction.Format => await HandleFormatAction(effectiveProject, verify, includeGenerated, diagnostics, severity), + DotnetProjectAction.Format => await HandleFormatAction(effectiveProject, verify, includeGenerated, diagnostics, severity, framework), DotnetProjectAction.Stop => await HandleStopAction(sessionId), DotnetProjectAction.Logs => await HandleLogsAction(sessionId, tailLines, since), DotnetProjectAction.ListTemplateOptions => await HandleListTemplateOptionsAction(template), @@ -314,7 +318,7 @@ private async Task HandleBuildAction(string? project, string? configurat "Summarize these .NET build errors and suggest fixes (be concise):"); } - private async Task HandleRunAction(string? project, string? configuration, string? appArgs, bool? noBuild, StartMode? startMode) + private async Task HandleRunAction(string? project, string? configuration, string? appArgs, bool? noBuild, StartMode? startMode, Dictionary? environmentVariables) { var effectiveStartMode = startMode ?? StartMode.Foreground; @@ -325,7 +329,8 @@ private async Task HandleRunAction(string? project, string? configuratio project: project, configuration: configuration, appArgs: appArgs, - noBuild: noBuild ?? false); + noBuild: noBuild ?? false, + environmentVariables: environmentVariables); } // Background mode - start process and return immediately with session metadata @@ -341,12 +346,12 @@ private async Task HandleRunAction(string? project, string? configuratio return $"Error: {configError}"; } - // Build the command arguments - var args = new StringBuilder("run"); - if (!string.IsNullOrEmpty(project)) args.Append($" --project \"{project}\""); - if (!string.IsNullOrEmpty(configuration)) args.Append($" -c {configuration}"); - if (noBuild ?? false) args.Append(" --no-build"); - if (!string.IsNullOrEmpty(appArgs)) args.Append($" -- {appArgs}"); + if (ValidateRunEnvironment(environmentVariables) is { } environmentError) + return environmentError; + if (environmentVariables is { Count: > 0 } + && await SdkFeatureSupport.RequireSdk11Async("Run environment variables", _logger) is { } sdkError) + return sdkError; + var args = BuildRunArguments(project, configuration, appArgs, noBuild ?? false, environmentVariables); // Determine the target for session tracking var workingDir = DotNetCommandExecutor.WorkingDirectoryOverride.Value; @@ -728,7 +733,7 @@ private async Task HandleWatchAction(string? watchAction, string? projec }; } - private async Task HandleFormatAction(string? project, bool? verify, bool? includeGenerated, string? diagnostics, string? severity) + private async Task HandleFormatAction(string? project, bool? verify, bool? includeGenerated, string? diagnostics, string? severity, string? framework) { // Route to existing DotnetFormat method return await DotnetFormat( @@ -736,7 +741,8 @@ private async Task HandleFormatAction(string? project, bool? verify, boo verify: verify ?? false, includeGenerated: includeGenerated ?? false, diagnostics: diagnostics, - severity: severity); + severity: severity, + framework: framework); } private Task HandleStopAction(string? sessionId) @@ -1161,7 +1167,8 @@ internal async Task DotnetProjectRun( string? project = null, string? configuration = null, string? appArgs = null, - bool noBuild = false) + bool noBuild = false, + Dictionary? environmentVariables = null) { // Validate project path if provided if (!ParameterValidator.ValidateProjectPath(project, out var projectError)) @@ -1171,21 +1178,49 @@ internal async Task DotnetProjectRun( if (!ParameterValidator.ValidateConfiguration(configuration, out var configError)) return $"Error: {configError}"; + if (ValidateRunEnvironment(environmentVariables) is { } environmentError) + return environmentError; + if (environmentVariables is { Count: > 0 } + && await SdkFeatureSupport.RequireSdk11Async("Run environment variables", _logger) is { } sdkError) + return sdkError; + var args = BuildRunArguments(project, configuration, appArgs, noBuild, environmentVariables); + + // Capture working directory for concurrency target selection + var workingDir = DotNetCommandExecutor.WorkingDirectoryOverride.Value; + return (await ExecuteWithConcurrencyCheck("run", GetOperationTarget(project, workingDir), args.ToString())).text; + } + + internal static string? ValidateRunEnvironment(Dictionary? environmentVariables) + { + if (environmentVariables is null) + return null; + foreach (var (name, value) in environmentVariables) + { + if (string.IsNullOrWhiteSpace(name) || name.Contains('=') || name.Any(char.IsControl)) + return "Error: environmentVariables names must be nonempty and must not contain '=' or control characters."; + if (value is null || value.Any(char.IsControl)) + return "Error: environmentVariables values must be strings without control characters; use an empty string for an empty value."; + } + return null; + } + + internal static StringBuilder BuildRunArguments(string? project, string? configuration, string? appArgs, + bool noBuild, Dictionary? environmentVariables) + { var args = new StringBuilder("run"); if (!string.IsNullOrEmpty(project)) args.Append($" --project \"{project}\""); if (!string.IsNullOrEmpty(configuration)) args.Append($" -c {configuration}"); if (noBuild) args.Append(" --no-build"); + if (environmentVariables is not null) + foreach (var (name, value) in environmentVariables) + args.Append($" --environment {CommandLineArgument.Quote($"{name}={value}")}"); if (!string.IsNullOrEmpty(appArgs)) args.Append($" -- {appArgs}"); - - // Capture working directory for concurrency target selection - var workingDir = DotNetCommandExecutor.WorkingDirectoryOverride.Value; - return (await ExecuteWithConcurrencyCheck("run", GetOperationTarget(project, workingDir), args.ToString())).text; + return args; } /// /// Run unit tests in a .NET project. - /// Test runner can be explicitly specified or auto-detected from global.json. - /// Auto mode (default) detects MTP from global.json config, otherwise uses VSTest for legacy compatibility. + /// Test runner can be explicitly specified or auto-detected from SDK-supported environment settings and global.json. /// internal async Task DotnetProjectTest( string? project = null, @@ -1222,6 +1257,15 @@ internal async Task DotnetProjectTest( // Determine the effective test runner TestRunner effectiveRunner; string selectionSource; + var explicitRunner = useLegacyProjectArgument || (testRunner.HasValue && testRunner != TestRunner.Auto); + var supportsEnvironmentRunner = false; + if (explicitRunner || SdkIntegration.TestRunnerDetector.GetEnvironmentRunner().HasValue) + { + var (major, sdkError) = await SdkFeatureSupport.GetMajorVersionAsync(_logger); + if (sdkError is not null) + return sdkError; + supportsEnvironmentRunner = major >= 11; + } // If useLegacyProjectArgument is true, use VSTest mode for backward compatibility if (useLegacyProjectArgument) @@ -1242,7 +1286,8 @@ internal async Task DotnetProjectTest( var (detectedRunner, detectionSource) = SdkIntegration.TestRunnerDetector.DetectTestRunner( workingDirectory: workingDirForDetection, projectPath: project, - logger: _logger); + logger: _logger, + supportsEnvironmentRunner: supportsEnvironmentRunner); effectiveRunner = detectedRunner; selectionSource = detectionSource; } @@ -1259,6 +1304,17 @@ internal async Task DotnetProjectTest( if (!string.IsNullOrEmpty(projectDir)) { DotNetCommandExecutor.WorkingDirectoryOverride.Value = projectDir; + if (explicitRunner || SdkIntegration.TestRunnerDetector.GetEnvironmentRunner().HasValue) + { + var (major, sdkError) = await SdkFeatureSupport.GetMajorVersionAsync(_logger); + if (sdkError is not null) + return sdkError; + supportsEnvironmentRunner = major >= 11; + if (!explicitRunner) + (effectiveRunner, selectionSource) = SdkIntegration.TestRunnerDetector.DetectTestRunner( + workingDirectory: projectDir, projectPath: project, logger: _logger, + supportsEnvironmentRunner: supportsEnvironmentRunner); + } } } @@ -1296,7 +1352,18 @@ internal async Task DotnetProjectTest( // Use working directory for concurrency target selection var workingDirForTarget = DotNetCommandExecutor.WorkingDirectoryOverride.Value; - return (await ExecuteWithConcurrencyCheck("test", GetOperationTarget(project, workingDirForTarget), args.ToString())).text; + var previousRunner = DotNetCommandExecutor.TestRunnerEnvironmentOverride.Value; + try + { + if (explicitRunner && supportsEnvironmentRunner) + DotNetCommandExecutor.TestRunnerEnvironmentOverride.Value = effectiveRunner == TestRunner.MicrosoftTestingPlatform + ? "Microsoft.Testing.Platform" : "VSTest"; + return (await ExecuteWithConcurrencyCheck("test", GetOperationTarget(project, workingDirForTarget), args.ToString())).text; + } + finally + { + DotNetCommandExecutor.TestRunnerEnvironmentOverride.Value = previousRunner; + } } /// diff --git a/DotNetMcp/Tools/Cli/DotNetCliTools.Solution.cs b/DotNetMcp/Tools/Cli/DotNetCliTools.Solution.cs index 903e535a..2a68a619 100644 --- a/DotNetMcp/Tools/Cli/DotNetCliTools.Solution.cs +++ b/DotNetMcp/Tools/Cli/DotNetCliTools.Solution.cs @@ -1,5 +1,8 @@ using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; using DotNetMcp.Actions; +using Microsoft.Extensions.Logging; using ModelContextProtocol.Protocol; using ModelContextProtocol.Server; @@ -15,25 +18,54 @@ public sealed partial class DotNetCliTools /// /// The name for the solution file /// The output directory for the solution file - /// The solution file format: 'sln' (classic) or 'slnx' (XML-based). Default is 'sln'. + /// The solution file format: 'sln', 'slnx', or 'slnf'. Default is 'sln'. + /// Parent .sln or .slnx file, required only for 'slnf' (SDK 11+) internal async Task DotnetSolutionCreate( string name, string? output = null, - string? format = null) + string? format = null, + string? parentSolution = null) { - var args = new StringBuilder("new sln"); - args.Append($" -n \"{name}\""); - if (!string.IsNullOrEmpty(output)) args.Append($" -o \"{output}\""); - - // Determine the format to use - var effectiveFormat = format ?? "sln"; // Default to 'sln' for backward compatibility - - if (effectiveFormat != "sln" && effectiveFormat != "slnx") + var effectiveFormat = format ?? "sln"; + if (effectiveFormat is not ("sln" or "slnx" or "slnf")) + return "Error: format must be 'sln', 'slnx', or 'slnf'."; + + if (effectiveFormat == "slnf") + { + if (!ParameterValidator.ValidateRequiredParameter(parentSolution, "parentSolution", out var parentError)) + return $"Error: {parentError}"; + var parentExtension = Path.GetExtension(parentSolution); + if (!string.Equals(parentExtension, ".sln", StringComparison.OrdinalIgnoreCase) + && !string.Equals(parentExtension, ".slnx", StringComparison.OrdinalIgnoreCase)) + return "Error: parentSolution must be a .sln or .slnx file."; + if (parentSolution!.Any(char.IsControl)) + return "Error: parentSolution must not contain control characters."; + try + { + var baseDirectory = DotNetCommandExecutor.WorkingDirectoryOverride.Value ?? Directory.GetCurrentDirectory(); + var filterDirectory = string.IsNullOrEmpty(output) ? baseDirectory : Path.GetFullPath(output, baseDirectory); + if (!File.Exists(Path.GetFullPath(parentSolution!, filterDirectory))) + return "Error: parentSolution does not exist. Relative parent paths are resolved from the filter's output directory."; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) + { + return $"Error: Invalid parentSolution or output path: {ex.Message}"; + } + if (await SdkFeatureSupport.RequireSdk11Async("Solution filters", _logger) is { } sdkError) + return sdkError; + } + else if (parentSolution is not null) { - return "Error: format must be either 'sln' or 'slnx'."; + return "Error: parentSolution is only used with format 'slnf'."; } - - args.Append($" --format {effectiveFormat}"); + + var args = new StringBuilder(effectiveFormat == "slnf" ? "new slnf" : "new sln"); + args.Append($" -n {CommandLineArgument.Quote(name)}"); + if (!string.IsNullOrEmpty(output)) args.Append($" -o {CommandLineArgument.Quote(output)}"); + if (effectiveFormat == "slnf") + args.Append($" --parent-solution {CommandLineArgument.Quote(parentSolution!)}"); + else + args.Append($" --format {effectiveFormat}"); return await ExecuteDotNetCommand(args.ToString()); } @@ -81,6 +113,9 @@ internal async Task DotnetSolutionRemove( return "Error: at least one project path is required."; } + if (string.Equals(Path.GetExtension(solution), ".slnf", StringComparison.OrdinalIgnoreCase)) + return await RemoveFilterProjectsAsync(solution, projects); + var args = new StringBuilder($"solution \"{solution}\" remove"); foreach (var project in projects) { @@ -89,6 +124,89 @@ internal async Task DotnetSolutionRemove( return await ExecuteDotNetCommand(args.ToString()); } + private async Task RemoveFilterProjectsAsync(string solution, string[] projects) + { + // SDK 11 RC3 compares filter-relative removal paths with parent-relative entries. + // Edit the filter itself rather than pass fictitious project paths to the CLI. + string? temporaryPath = null; + try + { + var cancellationToken = DotNetCommandExecutor.RequestCancellationToken.Value; + var workingDirectory = DotNetCommandExecutor.WorkingDirectoryOverride.Value ?? Directory.GetCurrentDirectory(); + var filterPath = Path.GetFullPath(solution, workingDirectory); + await using var stream = new FileStream(filterPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, + bufferSize: 4096, useAsync: true); + using var reader = new StreamReader(stream, leaveOpen: true); + var originalContent = await reader.ReadToEndAsync(cancellationToken); + var root = JsonNode.Parse(originalContent); + if (root?["solution"] is not JsonObject filter + || filter["path"] is not JsonValue parentValue || !parentValue.TryGetValue(out var parent) + || string.IsNullOrWhiteSpace(parent) || filter["projects"] is not JsonArray entries) + return "Error: Invalid solution filter. Expected solution.path and solution.projects."; + + var parentPath = Path.GetFullPath(parent.Replace('\\', Path.DirectorySeparatorChar), Path.GetDirectoryName(filterPath)!); + if (!string.Equals(Path.GetExtension(parentPath), ".sln", StringComparison.OrdinalIgnoreCase) + && !string.Equals(Path.GetExtension(parentPath), ".slnx", StringComparison.OrdinalIgnoreCase)) + return "Error: The solution filter's parent must be a .sln or .slnx file."; + if (!File.Exists(parentPath)) + return "Error: The solution filter's parent solution does not exist."; + var parentDirectory = Path.GetDirectoryName(parentPath)!; + var comparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + var requestedPaths = new HashSet(comparer); + foreach (var project in projects) + { + var fullPath = Path.GetFullPath(project, workingDirectory); + if (Directory.Exists(fullPath)) + { + var candidates = Directory.GetFiles(fullPath).Where(path => + Path.GetExtension(path) is ".csproj" or ".fsproj" or ".vbproj").ToArray(); + if (candidates.Length != 1) + return $"Error: Expected exactly one project in '{project}'."; + fullPath = candidates[0]; + } + requestedPaths.Add(fullPath); + } + + var indices = new List(); + var missingPaths = new HashSet(requestedPaths, comparer); + for (var index = 0; index < entries.Count; index++) + { + if (entries[index] is not JsonValue entry || !entry.TryGetValue(out var path) + || string.IsNullOrWhiteSpace(path)) + return "Error: Invalid solution filter project path."; + var fullPath = Path.GetFullPath(path.Replace('\\', Path.DirectorySeparatorChar), parentDirectory); + if (requestedPaths.Contains(fullPath)) + { + missingPaths.Remove(fullPath); + indices.Add(index); + } + } + if (missingPaths.Count > 0) + return "Error: One or more requested projects are not present in the solution filter. No changes were made."; + + foreach (var index in indices.AsEnumerable().Reverse()) + entries.RemoveAt(index); + var content = root!.ToJsonString(new JsonSerializerOptions { WriteIndented = true }); + temporaryPath = filterPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + await File.WriteAllTextAsync(temporaryPath, content, cancellationToken); + if (await File.ReadAllTextAsync(filterPath, cancellationToken) != originalContent) + return "Error: The solution filter changed during removal. No changes were made; retry with the current file."; + cancellationToken.ThrowIfCancellationRequested(); + File.Replace(temporaryPath, filterPath, destinationBackupFileName: null); + return $"Removed {indices.Count} project(s) from solution filter '{solution}'."; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or ArgumentException or InvalidOperationException or NotSupportedException) + { + _logger.LogWarning(ex, "Failed to remove projects from solution filter {Solution}", solution); + return $"Error: Could not update solution filter: {ex.Message}"; + } + finally + { + if (temporaryPath is not null) + File.Delete(temporaryPath); + } + } + /// /// Manage solution files and project membership. A solution file organizes multiple related projects. /// This is a consolidated tool that routes to specific solution operations based on the action parameter. @@ -97,7 +215,8 @@ internal async Task DotnetSolutionRemove( /// Path to solution file. Required for 'add', 'list', and 'remove' actions. Not used for 'create' action (which uses the name parameter). /// Solution name (required for 'create' action) /// Output directory for solution file (optional, used with 'create' action) - /// Solution file format: 'sln' (classic) or 'slnx' (XML-based). Default is 'sln'. (optional, used with 'create' action) + /// Solution file format: 'sln', 'slnx', or 'slnf' (SDK 11+). Default is 'sln'. Used with Create. + /// Explicit parent .sln or .slnx path, required for Create with format 'slnf' /// Array of project file paths (required for 'add' and 'remove' actions) /// Injected MCP request context for destructive-operation confirmation [McpServerTool(Title = ".NET Solution Manager", ReadOnly = false, Destructive = true, Idempotent = false, OpenWorld = true, UseStructuredContent = true, OutputSchemaType = typeof(SolutionListResult), IconSource = "https://raw.githubusercontent.com/microsoft/fluentui-emoji/62ecdc0d7ca5c6df32148c169556bc8d3782fca4/assets/Card%20File%20Box/Flat/card_file_box_flat.svg")] @@ -114,6 +233,7 @@ public async partial Task DotnetSolution( string? output = null, string? format = null, string[]? projects = null, + string? parentSolution = null, McpServer? server = null, RequestContext? context = null) { @@ -123,6 +243,17 @@ public async partial Task DotnetSolution( return StructuredContentHelper.ApplicationError($"Error: {actionError}"); } + if (parentSolution is not null && action != DotnetSolutionAction.Create) + return StructuredContentHelper.ApplicationError("Error: parentSolution is only used with Create."); + + if (string.Equals(Path.GetExtension(solution), ".slnf", StringComparison.OrdinalIgnoreCase)) + { + if (action is DotnetSolutionAction.Analyze or DotnetSolutionAction.Dependencies or DotnetSolutionAction.Validate) + return StructuredContentHelper.ApplicationError("Error: Solution filter analysis is not supported. Use the parent .sln or .slnx file."); + if (await SdkFeatureSupport.RequireSdk11Async("Solution filters", _logger) is { } sdkError) + return StructuredContentHelper.ApplicationError(sdkError); + } + // Auto-detect solution from workspace roots when not explicitly specified. // Only applicable for actions that require a solution path (Add, List, Remove); // Create uses the name parameter instead. @@ -137,7 +268,7 @@ DotnetSolutionAction.Add or DotnetSolutionAction.List or DotnetSolutionAction.Re // Route to appropriate method based on action var textResult = action switch { - DotnetSolutionAction.Create => await HandleCreateAction(name, output, format), + DotnetSolutionAction.Create => await HandleCreateAction(name, output, format, parentSolution), DotnetSolutionAction.Add => await HandleAddAction(effectiveSolution, projects), DotnetSolutionAction.List => await HandleListAction(effectiveSolution), DotnetSolutionAction.Remove => await HandleRemoveAction(effectiveSolution, projects, server, context), @@ -155,7 +286,7 @@ DotnetSolutionAction.Add or DotnetSolutionAction.List or DotnetSolutionAction.Re return StructuredContentHelper.ActionResult(action, textResult, structured); } - private async Task HandleCreateAction(string? name, string? output, string? format) + private async Task HandleCreateAction(string? name, string? output, string? format, string? parentSolution) { // Validate required parameter for create action if (!ParameterValidator.ValidateRequiredParameter(name, "name", out var nameError)) @@ -163,7 +294,7 @@ private async Task HandleCreateAction(string? name, string? output, stri return $"Error: {nameError}"; } - return await DotnetSolutionCreate(name!, output, format); + return await DotnetSolutionCreate(name!, output, format, parentSolution); } private async Task HandleAddAction(string? solution, string[]? projects) diff --git a/DotNetMcp/Tools/Sdk/DotNetCliTools.Sdk.Consolidated.cs b/DotNetMcp/Tools/Sdk/DotNetCliTools.Sdk.Consolidated.cs index c02b63c5..c73f1fbe 100644 --- a/DotNetMcp/Tools/Sdk/DotNetCliTools.Sdk.Consolidated.cs +++ b/DotNetMcp/Tools/Sdk/DotNetCliTools.Sdk.Consolidated.cs @@ -36,6 +36,7 @@ public sealed partial class DotNetCliTools /// SDK roll-forward policy for global.json (e.g., 'latestMinor', 'latestMajor', 'disable') for ConfigureGlobalJson action /// Test runner to configure in global.json (e.g., 'Microsoft.Testing.Platform', 'VSTest') for ConfigureGlobalJson action /// Path to global.json file; defaults to 'global.json' in the working directory for ConfigureGlobalJson action + /// Include prerelease template versions when installing without an explicit version (SDK 11+). Only used with InstallTemplatePack. [McpServerTool(Title = ".NET SDK & Templates", ReadOnly = false, Destructive = true, Idempotent = false, OpenWorld = true, UseStructuredContent = true, OutputSchemaType = typeof(SdkActionResult), IconSource = "https://raw.githubusercontent.com/microsoft/fluentui-emoji/62ecdc0d7ca5c6df32148c169556bc8d3782fca4/assets/Gear/Flat/gear_flat.svg")] [McpMeta("category", "sdk")] [McpMeta("priority", 9.0)] @@ -64,10 +65,11 @@ public async partial Task DotnetSdk( string? rollForward = null, string? testRunner = null, string? globalJsonPath = null, - McpServer? server = null) + McpServer? server = null, + bool prerelease = false) => await DotnetSdkCoreAsync(action, searchTerm, templateShortName, templatePackage, templateVersion, nugetSource, interactive, force, framework, forceReload, filter, maxResults, workingDirectory, - sdkVersion, rollForward, testRunner, globalJsonPath, server); + sdkVersion, rollForward, testRunner, globalJsonPath, server, prerelease: prerelease); private async Task DotnetSdkCoreAsync( DotnetSdkAction action, @@ -88,7 +90,8 @@ private async Task DotnetSdkCoreAsync( string? testRunner = null, string? globalJsonPath = null, McpServer? server = null, - bool useDashboard = true) + bool useDashboard = true, + bool prerelease = false) { object? metadata = null; async Task QueryTemplatesAsync() @@ -106,6 +109,8 @@ async Task QuerySdksAsync() } var textResult = await WithWorkingDirectoryAsync(workingDirectory, async () => { + if (prerelease && action != DotnetSdkAction.InstallTemplatePack) + return "Error: prerelease is only used with InstallTemplatePack."; // Validate action parameter if (!ParameterValidator.ValidateAction(action, out var errorMessage)) { @@ -128,7 +133,7 @@ async Task QuerySdksAsync() DotnetSdkAction.TemplateInfo => await HandleTemplateInfoAction(templateShortName, forceReload), DotnetSdkAction.ClearTemplateCache => await DotnetTemplateClearCache(server), DotnetSdkAction.ListTemplatePacks => await DotnetTemplatePackList(), - DotnetSdkAction.InstallTemplatePack => await HandleTemplatePackInstallAction(templatePackage, templateVersion, nugetSource, interactive, force, server), + DotnetSdkAction.InstallTemplatePack => await HandleTemplatePackInstallAction(templatePackage, templateVersion, nugetSource, interactive, force, server, prerelease), DotnetSdkAction.UninstallTemplatePack => await HandleTemplatePackUninstallAction(templatePackage, server), DotnetSdkAction.FrameworkInfo => await DotnetFrameworkInfoCoreAsync(framework, value => metadata = value), DotnetSdkAction.CacheMetrics => await DotnetCacheMetricsCore(value => metadata = value), @@ -192,7 +197,8 @@ private async Task HandleTemplatePackInstallAction( string? nugetSource, bool interactive, bool force, - McpServer? server = null) + McpServer? server = null, + bool prerelease = false) { if (!ParameterValidator.ValidateTemplatePackage(templatePackage, out var packageError)) { @@ -218,7 +224,7 @@ private async Task HandleTemplatePackInstallAction( return $"Error: {message}"; } - return await DotnetTemplatePackInstall(templatePackage!, templateVersion, nugetSource, interactive, force, server); + return await DotnetTemplatePackInstall(templatePackage!, templateVersion, nugetSource, interactive, force, server, prerelease); } private async Task HandleTemplatePackUninstallAction(string? templatePackage, McpServer? server = null) @@ -403,6 +409,7 @@ internal async Task DotnetTemplateClearCache(McpServer? server = null) /// Optional NuGet source to use (feed URL or local source) /// Allow user interaction for authentication /// Allow overriding a template pack from another source + /// Include prerelease versions when no explicit version is specified (SDK 11+) [McpMeta("category", "template")] [McpMeta("commonlyUsed", true)] internal async Task DotnetTemplatePackInstall( @@ -411,8 +418,11 @@ internal async Task DotnetTemplatePackInstall( string? nugetSource = null, bool interactive = false, bool force = false, - McpServer? server = null) + McpServer? server = null, + bool prerelease = false) { + if (prerelease && await SdkFeatureSupport.RequireSdk11Async("Prerelease template selection", _logger) is { } sdkError) + return sdkError; var packageExpression = !string.IsNullOrWhiteSpace(templateVersion) ? $"{templatePackage}@{templateVersion}" : templatePackage; @@ -421,6 +431,7 @@ internal async Task DotnetTemplatePackInstall( if (!string.IsNullOrWhiteSpace(nugetSource)) args.Append($" --nuget-source \"{nugetSource}\""); if (interactive) args.Append(" --interactive"); if (force) args.Append(" --force"); + if (prerelease) args.Append(" --prerelease"); var result = await ExecuteDotNetCommand(args.ToString()); diff --git a/README.md b/README.md index f227e2da..d092787d 100644 --- a/README.md +++ b/README.md @@ -819,16 +819,28 @@ Unified interface for all project operations: **New**, **Restore**, **Build**, * - **Stop action**: Terminates long-running process sessions (like `dotnet run`) by session ID - **noBuild parameter**: Skip building before running (mirrors `dotnet run --no-build`) -**Test Runner Compatibility**: The Test action automatically detects the test runner from `global.json` configuration. If `global.json` contains `{ "test": { "runner": "Microsoft.Testing.Platform" } }`, it uses the `--project` flag (MTP mode). Otherwise, it defaults to positional argument (VSTest mode) for legacy compatibility. +**Test Runner Compatibility**: In Auto mode, the Test action honors `DOTNET_TEST_RUNNER` on .NET SDK 11+ before reading `global.json`. Recognized values are `Microsoft.Testing.Platform` and `VSTest`, case-insensitively; empty or unknown values fall through to `global.json`. MTP uses `--project`; VSTest uses a positional project argument. An explicit `testRunner` (or the deprecated legacy selector) takes precedence; on SDK 11+, the matching runner is set only in the test child process, without changing the server environment or `global.json`. You can explicitly specify the test runner using the `testRunner` parameter: -- `Auto` (default) - Auto-detect from global.json -- `MicrosoftTestingPlatform` - Use --project flag (requires .NET SDK 8+ with MTP or SDK 10+) +- `Auto` (default) - Auto-detect from SDK-supported environment settings, then global.json +- `MicrosoftTestingPlatform` - Use --project flag (requires .NET SDK 10+ and MTP 1.7+) - `VSTest` - Use positional argument (compatible with all SDK versions) The `useLegacyProjectArgument` parameter is deprecated; use `testRunner: "VSTest"` instead. +**.NET 11 opt-ins:** Run accepts an `environmentVariables` string map, serialized as repeated `--environment` options in both foreground and background modes. Empty values, spaces, quotes, and embedded `=` are supported; names cannot contain `=` or control characters, and values cannot contain control characters. Format honors the existing `framework` parameter to select the target framework to analyze. These opt-ins require SDK 11+ in the command's working directory, regardless of the server's runtime. + +```typescript +await callTool("dotnet_project", { + action: "Run", project: "MyApi/MyApi.csproj", + environmentVariables: { ASPNETCORE_ENVIRONMENT: "Development", LOG_LEVEL: "Debug" } +}); +await callTool("dotnet_project", { + action: "Format", project: "MyApi/MyApi.csproj", framework: "net10.0" +}); +``` + Example: ```typescript @@ -928,10 +940,22 @@ await callTool("dotnet_package", { #### dotnet_solution - Solution File Management -**Full parity with `dotnet sln` / `dotnet solution` CLI commands.** +Supports solution creation and project membership through `dotnet sln` / `dotnet solution`. Manage solution files and project membership: **Create**, **Add**, **List**, **Remove** +SDK 11+ also supports `format: "slnf"` with a required `parentSolution` pointing to an existing `.sln` or `.slnx`. Relative parent paths are resolved from the filter's output directory. Add/List/Remove require an explicit `.slnf` path; filters are not added to automatic solution discovery. The default Create format remains `.sln`. Analyze/Dependencies/Validate require the parent solution, not a filter. + +```typescript +await callTool("dotnet_solution", { + action: "Create", name: "Tests", output: "filters", format: "slnf", + parentSolution: "../MyApp.slnx" +}); +await callTool("dotnet_solution", { + action: "Add", solution: "filters/Tests.slnf", projects: ["MyApp.Tests/MyApp.Tests.csproj"] +}); +``` + Examples: ```typescript @@ -1073,6 +1097,23 @@ await callTool("dotnet_sdk", { }); ``` +On SDK 11+, `InstallTemplatePack` accepts `prerelease: true` to include preview versions when selecting the latest template package. An explicit `templateVersion` or inline `Package@version` still selects that exact version. + +The existing Project New `additionalOptions` supports the SDK 11 test templates without extra tool parameters: + +```typescript +await callTool("dotnet_project", { + action: "New", template: "xunit", name: "MyTests", framework: "net11.0", + additionalOptions: "--xunit-version v3" +}); +await callTool("dotnet_project", { + action: "New", template: "nunit", name: "MyNUnitTests", framework: "net11.0", + additionalOptions: "--test-runner Microsoft.Testing.Platform" +}); +``` + +The SDK's MTP template post-actions can update the applicable `global.json` to select `Microsoft.Testing.Platform`, even with `--no-restore`; inspect that change before running other test projects. The pinned RC3 templates reject these MTP options with an explicit `net10.0` target despite advertising it in help, so the examples opt in to `net11.0`. Ordinary project creation keeps the server's .NET 10 LTS default. + #### dotnet_dev_certs - Developer Certificates and Secrets Manage HTTPS certificates and user secrets: **CertificateTrust**, **CertificateCheck**, **CertificateClean**, **CertificateExport**, **SecretsInit**, **SecretsSet**, **SecretsList**, **SecretsRemove**, **SecretsClear** @@ -1269,7 +1310,7 @@ See [.github/copilot-instructions.md](.github/copilot-instructions.md) for devel - **Cause**: Test runner mismatch or SDK version incompatibility - **Background**: The `--project` flag is only supported by [Microsoft Testing Platform (MTP)](https://learn.microsoft.com/dotnet/core/tools/dotnet-test-mtp). The legacy [VSTest](https://learn.microsoft.com/dotnet/core/tools/dotnet-test-vstest) runner uses positional arguments instead. - **Solution**: The MCP server now auto-detects the test runner from `global.json`: - 1. **Auto mode** (default): Add `{ "test": { "runner": "Microsoft.Testing.Platform" } }` to `global.json` if using MTP, otherwise it defaults to VSTest + 1. **Auto mode** (default): On SDK 11+, recognized `DOTNET_TEST_RUNNER` values override `global.json`; otherwise add `{ "test": { "runner": "Microsoft.Testing.Platform" } }` to `global.json` for MTP. With neither setting, the default is VSTest. 2. **Explicit mode**: Set `testRunner: "MicrosoftTestingPlatform"` or `testRunner: "VSTest"` when calling `dotnet_project` Test action 3. **Legacy parameter**: Use `useLegacyProjectArgument: true` (deprecated, use `testRunner: "VSTest"` instead) - **Verify support**: Run `dotnet test --help | grep -- --project` to check if your SDK supports the `--project` flag diff --git a/doc/ai-assistant-guide.md b/doc/ai-assistant-guide.md index d0055ce9..3be3e217 100644 --- a/doc/ai-assistant-guide.md +++ b/doc/ai-assistant-guide.md @@ -101,6 +101,24 @@ AI: Reads dotnet://templates resource > **📘 About Code Examples:** The workflow examples in this guide show raw `dotnet` CLI commands for clarity and universal understanding. When AI assistants execute these operations through the MCP server, they use **consolidated MCP tools** (e.g., `dotnet_project`, `dotnet_package`, `dotnet_ef`) with appropriate actions. +### .NET 11 SDK feature selection + +Use the existing tools rather than constructing a new CLI escape hatch: + +| Task | MCP arguments | +|---|---| +| Create a solution filter | `dotnet_solution`: Create, `format="slnf"`, explicit `parentSolution`, name/output | +| Edit filter membership | `dotnet_solution`: Add/List/Remove with explicit `solution="...slnf"` | +| Run with application environment | `dotnet_project`: Run, `environmentVariables` string map; works in foreground/background | +| Format one target framework | `dotnet_project`: Format, `framework="net10.0"` | +| Install latest preview templates | `dotnet_sdk`: InstallTemplatePack, `prerelease=true`; an explicit version remains exact | +| Create xUnit v3 tests | `dotnet_project`: New, `template="xunit"`, `framework="net11.0"`, `additionalOptions="--xunit-version v3"` | +| Create NUnit-on-MTP tests | `dotnet_project`: New, `template="nunit"`, `framework="net11.0"`, `additionalOptions="--test-runner Microsoft.Testing.Platform"` | + +These opt-ins depend on the active CLI SDK, not the server runtime. Filter creation requires an existing parent; relative parent paths are relative to the output directory. Default solution creation remains `.sln`, and filter paths are never auto-selected. + +Test Auto mode honors `DOTNET_TEST_RUNNER` on SDK 11+ before `global.json`. SDK MTP template post-actions can update `global.json` even with `--no-restore`; inspect the change. The pinned RC3 templates require the explicit .NET 11 target shown above for these options despite advertising .NET 10 in help. Do not pass file-based `.cs` apps into XML property/item editors. Dedicated test policy options, file-app editing, device-aware Watch, and NuGet source publication-age settings are not exposed by this increment. + ### 1. Creating a New Console Application **Simple Prompt:** @@ -275,7 +293,7 @@ dotnet add package ### 5. Solution Management -> **Note:** The `dotnet_solution` tool provides **full parity with `dotnet sln` / `dotnet solution` CLI commands**. All solution operations (create, add, list, remove) are available through the MCP server. +> **Note:** The `dotnet_solution` tool supports solution creation and membership operations (Create, Add, List, Remove), including explicit solution filters on SDK 11+. Use the parent solution for Analyze, Dependencies, and Validate. **Create Multi-Project Solution:** diff --git a/doc/error-diagnostics.md b/doc/error-diagnostics.md index a505c57b..b22e3c05 100644 --- a/doc/error-diagnostics.md +++ b/doc/error-diagnostics.md @@ -75,6 +75,12 @@ await callTool("dotnet_project", { ## Common Error Code Examples +### NETSDK1235: Custom .nuspec with PackAsTool + +.NET 11 warns when a tool project combines `PackAsTool=true` with `NuspecFile`. Custom `.nuspec` files can violate the required tool layout and identifiers. Remove `NuspecFile` to let the SDK generate the tool package. + +This is an SDK warning, not a server rejection: pack can still succeed. The server preserves the diagnostic and uses the exit code to determine success; a message on stderr alone does not turn a successful invocation into an MCP error. This code is passed through, not added to the enriched error-code catalog. + ### CS0246: Type or namespace not found **What it means:** The compiler can't find a type or namespace you're trying to use. diff --git a/doc/sdk-integration.md b/doc/sdk-integration.md index 389e932b..12770ce3 100644 --- a/doc/sdk-integration.md +++ b/doc/sdk-integration.md @@ -76,6 +76,22 @@ Provides framework validation, metadata, and project analysis: ## Helper Classes +### SDK-dependent CLI features + +The active CLI SDK is determined in the command's working directory, including its `global.json`, not from the MCP server target framework. Opt-in solution filters, Run `environmentVariables`, Format `framework`, and template installation `prerelease` require SDK 11+. Unsupported opt-ins return an application error instead of silently discarding arguments. Existing operations retain their defaults. + +Solution filter Create emits `dotnet new slnf --parent-solution`. The parent must exist, and relative parent paths are interpreted from the filter output directory. Add/List use the SDK CLI; Remove updates the filter's JSON project array while excluding in-place writers, preserving other JSON properties. The completed content is written to an adjacent temporary file and replaced only after a final content check; invalid input or cancellation before replacement leaves the original intact. This avoids an SDK 11 RC3 removal bug that compares filter-relative input paths against parent-relative entries and reports success without removing projects when the directories differ. Unknown requested entries and malformed filters fail without modifying the file. Remove retains the same destructive-operation confirmation as ordinary solutions. Solution analysis uses the parent `.sln`/`.slnx`; filters do not change workspace auto-discovery. + +Run builds the same safely quoted repeated `--environment KEY=VALUE` arguments for foreground and background execution before the application argument separator. These are application settings, not mutations of the server's environment. Format forwards the selected framework; SDK restore may still produce assets for other targets. + +Test Auto selection honors recognized, case-insensitive `DOTNET_TEST_RUNNER` values only on supporting SDKs, then uses `global.json`, then defaults to VSTest. Unknown or empty values do not select a runner. Explicit `testRunner` and the legacy selector retain precedence; SDK 11+ child execution receives the corresponding runner via request-scoped environment state, restored after execution. No global environment or configuration files are rewritten. + +Template installation `prerelease: true` includes preview versions only for automatic selection. Explicit versions remain exact; successful installations retain existing template cache invalidation and resource notifications. xUnit v3 and NUnit-on-MTP creation use Project New's existing `additionalOptions` and template-option discovery. On the pinned RC3 SDK, select `framework="net11.0"` explicitly: MTP generation with `net10.0` fails despite the help listing that framework. SDK template post-actions can update the applicable `global.json` test runner even when restore is skipped; this is a template side effect, not server-side test-runner detection rewriting configuration. + +Some .NET 11 behavior remains SDK-owned: an inherited `Configuration` supplies omitted `-c` defaults (explicit options win), watch crash recovery occurs on relevant file changes, and container publishing selects platform-native runtimes with Docker/Podman fallbacks. Set `LocalRegistry` in the project or publish profile to force a container runtime. The server does not implement a competing selector or restart loop. + +Dedicated test run-level controls/artifacts layout, file-app directive/reference editing, watch device/Aspire lifecycle support, and NuGet source minimum publication age policy are tracked separately. Existing XML project editors are not a file-based C# directive editor. See the [SDK feature overview](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-11/sdk) and [test runner precedence](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-test). + ### CachedResourceManager Located in `DotNetMcp/CachedResourceManager.cs`