-
Notifications
You must be signed in to change notification settings - Fork 708
Hide experimental types from external source generators using internal property pattern #1301
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using System.Collections.Immutable; | ||
|
|
||
| namespace ModelContextProtocol.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Suppresses MCPEXP001 diagnostics in source-generated code. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The MCP SDK uses internal serialization properties to handle serialization of experimental types. | ||
| /// When consumers define their own <c>JsonSerializerContext</c>, the System.Text.Json source generator | ||
| /// on .NET 8 and .NET 9 emits property metadata referencing experimental types (even for | ||
| /// <c>[JsonIgnore]</c> properties), which triggers MCPEXP001 diagnostics in the generated code. | ||
| /// </para> | ||
| /// <para> | ||
| /// This suppressor suppresses MCPEXP001 only in source-generated files (identified by <c>.g.cs</c> file extension), | ||
| /// so that hand-written user code that directly references experimental types still produces the diagnostic. | ||
| /// </para> | ||
| /// </remarks> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class MCPEXP001Suppressor : DiagnosticSuppressor | ||
| { | ||
| private static readonly SuppressionDescriptor SuppressInGeneratedCode = new( | ||
| id: "MCP_MCPEXP001_GENERATED", | ||
| suppressedDiagnosticId: "MCPEXP001", | ||
| justification: "MCPEXP001 is suppressed in source-generated code because the experimental type reference originates from the MCP SDK's internal serialization infrastructure, not from user code."); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => | ||
| ImmutableArray.Create(SuppressInGeneratedCode); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override void ReportSuppressions(SuppressionAnalysisContext context) | ||
| { | ||
| foreach (Diagnostic diagnostic in context.ReportedDiagnostics) | ||
| { | ||
| if (diagnostic.Id == "MCPEXP001" && IsInGeneratedCode(diagnostic)) | ||
| { | ||
| context.ReportSuppression(Suppression.Create(SuppressInGeneratedCode, diagnostic)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static bool IsInGeneratedCode(Diagnostic diagnostic) | ||
| { | ||
| string? filePath = diagnostic.Location.SourceTree?.FilePath; | ||
| return filePath is not null && filePath.EndsWith(".g.cs", StringComparison.OrdinalIgnoreCase); | ||
| } | ||
|
MackinnonBuck marked this conversation as resolved.
Outdated
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
159 changes: 159 additions & 0 deletions
159
tests/ModelContextProtocol.Analyzers.Tests/MCPEXP001SuppressorTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using System.Collections.Immutable; | ||
| using Xunit; | ||
|
|
||
| namespace ModelContextProtocol.Analyzers.Tests; | ||
|
|
||
| public class MCPEXP001SuppressorTests | ||
| { | ||
| [Fact] | ||
| public async Task Suppressor_InGeneratedCode_SuppressesMCPEXP001() | ||
| { | ||
| // Simulate source-generated code (e.g., STJ source gen) that references an experimental type. | ||
| // The file path ends with .g.cs to indicate it's generated. | ||
| var result = await RunSuppressorAsync( | ||
| source: """ | ||
| using ExperimentalTypes; | ||
|
|
||
| namespace Generated | ||
| { | ||
| public static class SerializerHelper | ||
| { | ||
| public static object Create() => new ExperimentalClass(); | ||
| } | ||
| } | ||
| """, | ||
| filePath: "Generated.g.cs", | ||
| additionalSource: GetExperimentalTypeDefinition(), | ||
| additionalFilePath: "ExperimentalTypes.cs"); | ||
|
|
||
| // MCPEXP001 should exist before the suppressor runs | ||
| Assert.Contains(result.BeforeSuppression, d => d.Id == "MCPEXP001"); | ||
|
|
||
| // After suppression, MCPEXP001 should be gone from the results | ||
| Assert.DoesNotContain(result.AfterSuppression, d => d.Id == "MCPEXP001"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task Suppressor_InHandWrittenCode_DoesNotSuppressMCPEXP001() | ||
| { | ||
| // Hand-written user code referencing an experimental type. | ||
| // The file path does NOT end with .g.cs. | ||
| var result = await RunSuppressorAsync( | ||
| source: """ | ||
| using ExperimentalTypes; | ||
|
|
||
| namespace UserCode | ||
| { | ||
| public static class MyHelper | ||
| { | ||
| public static object Create() => new ExperimentalClass(); | ||
| } | ||
| } | ||
| """, | ||
| filePath: "MyHelper.cs", | ||
| additionalSource: GetExperimentalTypeDefinition(), | ||
| additionalFilePath: "ExperimentalTypes.cs"); | ||
|
|
||
| // MCPEXP001 should exist before the suppressor runs | ||
| Assert.Contains(result.BeforeSuppression, d => d.Id == "MCPEXP001"); | ||
|
|
||
| // It should still be present after the suppressor runs (not suppressed) | ||
| Assert.Contains(result.AfterSuppression, d => d.Id == "MCPEXP001"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task Suppressor_MixedGeneratedAndHandWritten_OnlySuppressesGenerated() | ||
| { | ||
| var result = await RunSuppressorAsync( | ||
| [ | ||
| (GetExperimentalTypeDefinition(), "ExperimentalTypes.cs"), | ||
| (""" | ||
| using ExperimentalTypes; | ||
| namespace Generated | ||
| { | ||
| public static class GeneratedHelper | ||
| { | ||
| public static object Create() => new ExperimentalClass(); | ||
| } | ||
| } | ||
| """, "Generated.g.cs"), | ||
| (""" | ||
| using ExperimentalTypes; | ||
| namespace UserCode | ||
| { | ||
| public static class UserHelper | ||
| { | ||
| public static object Create() => new ExperimentalClass(); | ||
| } | ||
| } | ||
| """, "UserCode.cs"), | ||
| ]); | ||
|
|
||
| // Should have MCPEXP001 in both files before suppression | ||
| Assert.Equal(2, result.BeforeSuppression.Count(d => d.Id == "MCPEXP001")); | ||
|
|
||
| // After suppression: only the hand-written one should remain | ||
| var remaining = result.AfterSuppression.Where(d => d.Id == "MCPEXP001").ToList(); | ||
| Assert.Single(remaining); | ||
| Assert.Equal("UserCode.cs", remaining[0].Location.SourceTree?.FilePath); | ||
| } | ||
|
|
||
| private static string GetExperimentalTypeDefinition() => """ | ||
| using System.Diagnostics.CodeAnalysis; | ||
|
|
||
| namespace ExperimentalTypes | ||
| { | ||
| [Experimental("MCPEXP001")] | ||
| public class ExperimentalClass { } | ||
| } | ||
| """; | ||
|
|
||
| private static Task<SuppressorResult> RunSuppressorAsync( | ||
| string source, | ||
| string filePath, | ||
| string additionalSource, | ||
| string additionalFilePath) | ||
| { | ||
| return RunSuppressorAsync([(additionalSource, additionalFilePath), (source, filePath)]); | ||
| } | ||
|
|
||
| private static async Task<SuppressorResult> RunSuppressorAsync(params (string Source, string FilePath)[] sources) | ||
| { | ||
| var syntaxTrees = sources.Select( | ||
| s => CSharpSyntaxTree.ParseText(s.Source, path: s.FilePath)).ToArray(); | ||
|
|
||
| var runtimePath = Path.GetDirectoryName(typeof(object).Assembly.Location)!; | ||
| List<MetadataReference> referenceList = | ||
| [ | ||
| MetadataReference.CreateFromFile(typeof(object).Assembly.Location), | ||
| MetadataReference.CreateFromFile(Path.Combine(runtimePath, "System.Runtime.dll")), | ||
| MetadataReference.CreateFromFile(Path.Combine(runtimePath, "netstandard.dll")), | ||
| ]; | ||
|
|
||
| var compilation = CSharpCompilation.Create( | ||
| "TestAssembly", | ||
| syntaxTrees, | ||
| referenceList, | ||
| new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); | ||
|
|
||
| var beforeSuppression = compilation.GetDiagnostics(); | ||
| var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(new MCPEXP001Suppressor()); | ||
| var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers); | ||
| var afterSuppression = await compilationWithAnalyzers.GetAllDiagnosticsAsync(default); | ||
|
|
||
| return new SuppressorResult | ||
| { | ||
| BeforeSuppression = beforeSuppression, | ||
| AfterSuppression = afterSuppression, | ||
| }; | ||
| } | ||
|
|
||
| private class SuppressorResult | ||
| { | ||
| public ImmutableArray<Diagnostic> BeforeSuppression { get; set; } = []; | ||
| public ImmutableArray<Diagnostic> AfterSuppression { get; set; } = []; | ||
| } | ||
| } |
20 changes: 20 additions & 0 deletions
20
tests/ModelContextProtocol.SuppressorRegressionTest/ExperimentalPropertyRegressionContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| using System.Text.Json.Serialization; | ||
| using ModelContextProtocol.Protocol; | ||
|
|
||
| namespace ModelContextProtocol.SuppressorRegressionTest; | ||
|
|
||
| /// <summary> | ||
| /// This file validates that the MCPEXP001 diagnostic suppressor works correctly. | ||
| /// By including MCP protocol types that have experimental properties in a | ||
| /// <see cref="JsonSerializerContext"/>, we verify that the source generator does | ||
| /// not produce unsuppressed MCPEXP001 diagnostics. If the suppressor is removed | ||
| /// or broken, this project will fail to build. | ||
| /// </summary> | ||
| [JsonSerializable(typeof(Tool))] | ||
| [JsonSerializable(typeof(ServerCapabilities))] | ||
| [JsonSerializable(typeof(ClientCapabilities))] | ||
| [JsonSerializable(typeof(CallToolResult))] | ||
| [JsonSerializable(typeof(CallToolRequestParams))] | ||
| [JsonSerializable(typeof(CreateMessageRequestParams))] | ||
| [JsonSerializable(typeof(ElicitRequestParams))] | ||
| internal partial class ExperimentalPropertyRegressionContext : JsonSerializerContext; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.