From 37cba11e5d09252f62506aa0e9fdf994180d7acf Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Wed, 4 Nov 2026 17:51:49 +0330 Subject: [PATCH] =?UTF-8?q?Add=20Standalone=20MCP=20ASP.NET=20Core=20Serve?= =?UTF-8?q?r=20-=20=D8=AA=DA=A9=D9=85=DB=8C=D9=84=20Program=20=D9=88=20Sta?= =?UTF-8?q?rtup=20=D9=88=20=D8=AB=D8=A8=D8=AA=20=D8=B3=D8=B1=D9=88=DB=8C?= =?UTF-8?q?=D8=B3=E2=80=8C=D9=87=D8=A7=DB=8C=20=D9=BE=D8=A7=DB=8C=D9=87?= =?UTF-8?q?=D8=8C=20configuration=D8=8C=20CORS=D8=8C=20Swagger=20=D9=88=20?= =?UTF-8?q?=20=20=D8=A7=D8=AD=D8=B1=D8=A7=D8=B2=20=D9=87=D9=88=DB=8C=D8=AA?= =?UTF-8?q?/=D9=85=D8=AC=D9=88=D8=B2.=20-=20=D8=A7=D9=81=D8=B2=D9=88=D8=AF?= =?UTF-8?q?=D9=86=20McpController=20=D9=88=20StartupController.=20-=20?= =?UTF-8?q?=D8=A7=D9=81=D8=B2=D9=88=D8=AF=D9=86=20DI=20=D9=88=20=D8=A7?= =?UTF-8?q?=D8=A8=D8=B2=D8=A7=D8=B1=20XEchoTools.=20-=20=D8=A8=D9=87?= =?UTF-8?q?=E2=80=8C=D8=B1=D9=88=D8=B2=D8=B1=D8=B3=D8=A7=D9=86=DB=8C=20app?= =?UTF-8?q?settings=D8=8C=20launchSettings=20=D9=88=20xAiMcpServer.csproj.?= =?UTF-8?q?=20-=20=D8=AD=D8=B0=D9=81=20appsettings.Development.json=20?= =?UTF-8?q?=D8=A7=D8=B2=20=D9=88=D8=B6=D8=B9=DB=8C=D8=AA=20=DA=A9=D8=A7?= =?UTF-8?q?=D8=B1=DB=8C=20=D9=81=D8=B9=D9=84=DB=8C.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/McpController.cs | 21 ++++++ Controllers/StartupController.cs | 63 ++++++++++++++++ DI/DiExtensions.cs | 86 ++++++++++++++++++++++ Program.cs | 30 ++++---- Properties/launchSettings.json | 2 +- Startup.cs | 120 +++++++++++++++++++++++++++++-- Tools/XEchoTools.cs | 18 +++++ appsettings.Development.json | 9 --- appsettings.json | 36 +++++++++- xAiMcpServer.csproj | 44 ++++++++++++ 10 files changed, 398 insertions(+), 31 deletions(-) create mode 100644 Controllers/McpController.cs create mode 100644 Controllers/StartupController.cs create mode 100644 DI/DiExtensions.cs create mode 100644 Tools/XEchoTools.cs delete mode 100644 appsettings.Development.json diff --git a/Controllers/McpController.cs b/Controllers/McpController.cs new file mode 100644 index 0000000..a622988 --- /dev/null +++ b/Controllers/McpController.cs @@ -0,0 +1,21 @@ +using xCommons.Providers; +using xAiService.Interfaces; +using xAiService.Controllers; +using xCommons.Configurations; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiMcpServer.Controllers +{ + public class McpController : XAiMcpControllerBase + { + public McpController( + IXAiMcpHandler mcpHandler, + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) + { } + } +} \ No newline at end of file diff --git a/Controllers/StartupController.cs b/Controllers/StartupController.cs new file mode 100644 index 0000000..db92745 --- /dev/null +++ b/Controllers/StartupController.cs @@ -0,0 +1,63 @@ +using xCommons.Providers; +using xCommons.Extensions; +using xCommons.Controllers; +using xExceptions.Constants; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + /// + /// Runing when application start ... + /// + [Route("")] + [AllowAnonymous] + public class StartupController : XBaseController + { + + public StartupController( + ILogger logger, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider + ) : base( + logger, + appConfiguration, + validationProvider + ) + { } + + /// + /// Show Configured Welcome Message + /// + /// + [HttpGet("")] + [AllowAnonymous] + public virtual ActionResult Index() + { + // + var controllerName = GetControllerName(); + var message = $"{AppConfiguration.WelcomeMessage}"; + + // + return Ok(message); + } + + /// + /// Global Exception Handler Endpoint (Production) ... + /// Returns a Generic Error without Leaking Exception Details ... + /// + /// + [AllowAnonymous] + [Route("error")] + [ApiExplorerSettings(IgnoreApi = true)] + public virtual ActionResult Error() + { + // + var error = XException.ActionFailed.ToXError(); + return StatusCode(StatusCodes.Status500InternalServerError, error); + } + } +} \ No newline at end of file diff --git a/DI/DiExtensions.cs b/DI/DiExtensions.cs new file mode 100644 index 0000000..85d1fbb --- /dev/null +++ b/DI/DiExtensions.cs @@ -0,0 +1,86 @@ +using xIdentityHelper; +using xCommons.Extensions; +using xCommons.Authorization; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiMcpServer.DI +{ + public static class DiExtensions + { + /// + /// Register Authorization Policies + /// + /// + /// + public static void AddXAuthorization( + this IServiceCollection services, + IDictionary policies = null + ) + { + // + services.AddAuthorization(options => + { + // + if (!policies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = policies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + + // + var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); + if (!xPolicies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = xPolicies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + }); + + // + services.AddSingleton(); + } + + /// + /// Use Forward Headers Options for resolving behind a proxy issues ... + /// + /// + /// + public static void UseXForwardOptions(this IApplicationBuilder source) + { + // + var forwardOptions = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, + RequireHeaderSymmetry = false + }; + + // + forwardOptions.KnownNetworks.Clear(); + forwardOptions.KnownProxies.Clear(); + + // + // ref: https://github.com/aspnet/Docs/issues/2384 + source.UseForwardedHeaders(forwardOptions); + } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index b084125..efb709d 100644 --- a/Program.cs +++ b/Program.cs @@ -1,11 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; +using Grapevine; namespace xAiMcpServer { @@ -13,14 +7,20 @@ namespace xAiMcpServer { public static void Main(string[] args) { - CreateHostBuilder(args).Build().Run(); - } + // + var server = RestServerBuilder + .From() + .Build(); + + // + server.Start(); - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + // + Console.WriteLine("MCP Server running on https://localhost:7001/mcp"); + Console.ReadLine(); + + // + server.Stop(); + } } } diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json index 9c87c8e..f4f59c2 100644 --- a/Properties/launchSettings.json +++ b/Properties/launchSettings.json @@ -21,7 +21,7 @@ "commandName": "Project", "launchBrowser": true, "launchUrl": "weatherforecast", - "applicationUrl": "https://localhost:5001;http://localhost:5000", + "applicationUrl": "https://localhost:7001;http://localhost:7000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/Startup.cs b/Startup.cs index aff468d..1f803b7 100644 --- a/Startup.cs +++ b/Startup.cs @@ -1,8 +1,22 @@ +using System; +using System.IO; +using Grapevine; +using System.Net.Http; +using xAiMcpServer.DI; +using Newtonsoft.Json; +using System.Reflection; +using xIdentityService.DI; +using xCommons.Extensions; +using xAiService.Extensions; +using xCommons.Configurations; +using Grapevine.Extensions.Mcp; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; +using Newtonsoft.Json.Serialization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using IdentityModel.AspNetCore.OAuth2Introspection; namespace xAiMcpServer { @@ -15,26 +29,124 @@ namespace xAiMcpServer public IConfiguration Configuration { get; } - // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddControllers(); + // + // Register MCP Handler ... + services.AddXAiMcpHandler(); + + // + // Register Validation Provider and all XCommons Module Services ... + services.AddXCommons(Configuration); + + // + // Register App Configuration ... + services.AddXAppConfiguration(Configuration); + var appConfiguration = services.GetRegisteredService(); + + // + // Register Allowed Origins ... + services.AddXCors(appConfiguration.AllowedOrigins); + + // + // Register Swagger ... + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + services.AddXSwagger(Configuration, xmlFilePath: xmlPath); + + // + // Add Api V1 Versioning ... + services.AddXApiV1Versioning(); + + // + // OAuthIntrospectin Http Client Handler ... + // this is for handling SSLErrors ... + services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) + .ConfigurePrimaryHttpMessageHandler(() => + { + return new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true + }; + }); + + // + // Register Authorizations ... + services.AddXAuthorization(); + + // + services.AddControllers() + .AddNewtonsoftJson(x => + { + x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + }); + + // + var lifeTime = ServiceLifetime.Scoped; + + // + // Register XIdentity Service ... + services.AddXIdentityService( + lifeTime: lifeTime, + configuration: Configuration + ); + + // + // Register MCP Server ... + services + .AddMcpServer() + .WithHttpTransport() + .WithToolsFromAssembly(); + } + + public void ConfigureServer(IRestServer server) + { + server.Prefixes.Add("https://localhost:7001/"); } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - if (env.IsDevelopment()) + // + // Configure the HTTP request pipeline ... + var isDevelopmentEnvironment = env.IsDevelopment(); + if (isDevelopmentEnvironment) { app.UseDeveloperExceptionPage(); } + else + { + app.UseHsts(); + } + // + // Force Https Redirection ... app.UseHttpsRedirection(); + // + // Use Swagger Middleware (Only in Development) ... + if (isDevelopmentEnvironment) + { + app.UseXSwagger(); + } + + // + // Using Cors (before Proxy so Browser Requests get CORS Headers) ... + app.UseXCors(); + + // + // Using Routing ... app.UseRouting(); + // + // Use xIdentityService (Authentication) ... + app.UseXIdentityService(); + + // + // Use Authorization ... app.UseAuthorization(); + // app.UseEndpoints(endpoints => { endpoints.MapControllers(); diff --git a/Tools/XEchoTools.cs b/Tools/XEchoTools.cs new file mode 100644 index 0000000..8d0bde5 --- /dev/null +++ b/Tools/XEchoTools.cs @@ -0,0 +1,18 @@ +using System.ComponentModel; +using ModelContextProtocol.Server; + +namespace xAiMcpServer.Tools +{ + [McpServerToolType] + public static class XEchoTools + { + [McpServerTool, + Description("Echoes the message back to the client.")] + public static string Echo(string message) + { + // + var result = $"hello {message}"; + return result; + } + } +} \ No newline at end of file diff --git a/appsettings.Development.json b/appsettings.Development.json deleted file mode 100644 index 8983e0f..0000000 --- a/appsettings.Development.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - } -} diff --git a/appsettings.json b/appsettings.json index d9d9a9b..be150f6 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,10 +1,42 @@ { + "Version": "0.1", + "Name": "xAiMcpServer", + "DefaultLanguage": "fa-IR", + "XPoweredValue": "SaherElmITCenter", + "WelcomeMessage": "Welcome to xSaherElm Project's AI Mcp Server", + "SwaggerConfiguration": { + "Version": "v1.0", + "Title": "xSaherElm AI Mcp Server", + "Description": "Complete AI Mcp Server Documentation", + "Contact": { + "Name": "Hadi Khazaee Asl", + "Email": "hadi_khazaee_asl@yahoo.com", + "Url": "https://www.saherelm.ir" + } + }, + "AllowedOrigins": [ + "http://localhost:6000", + "https://localhost:6001", + "http://api.saherelm.ir", + "https://api.saherelm.ir", + "http://api.saherelmhub.ir", + "https://api.saherelmhub.ir" + ], + "IdentityServiceConfiguration": { + "Authority": "https://localhost:4001", + "ApiName": "xSaherElmAPI", + "ApiSecret": "s@H@1694056", + "ClientId": "xSaherElmAPIClient", + "ClientSecret": "s@H@1694056", + "XPoweredValue": "SaherElmITCenter", + "XRevisionSecretKey": "SaherElmITCenter@1694056", + "DefaultClientTimeout": -1 + }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } - }, - "AllowedHosts": "*" + } } diff --git a/xAiMcpServer.csproj b/xAiMcpServer.csproj index d12c450..d7836df 100644 --- a/xAiMcpServer.csproj +++ b/xAiMcpServer.csproj @@ -1,8 +1,52 @@ + + 1.0.0 + 12.0 + Hadi Khazaee Asl + SaherElm IT Center + xSaherElm.xAiMcpServer netcoreapp3.1 + + + a WebAPI Project which Provides all Business Logic of MCP Tools for xSaherElm Project's AI. + + + + icon.png + + + false + false + + + + + + + + + + + + + + + + + + + + + + + + $(NoWarn);1591 + true + true +