|
| 1 | +# Source Generator Example |
| 2 | + |
| 3 | +This example demonstrates how to use the XmlToDescriptionGenerator source generator. |
| 4 | + |
| 5 | +## Without Source Generator (Traditional Approach) |
| 6 | + |
| 7 | +```csharp |
| 8 | +using ModelContextProtocol.Server; |
| 9 | +using System.ComponentModel; |
| 10 | + |
| 11 | +[McpServerToolType] |
| 12 | +public class WeatherTools |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Get the current weather for a location. |
| 16 | + /// </summary> |
| 17 | + [McpServerTool] |
| 18 | + [Description("Get the current weather for a location.")] // Duplication! |
| 19 | + public static string GetWeather(string location) |
| 20 | + { |
| 21 | + return $"Weather for {location}: Sunny, 72°F"; |
| 22 | + } |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +## With Source Generator (Recommended) |
| 27 | + |
| 28 | +```csharp |
| 29 | +using ModelContextProtocol.Server; |
| 30 | + |
| 31 | +[McpServerToolType] |
| 32 | +public partial class WeatherTools |
| 33 | +{ |
| 34 | + /// <summary> |
| 35 | + /// Get the current weather for a location. |
| 36 | + /// </summary> |
| 37 | + [McpServerTool] |
| 38 | + public static partial string GetWeather(string location) |
| 39 | + { |
| 40 | + return $"Weather for {location}: Sunny, 72°F"; |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +The source generator automatically creates a partial method declaration with the `[Description]` attribute: |
| 46 | + |
| 47 | +```csharp |
| 48 | +// <auto-generated/> |
| 49 | +#nullable enable |
| 50 | + |
| 51 | +using System.ComponentModel; |
| 52 | +using ModelContextProtocol.Server; |
| 53 | + |
| 54 | +namespace YourNamespace; |
| 55 | + |
| 56 | +public partial class WeatherTools |
| 57 | +{ |
| 58 | + [Description("Get the current weather for a location.")] |
| 59 | + public static partial string GetWeather(string location); |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +## Key Changes Required |
| 64 | + |
| 65 | +1. Make the class `partial` |
| 66 | +2. Make the method `partial` |
| 67 | +3. Remove any existing `[Description]` attribute |
| 68 | +4. Keep your XML documentation comments |
| 69 | + |
| 70 | +The Description attribute will be automatically generated from your XML `<summary>` element! |
0 commit comments