ToolResponse.cs (3252B)
1 // ----------------------------------------------------------------------------- 2 // <copyright file="ToolResponse.cs" company="Microsoft Corporation"> 3 // Copyright (c) Microsoft Corporation. Licensed under the MIT License. 4 // </copyright> 5 // ----------------------------------------------------------------------------- 6 7 namespace WinGetMCPServer.Response 8 { 9 using Microsoft.WinGet.SharedLib.PolicySettings; 10 using ModelContextProtocol.Protocol; 11 using System.Text.Json; 12 using System.Text.Json.Serialization; 13 using WinGetMCPServer.Exceptions; 14 using static System.Runtime.InteropServices.JavaScript.JSType; 15 16 /// <summary> 17 /// Contains reusable responses for tools. 18 /// </summary> 19 internal static class ToolResponse 20 { 21 /// <summary> 22 /// Checks whether the server is disabled by group policy. 23 /// </summary> 24 public static void CheckGroupPolicy() 25 { 26 if (!GroupPolicy.GetInstance().IsEnabled(Policy.McpServer)) 27 { 28 throw new ToolResponseException(new CallToolResult() 29 { 30 IsError = true, 31 Content = [new TextContentBlock() { Text = "The Windows Package Manager MCP server is disabled by group policy." }] 32 }); 33 } 34 } 35 36 /// <summary> 37 /// Constructs a response from an object. 38 /// </summary> 39 /// <param name="value">The object to return in the response.</param> 40 /// <param name="isError">Whether or not the response is an error.</param> 41 /// <returns>The response.</returns> 42 public static CallToolResult FromObject(object value, bool isError = false) 43 { 44 return FromObject(value, isError, GetDefaultJsonOptions()); 45 } 46 47 /// <summary> 48 /// Constructs a response from an object. 49 /// </summary> 50 /// <param name="value">The object to return in the response.</param> 51 /// <param name="isError">Whether or not the response is an error.</param> 52 /// <param name="jsonSerializerOptions">The JSON serializer options for serializing the object.</param> 53 /// <returns>The response.</returns> 54 public static CallToolResult FromObject(object value, bool isError, JsonSerializerOptions jsonSerializerOptions) 55 { 56 return new CallToolResult() 57 { 58 IsError = isError, 59 Content = [new TextContentBlock() { Text = JsonSerializer.Serialize(value, GetDefaultJsonOptions()) }] 60 }; 61 } 62 63 /// <summary> 64 /// Gets the default serialization options. 65 /// </summary> 66 /// <returns>The default serialization options.</returns> 67 public static JsonSerializerOptions GetDefaultJsonOptions() 68 { 69 return new JsonSerializerOptions() 70 { 71 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, 72 PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 73 Converters = 74 { 75 new JsonStringEnumConverter(), 76 }, 77 }; 78 } 79 } 80 }