|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Net; |
| 5 | +using System.Text; |
| 6 | +using System.Web; |
| 7 | +using Microsoft.Extensions.Configuration; |
| 8 | +using Microsoft.Extensions.DependencyInjection; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | +using Microsoft.SemanticKernel; |
| 11 | +using Microsoft.SemanticKernel.Agents; |
| 12 | +using Microsoft.SemanticKernel.Connectors.OpenAI; |
| 13 | +using ModelContextProtocol.Client; |
| 14 | + |
| 15 | +var config = new ConfigurationBuilder() |
| 16 | + .AddUserSecrets<Program>() |
| 17 | + .AddEnvironmentVariables() |
| 18 | + .Build(); |
| 19 | + |
| 20 | +if (config["OpenAI:ApiKey"] is not { } apiKey) |
| 21 | +{ |
| 22 | + Console.Error.WriteLine("Please provide a valid OpenAI:ApiKey to run this sample. See the associated README.md for more details."); |
| 23 | + return; |
| 24 | +} |
| 25 | + |
| 26 | +// We can customize a shared HttpClient with a custom handler if desired |
| 27 | +using var sharedHandler = new SocketsHttpHandler |
| 28 | +{ |
| 29 | + PooledConnectionLifetime = TimeSpan.FromMinutes(2), |
| 30 | + PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1) |
| 31 | +}; |
| 32 | +using var httpClient = new HttpClient(sharedHandler); |
| 33 | + |
| 34 | +var consoleLoggerFactory = LoggerFactory.Create(builder => |
| 35 | +{ |
| 36 | + builder.AddConsole(); |
| 37 | +}); |
| 38 | + |
| 39 | +// Create SSE client transport for the MCP server |
| 40 | +var serverUrl = "http://localhost:7071/"; |
| 41 | +var transport = new SseClientTransport(new() |
| 42 | +{ |
| 43 | + Endpoint = new Uri(serverUrl), |
| 44 | + Name = "Secure Weather Client", |
| 45 | + OAuth = new() |
| 46 | + { |
| 47 | + ClientName = "ProtectedMcpClient", |
| 48 | + RedirectUri = new Uri("http://localhost:1179/callback"), |
| 49 | + AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync, |
| 50 | + } |
| 51 | +}, httpClient, consoleLoggerFactory); |
| 52 | + |
| 53 | +// Create an MCPClient for the protected MCP server |
| 54 | +await using var mcpClient = await McpClientFactory.CreateAsync(transport, loggerFactory: consoleLoggerFactory); |
| 55 | + |
| 56 | +// Retrieve the list of tools available on the GitHub server |
| 57 | +var tools = await mcpClient.ListToolsAsync().ConfigureAwait(false); |
| 58 | +foreach (var tool in tools) |
| 59 | +{ |
| 60 | + Console.WriteLine($"{tool.Name}: {tool.Description}"); |
| 61 | +} |
| 62 | + |
| 63 | +// Prepare and build kernel with the MCP tools as Kernel functions |
| 64 | +var builder = Kernel.CreateBuilder(); |
| 65 | +builder.Services |
| 66 | + .AddLogging(c => c.AddDebug().SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace)) |
| 67 | + .AddOpenAIChatCompletion( |
| 68 | + modelId: config["OpenAI:ChatModelId"] ?? "gpt-4o-mini", |
| 69 | + apiKey: apiKey); |
| 70 | +Kernel kernel = builder.Build(); |
| 71 | +kernel.Plugins.AddFromFunctions("WeatherApi", tools.Select(aiFunction => aiFunction.AsKernelFunction())); |
| 72 | + |
| 73 | +// Enable automatic function calling |
| 74 | +OpenAIPromptExecutionSettings executionSettings = new() |
| 75 | +{ |
| 76 | + Temperature = 0, |
| 77 | + FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(options: new() { RetainArgumentTypes = true }) |
| 78 | +}; |
| 79 | + |
| 80 | +// Test using weather tools |
| 81 | +var prompt = "Get current weather alerts for New York?"; |
| 82 | +var result = await kernel.InvokePromptAsync(prompt, new(executionSettings)).ConfigureAwait(false); |
| 83 | +Console.WriteLine($"\n\n{prompt}\n{result}"); |
| 84 | + |
| 85 | +// Define the agent |
| 86 | +ChatCompletionAgent agent = new() |
| 87 | +{ |
| 88 | + Instructions = "Answer questions about weather alerts for US states.", |
| 89 | + Name = "WeatherAgent", |
| 90 | + Kernel = kernel, |
| 91 | + Arguments = new KernelArguments(executionSettings), |
| 92 | +}; |
| 93 | + |
| 94 | +// Respond to user input, invoking functions where appropriate. |
| 95 | +ChatMessageContent response = await agent.InvokeAsync("Get the current weather alerts for Washington?").FirstAsync(); |
| 96 | +Console.WriteLine($"\n\nResponse from WeatherAgent:\n{response.Content}"); |
| 97 | + |
| 98 | +/// <summary> |
| 99 | +/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser. |
| 100 | +/// This implementation demonstrates how SDK consumers can provide their own authorization flow. |
| 101 | +/// </summary> |
| 102 | +/// <param name="authorizationUrl">The authorization URL to open in the browser.</param> |
| 103 | +/// <param name="redirectUri">The redirect URI where the authorization code will be sent.</param> |
| 104 | +/// <param name="cancellationToken">The cancellation token.</param> |
| 105 | +/// <returns>The authorization code extracted from the callback, or null if the operation failed.</returns> |
| 106 | +static async Task<string?> HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken) |
| 107 | +{ |
| 108 | + Console.WriteLine("Starting OAuth authorization flow..."); |
| 109 | + Console.WriteLine($"Opening browser to: {authorizationUrl}"); |
| 110 | + |
| 111 | + var listenerPrefix = redirectUri.GetLeftPart(UriPartial.Authority); |
| 112 | + if (!listenerPrefix.EndsWith("/", StringComparison.InvariantCultureIgnoreCase)) |
| 113 | + { |
| 114 | + listenerPrefix += "/"; |
| 115 | + } |
| 116 | + |
| 117 | + using var listener = new HttpListener(); |
| 118 | + listener.Prefixes.Add(listenerPrefix); |
| 119 | + |
| 120 | + try |
| 121 | + { |
| 122 | + listener.Start(); |
| 123 | + Console.WriteLine($"Listening for OAuth callback on: {listenerPrefix}"); |
| 124 | + |
| 125 | + OpenBrowser(authorizationUrl); |
| 126 | + |
| 127 | + var context = await listener.GetContextAsync(); |
| 128 | + var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty); |
| 129 | + var code = query["code"]; |
| 130 | + var error = query["error"]; |
| 131 | + |
| 132 | + string responseHtml = "<html><body><h1>Authentication complete</h1><p>You can close this window now.</p></body></html>"; |
| 133 | + byte[] buffer = Encoding.UTF8.GetBytes(responseHtml); |
| 134 | + context.Response.ContentLength64 = buffer.Length; |
| 135 | + context.Response.ContentType = "text/html"; |
| 136 | + context.Response.OutputStream.Write(buffer, 0, buffer.Length); |
| 137 | + context.Response.Close(); |
| 138 | + |
| 139 | + if (!string.IsNullOrEmpty(error)) |
| 140 | + { |
| 141 | + Console.WriteLine($"Auth error: {error}"); |
| 142 | + return null; |
| 143 | + } |
| 144 | + |
| 145 | + if (string.IsNullOrEmpty(code)) |
| 146 | + { |
| 147 | + Console.WriteLine("No authorization code received"); |
| 148 | + return null; |
| 149 | + } |
| 150 | + |
| 151 | + Console.WriteLine("Authorization code received successfully."); |
| 152 | + return code; |
| 153 | + } |
| 154 | + catch (Exception ex) |
| 155 | + { |
| 156 | + Console.WriteLine($"Error getting auth code: {ex.Message}"); |
| 157 | + return null; |
| 158 | + } |
| 159 | + finally |
| 160 | + { |
| 161 | + if (listener.IsListening) |
| 162 | + { |
| 163 | + listener.Stop(); |
| 164 | + } |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +/// <summary> |
| 169 | +/// Opens the specified URL in the default browser. |
| 170 | +/// </summary> |
| 171 | +/// <param name="url">The URL to open.</param> |
| 172 | +static void OpenBrowser(Uri url) |
| 173 | +{ |
| 174 | + try |
| 175 | + { |
| 176 | + var psi = new ProcessStartInfo |
| 177 | + { |
| 178 | + FileName = url.ToString(), |
| 179 | + UseShellExecute = true |
| 180 | + }; |
| 181 | + Process.Start(psi); |
| 182 | + } |
| 183 | + catch (Exception ex) |
| 184 | + { |
| 185 | + Console.WriteLine($"Error opening browser. {ex.Message}"); |
| 186 | + Console.WriteLine($"Please manually open this URL: {url}"); |
| 187 | + } |
| 188 | +} |
0 commit comments