├── src ├── Mcp.Links.Http │ ├── App.razor │ ├── GlobalUsings.cs │ ├── Resources │ │ ├── I18n.cs │ │ ├── I18n.zh-CN.resx │ │ └── I18n.resx │ ├── wwwroot │ │ ├── favicon.ico │ │ ├── favicon.png │ │ ├── icon-1.png │ │ ├── icon-2.png │ │ ├── appsettings.json │ │ ├── css │ │ │ └── site.css │ │ ├── app.css │ │ ├── assets │ │ │ └── logo.svg │ │ ├── index.html │ │ └── lib │ │ │ └── bootstrap │ │ │ └── dist │ │ │ └── css │ │ │ ├── bootstrap-reboot.min.css │ │ │ └── bootstrap-reboot.rtl.min.css │ ├── appsettings.Development.json │ ├── Pages │ │ ├── Exception │ │ │ ├── 403 │ │ │ │ └── 403.razor │ │ │ ├── 404 │ │ │ │ └── 404.razor │ │ │ └── 500 │ │ │ │ └── 500.razor │ │ ├── Result │ │ │ ├── Fail │ │ │ │ ├── Fail.razor.css │ │ │ │ └── Fail.razor │ │ │ └── Success │ │ │ │ ├── Success.razor.css │ │ │ │ └── Success.razor │ │ ├── _Host.cshtml │ │ ├── Welcome.razor.css │ │ ├── Mcp │ │ │ ├── Store.razor.css │ │ │ └── ServerDetail.razor.cs │ │ ├── Welcome.razor.cs │ │ └── Welcome.razor │ ├── Routes.razor │ ├── _Imports.razor │ ├── appsettings.json │ ├── Properties │ │ └── launchSettings.json │ ├── client-apps.json │ ├── Extensions │ │ └── AppKeyAuthenticationExtensions.cs │ ├── Mcp.Links.Http.csproj │ ├── McpClientStartupService.cs │ ├── mcp.json │ ├── Layouts │ │ ├── BasicLayout.razor │ │ └── BasicLayout.razor.cs │ ├── Authentication │ │ └── AppKeyAuthenticationHandler.cs │ ├── Services │ │ ├── IMcpClientAppService.cs │ │ ├── IMcpStoreService.cs │ │ ├── IMcpServerService.cs │ │ ├── IMcpInspectorService.cs │ │ └── McpClientAppService.cs │ └── Program.cs └── Mcp.Links │ ├── Configuration │ ├── McpClientConfigOptions.cs │ ├── McpServerConfigOptions.cs │ ├── McpClientConfig.cs │ ├── McpServerConfigOptionsValidator.cs │ └── McpServerConfig.cs │ ├── Mcp.Links.csproj │ ├── Aggregation │ ├── McpClientTransportFactory.cs │ ├── AggregatedMcpServerHostedService.cs │ ├── McpClientWrapper.cs │ ├── McpClientInitializer.cs │ ├── AggregatedMcpServerBuilderExtensions.cs │ ├── McpToolsHandler.cs │ ├── AggregatedMcpServerFactory.cs │ └── McpClientsFactory.cs │ └── Throw.cs ├── doc └── imgs │ └── intro.png ├── Mcp.Links.slnx ├── .dockerignore ├── LICENSE.txt ├── .github └── workflows │ └── mcp-links-AutoDeployTrigger-50990fb5-be48-4371-939e-6c00f3306024.yml ├── .gitattributes ├── README_zh-cn.md ├── Dockerfile ├── README.md └── .gitignore /src/Mcp.Links.Http/App.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http 2 | 3 | -------------------------------------------------------------------------------- /doc/imgs/intro.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheng-jie/Mcp.Links/HEAD/doc/imgs/intro.png -------------------------------------------------------------------------------- /src/Mcp.Links.Http/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Mcp.Links.Http.Resources; 2 | 3 | global using AntDesign; -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Resources/I18n.cs: -------------------------------------------------------------------------------- 1 | namespace Mcp.Links.Http.Resources; 2 | 3 | 4 | internal class I18n 5 | { 6 | } -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheng-jie/Mcp.Links/HEAD/src/Mcp.Links.Http/wwwroot/favicon.ico -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheng-jie/Mcp.Links/HEAD/src/Mcp.Links.Http/wwwroot/favicon.png -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/icon-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheng-jie/Mcp.Links/HEAD/src/Mcp.Links.Http/wwwroot/icon-1.png -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/icon-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheng-jie/Mcp.Links/HEAD/src/Mcp.Links.Http/wwwroot/icon-2.png -------------------------------------------------------------------------------- /src/Mcp.Links.Http/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Mcp.Links.slnx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Exception/500/500.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http.Pages.Exception 2 | @page "/exception/500" 3 | 4 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Exception/404/404.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http.Pages.Exception 2 | @page "/exception/404" 3 | 4 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Exception/403/403.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http.Pages.Exception 2 | @page "/exception/403" 3 | 4 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Routes.razor: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Result/Fail/Fail.razor.css: -------------------------------------------------------------------------------- 1 | /* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */ 2 | /* stylelint-disable no-duplicate-selectors */ 3 | /* stylelint-disable */ 4 | /* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */ 5 | .error_icon { 6 | color: #ff4d4f; 7 | } 8 | .title__b__0 { 9 | margin-bottom: 16px; 10 | color: rgba(0, 0, 0, 0.85); 11 | font-weight: 500; 12 | font-size: 16px; 13 | } 14 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ProSettings": { 3 | "NavTheme": "dark", 4 | "Layout": "side", 5 | "ContentWidth": "Fluid", 6 | "FixedHeader": false, 7 | "FixSiderbar": true, 8 | "Title": "Ant Design Pro", 9 | "PrimaryColor": "daybreak", 10 | "ColorWeak": false, 11 | "SplitMenus": false, 12 | "HeaderRender": true, 13 | "FooterRender": true, 14 | "MenuRender": true, 15 | "MenuHeaderRender": true, 16 | "HeaderHeight": 48 17 | } 18 | } -------------------------------------------------------------------------------- /src/Mcp.Links/Configuration/McpClientConfigOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace Mcp.Links.Configuration; 6 | 7 | public class McpClientConfigOptions 8 | { 9 | /// 10 | /// Dictionary of MCP client configurations keyed by client ID. 11 | /// 12 | [JsonPropertyName("mcpClients")] 13 | [Required] 14 | public McpClientConfig[] McpClients { get; set; } = Array.Empty(); 15 | } 16 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using AntDesign 2 | @using AntDesign.Charts 3 | @using AntDesign.ProLayout 4 | @using System.Net.Http 5 | @using System.Net.Http.Json 6 | @using Microsoft.AspNetCore.Components.Forms 7 | @using Microsoft.AspNetCore.Components.Routing 8 | @using Microsoft.AspNetCore.Components.Web 9 | @using Microsoft.JSInterop 10 | @* @using Mcp.Links.Http 11 | @using Mcp.Links.Http.Layouts *@ 12 | @using AntDesign.Extensions.Localization 13 | @using System.Globalization 14 | 15 | @using global::Mcp.Links.Configuration 16 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Result/Success/Success.razor.css: -------------------------------------------------------------------------------- 1 | /* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */ 2 | /* stylelint-disable no-duplicate-selectors */ 3 | /* stylelint-disable */ 4 | /* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */ 5 | .title__b__1 { 6 | position: relative; 7 | color: rgba(0, 0, 0, 0.85); 8 | font-size: 12px; 9 | text-align: center; 10 | } 11 | .head-title { 12 | margin-bottom: 20px; 13 | color: rgba(0, 0, 0, 0.85); 14 | font-weight: 500px; 15 | font-size: 16px; 16 | } 17 | -------------------------------------------------------------------------------- /src/Mcp.Links/Configuration/McpServerConfigOptions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace Mcp.Links.Configuration; 5 | 6 | /// 7 | /// Represents the root configuration for MCP servers from mcp.json file. 8 | /// 9 | public class McpServerConfigOptions 10 | { 11 | /// 12 | /// Dictionary of MCP server configurations keyed by server ID. 13 | /// 14 | [JsonPropertyName("mcpServers")] 15 | [Required] 16 | public Dictionary McpServers { get; set; } = new(); 17 | } 18 | -------------------------------------------------------------------------------- /src/Mcp.Links/Mcp.Links.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "ProSettings": { 10 | "NavTheme": "light", 11 | "HeaderHeight": 48, 12 | "Layout": "top", 13 | "ContentWidth": "Fluid", 14 | "FixedHeader": false, 15 | "FixSiderbar": true, 16 | "Title": "MCP Links", 17 | "IconfontUrl": null, 18 | "PrimaryColor": "green", 19 | "ColorWeak": false, 20 | "SplitMenus": false, 21 | "HeaderRender": true, 22 | "FooterRender": false, 23 | "MenuRender": false, 24 | "MenuHeaderRender": true 25 | } 26 | } -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "http": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": true, 8 | "applicationUrl": "http://localhost:5146", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "dotnetRunMessages": true, 16 | "launchBrowser": true, 17 | "applicationUrl": "https://localhost:7272;http://localhost:5146", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/client-apps.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcpClients": [ 3 | { 4 | "appId": "default", 5 | "appKey": "361e3e36afc24e32a29763ffb593485c", 6 | "name": "default mcp client", 7 | "description": null, 8 | "mcpServerIds": [ 9 | "time" 10 | ] 11 | }, 12 | { 13 | "appId": "vscode", 14 | "appKey": "791c318d841d445d83b598b82222f04f", 15 | "name": "VS Code", 16 | "description": null, 17 | "mcpServerIds": [ 18 | "csharp-code-interceptor", 19 | "fetch", 20 | "spec-coding" 21 | ] 22 | }, 23 | { 24 | "appId": "cursor", 25 | "appKey": "f1baa4a7f7ad483dad2730abffdcd2c7", 26 | "name": "Cursor", 27 | "description": null, 28 | "mcpServerIds": [ 29 | "csharp-code-interceptor", 30 | "fetch", 31 | "spec-coding" 32 | ] 33 | } 34 | ] 35 | } -------------------------------------------------------------------------------- /src/Mcp.Links/Configuration/McpClientConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Mcp.Links.Configuration; 4 | 5 | public class McpClientConfig 6 | { 7 | 8 | /// 9 | /// The unique identifier for the client app. 10 | /// 11 | public required string AppId { get; set; } 12 | 13 | 14 | /// 15 | /// The key for the client app. 16 | /// 17 | public required string AppKey { get; set; } 18 | 19 | /// 20 | /// The name of the client app. 21 | /// 22 | public required string Name { get; set; } 23 | 24 | 25 | /// 26 | /// The description of the client app. 27 | /// 28 | public string? Description { get; set; } 29 | 30 | 31 | /// 32 | /// Gets or sets the list of MCP server IDs associated with the client app. 33 | /// 34 | public required string[] McpServerIds { get; set; } 35 | } 36 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Build artifacts 2 | bin/ 3 | obj/ 4 | 5 | # .dockerignore and Dockerfile 6 | .dockerignore 7 | Dockerfile 8 | 9 | # Version control 10 | .git/ 11 | .github/ 12 | .gitignore 13 | 14 | # IDE files 15 | .vs/ 16 | .vscode/ 17 | .idea/ 18 | *.user 19 | *.suo 20 | 21 | # OS files 22 | **/.DS_Store 23 | **/Thumbs.db 24 | 25 | # Node.js dependencies 26 | **/node_modules/ 27 | 28 | # Python cache 29 | **/__pycache__/ 30 | **/*.pyc 31 | **/*.pyo 32 | **/*.egg-info/ 33 | 34 | # Logs 35 | logs/ 36 | *.log 37 | 38 | # Temporary files 39 | temp/ 40 | tmp/ 41 | 42 | # Test results 43 | TestResults/ 44 | **/*.trx 45 | 46 | # Coverage reports 47 | coverage/ 48 | *.coverage 49 | 50 | # NuGet packages 51 | packages/ 52 | *.nupkg 53 | 54 | # Backup files 55 | *.bak 56 | *.tmp 57 | *.swp 58 | *~ 59 | 60 | # Local configuration files that shouldn't be in containers 61 | appsettings.Development.json 62 | appsettings.Local.json 63 | 64 | # Documentation 65 | README.md 66 | README_zh-cn.md 67 | LICENSE.txt 68 | *.md 69 | 70 | # Solution files 71 | *.sln 72 | *.slnx 73 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [year] [fullname] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/_Host.cshtml: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @namespace Mcp.Links.Http.Pages 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | @{ 5 | Layout = null; 6 | } 7 | 8 | 9 | 10 | 11 | 12 | 13 | MCP Links 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /.github/workflows/mcp-links-AutoDeployTrigger-50990fb5-be48-4371-939e-6c00f3306024.yml: -------------------------------------------------------------------------------- 1 | name: Trigger auto deployment for mcp-links 2 | 3 | # When this action will be executed 4 | on: 5 | # Automatically trigger it when tags are created 6 | push: 7 | tags: 8 | - 'v*' 9 | 10 | # Allow manual trigger 11 | workflow_dispatch: 12 | 13 | jobs: 14 | build-and-deploy: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout to the branch 19 | uses: actions/checkout@v2 20 | 21 | - name: Azure Login 22 | uses: azure/login@v2 23 | with: 24 | creds: ${{ secrets.MCPLINKS_AZURE_CREDENTIALS }} 25 | 26 | - name: Build and push container image to registry 27 | uses: azure/container-apps-deploy-action@v2 28 | with: 29 | appSourcePath: ${{ github.workspace }} 30 | _dockerfilePathKey_: _dockerfilePath_ 31 | _targetLabelKey_: _targetLabel_ 32 | registryUrl: ghcr.io 33 | registryUsername: ${{ secrets.MCPLINKS_REGISTRY_USERNAME }} 34 | registryPassword: ${{ secrets.MCPLINKS_REGISTRY_PASSWORD }} 35 | containerAppName: mcp-links 36 | resourceGroup: mcp 37 | imageToBuild: ghcr.io/sheng-jie/mcp-links:${{ github.ref_name }} 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Extensions/AppKeyAuthenticationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Mcp.Links.Http.Authentication; 3 | 4 | namespace Mcp.Links.Http.Extensions; 5 | 6 | public static class AppKeyAuthenticationExtensions 7 | { 8 | public const string AuthorizationPolicyName = "McpAppKeyPolicy"; 9 | 10 | public static IServiceCollection AddAppKeyAuthentication(this IServiceCollection services, IConfiguration configuration) 11 | { 12 | // do not set default authentication scheme 13 | // services.AddAuthentication(options => 14 | // { 15 | // options.DefaultAuthenticateScheme = "AppKey"; 16 | // options.DefaultChallengeScheme = "AppKey"; 17 | // }) 18 | services.AddAuthentication() 19 | .AddScheme("AppKey", options => 20 | { 21 | options.Apps = configuration.GetSection("mcpClients").Get() ?? Array.Empty(); 22 | }); 23 | 24 | services.AddAuthorization(options => 25 | { 26 | options.AddPolicy(AuthorizationPolicyName, policy => 27 | { 28 | policy.AddAuthenticationSchemes("AppKey"); 29 | policy.RequireClaim("AppId"); 30 | }); 31 | }); 32 | 33 | return services; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/css/site.css: -------------------------------------------------------------------------------- 1 | /* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */ 2 | /* stylelint-disable no-duplicate-selectors */ 3 | /* stylelint-disable */ 4 | /* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */ 5 | html, 6 | body, 7 | #root, 8 | #app, 9 | app { 10 | height: 100%; 11 | } 12 | .colorWeak { 13 | filter: invert(80%); 14 | } 15 | .ant-layout { 16 | min-height: 100vh; 17 | } 18 | canvas { 19 | display: block; 20 | } 21 | body { 22 | text-rendering: optimizeLegibility; 23 | -webkit-font-smoothing: antialiased; 24 | -moz-osx-font-smoothing: grayscale; 25 | } 26 | ul, 27 | ol { 28 | list-style: none; 29 | } 30 | .action { 31 | cursor: pointer; 32 | } 33 | @media (max-width: 480px) { 34 | .ant-table { 35 | width: 100%; 36 | overflow-x: auto; 37 | } 38 | .ant-table-thead > tr > th, 39 | .ant-table-tbody > tr > th, 40 | .ant-table-thead > tr > td, 41 | .ant-table-tbody > tr > td { 42 | white-space: pre; 43 | } 44 | .ant-table-thead > tr > th > span, 45 | .ant-table-tbody > tr > th > span, 46 | .ant-table-thead > tr > td > span, 47 | .ant-table-tbody > tr > td > span { 48 | display: block; 49 | } 50 | } 51 | @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { 52 | body .ant-design-pro > .ant-layout { 53 | min-height: 100vh; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Mcp.Links.Http.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/McpClientStartupService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using Microsoft.Extensions.Logging; 3 | using Mcp.Links.Aggregation; 4 | 5 | namespace Mcp.Links.Http; 6 | 7 | public class McpClientStartupService : IHostedService 8 | { 9 | private readonly McpClientsFactory _mcpClientsFactory; 10 | private readonly ILogger _logger; 11 | 12 | public McpClientStartupService(McpClientsFactory mcpClientsFactory, ILogger logger) 13 | { 14 | _mcpClientsFactory = mcpClientsFactory; 15 | _logger = logger; 16 | } 17 | 18 | public async Task StartAsync(CancellationToken cancellationToken) 19 | { 20 | try 21 | { 22 | _logger.LogInformation("Initializing MCP clients on startup..."); 23 | await _mcpClientsFactory.GetOrCreateClientsAsync(cancellationToken); 24 | _logger.LogInformation("MCP clients initialized successfully on startup."); 25 | } 26 | catch (Exception ex) 27 | { 28 | _logger.LogError(ex, "Failed to initialize MCP clients on startup"); 29 | // You can choose to throw here if client initialization is critical 30 | // throw; 31 | } 32 | } 33 | 34 | public Task StopAsync(CancellationToken cancellationToken) 35 | { 36 | _logger.LogInformation("Stopping MCP client startup service..."); 37 | return Task.CompletedTask; 38 | } 39 | } -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/McpClientTransportFactory.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | using ModelContextProtocol.Client; 3 | 4 | namespace Mcp.Links.Aggregation; 5 | 6 | public static class McpClientTransportFactory 7 | { 8 | public static IClientTransport Create(string name, McpServerConfig config) 9 | { 10 | if (config.Type == "stdio") 11 | { 12 | return new StdioClientTransport(new StdioClientTransportOptions 13 | { 14 | Name = $"{name}-client", 15 | Command = config.Command!, 16 | Arguments = config.Args, 17 | EnvironmentVariables = config.Env 18 | }); 19 | } 20 | else if (config.Type == "sse" || config.Type == "http") 21 | { 22 | var options = new SseClientTransportOptions 23 | { 24 | Name = $"{name}-client", 25 | Endpoint = new Uri(config.Url!), 26 | TransportMode = config.Type == "sse" ? HttpTransportMode.Sse : HttpTransportMode.AutoDetect, 27 | AdditionalHeaders = config.Headers 28 | }; 29 | 30 | return new SseClientTransport(options); 31 | } 32 | else 33 | { 34 | throw new InvalidOperationException($"Unsupported MCP server type: {config.Type}"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/mcp.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcpServers": { 3 | "csharp-code-interceptor": { 4 | "enabled": false, 5 | "type": "http", 6 | "url": "https://csharp.starworks.cc/mcp" 7 | }, 8 | "microsoft-learn": { 9 | "enabled": false, 10 | "type": "http", 11 | "url": "https://learn.microsoft.com/api/mcp" 12 | }, 13 | "edgeone-pages-mcp": { 14 | "enabled": true, 15 | "type": "stdio", 16 | "command": "npx", 17 | "args": [ 18 | "edgeone-pages-mcp" 19 | ] 20 | }, 21 | "fetch": { 22 | "enabled": true, 23 | "type": "stdio", 24 | "command": "uvx", 25 | "args": [ 26 | "mcp-server-fetch" 27 | ], 28 | "env": { 29 | "node-env": "dev", 30 | "port": "3300" 31 | } 32 | }, 33 | "samplemcpserver": { 34 | "enabled": true, 35 | "type": "stdio", 36 | "command": "dnx", 37 | "args": [ 38 | "sheng-jie.SampleMcpServer", 39 | "--yes" 40 | ], 41 | "env": { 42 | "WEATHER_CHOICES": "晴朗,暴雨,潮湿,冰冻,多云,阴天,大雪,小雨,雷阵雨,雾霾" 43 | } 44 | }, 45 | "spec-coding": { 46 | "enabled": true, 47 | "type": "stdio", 48 | "command": "dnx", 49 | "args": [ 50 | "SpecCodingMcpServer", 51 | "--yes" 52 | ] 53 | }, 54 | "time": { 55 | "enabled": true, 56 | "type": "stdio", 57 | "command": "uvx", 58 | "args": [ 59 | "mcp-server-time", 60 | "--local-timezone=Asia/Shanghai" 61 | ] 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Result/Fail/Fail.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http.Pages.Result 2 | @page "/result/fail" 3 | 4 | 5 | 6 | 10 | 11 | 12 | 13 | 14 |
15 | The content you submitted has the following error: 16 |
17 |
18 | 19 | Your account has been blocked 20 | 21 | Unblock account 22 | 23 | 24 |
25 |
26 | 27 | Your account is not valid for use 28 | 29 | Upgrade account 30 | 31 |
32 |
33 |
34 |
35 |
-------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/AggregatedMcpServerHostedService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using Mcp.Links.Aggregation; 3 | using Mcp.Links.Configuration; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.Options; 7 | 8 | 9 | [Obsolete("This class is obsolete and will be removed in a future version.")] 10 | internal sealed class AggregatedMcpServerHostedService(McpClientsFactory mcpClientsFactory, 11 | ILoggerFactory loggerFactory, 12 | IHostApplicationLifetime? lifetime = null) : BackgroundService 13 | { 14 | /// 15 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 16 | { 17 | var logger = loggerFactory.CreateLogger(); 18 | 19 | try 20 | { 21 | logger?.LogInformation("Starting Aggregated MCP Server..."); 22 | 23 | var clientWrappers = await mcpClientsFactory.GetOrCreateClientsAsync(stoppingToken).ConfigureAwait(false); 24 | 25 | var factory = new AggregatedMcpServerFactory(clientWrappers); 26 | var server = factory.CreateAggregatedServer(); 27 | 28 | logger?.LogInformation("Aggregated MCP Server started successfully."); 29 | await server.RunAsync(stoppingToken).ConfigureAwait(false); 30 | } 31 | catch (Exception ex) 32 | { 33 | logger?.LogError(ex, "Failed to start Aggregated MCP Server."); 34 | throw; // Re-throw the exception to ensure the host stops 35 | } 36 | finally 37 | { 38 | lifetime?.StopApplication(); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/Mcp.Links/Configuration/McpServerConfigOptionsValidator.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Options; 2 | 3 | namespace Mcp.Links.Configuration; 4 | 5 | public class McpServerConfigOptionsValidator : IValidateOptions 6 | { 7 | public ValidateOptionsResult Validate(string? name, McpServerConfigOptions options) 8 | { 9 | if (options == null) 10 | { 11 | return ValidateOptionsResult.Fail("McpServerOptions cannot be null."); 12 | } 13 | 14 | if (options.McpServers == null || options.McpServers.Count == 0) 15 | { 16 | return ValidateOptionsResult.Fail("At least one MCP server configuration must be provided."); 17 | } 18 | 19 | // Validate each server configuration 20 | foreach (var (serverId, serverConfig) in options.McpServers) 21 | { 22 | if (string.IsNullOrEmpty(serverId)) 23 | { 24 | return ValidateOptionsResult.Fail("Server ID cannot be null or empty"); 25 | } 26 | 27 | if (serverConfig == null) 28 | { 29 | return ValidateOptionsResult.Fail($"Server configuration for '{serverId}' cannot be null"); 30 | } 31 | 32 | if (!serverConfig.IsValid()) 33 | { 34 | var serverErrors = serverConfig.GetValidationErrors() 35 | .Select(error => $"Server '{serverId}': {error}"); 36 | return ValidateOptionsResult.Fail($"Invalid configuration for MCP server '{serverId}': {string.Join(", ", serverErrors)}"); 37 | } 38 | } 39 | 40 | return ValidateOptionsResult.Success; 41 | } 42 | } -------------------------------------------------------------------------------- /src/Mcp.Links/Throw.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Runtime.CompilerServices; 3 | 4 | internal static class Throw 5 | { 6 | // NOTE: Most of these should be replaced with extension statics for the relevant extension 7 | // type as downlevel polyfills once the C# 14 extension everything feature is available. 8 | 9 | public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null) 10 | { 11 | if (arg is null) 12 | { 13 | ThrowArgumentNullException(parameterName); 14 | } 15 | } 16 | 17 | public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null) 18 | { 19 | if (arg is null || arg.AsSpan().IsWhiteSpace()) 20 | { 21 | ThrowArgumentNullOrWhiteSpaceException(parameterName); 22 | } 23 | } 24 | 25 | public static void IfNegative(int arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null) 26 | { 27 | if (arg < 0) 28 | { 29 | Throw(parameterName); 30 | static void Throw(string? parameterName) => throw new ArgumentOutOfRangeException(parameterName, "must not be negative."); 31 | } 32 | } 33 | 34 | [DoesNotReturn] 35 | private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName) 36 | { 37 | if (parameterName is null) 38 | { 39 | ThrowArgumentNullException(parameterName); 40 | } 41 | 42 | throw new ArgumentException("Value cannot be empty or composed entirely of whitespace.", parameterName); 43 | } 44 | 45 | [DoesNotReturn] 46 | private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName); 47 | } 48 | -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/McpClientWrapper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Mcp.Links.Configuration; 3 | using Microsoft.Extensions.Logging; 4 | using ModelContextProtocol.Client; 5 | 6 | namespace Mcp.Links.Aggregation; 7 | 8 | public class McpClientWrapper 9 | { 10 | public string Name { get; private set; } 11 | 12 | private readonly McpServerConfig _config; 13 | 14 | private readonly IClientTransport _clientTransport; 15 | public IMcpClient McpClient { get; private set; } 16 | private readonly ILogger? _logger; 17 | 18 | public McpClientWrapper(string name, McpServerConfig config, ILoggerFactory? loggerFactory = null) 19 | { 20 | Name = name ?? throw new ArgumentNullException(nameof(name)); 21 | _config = config ?? throw new ArgumentNullException(nameof(config)); 22 | _logger = loggerFactory?.CreateLogger(); 23 | 24 | _clientTransport = McpClientTransportFactory.Create(name, config); 25 | 26 | // _transportClient = McpTransportClientFactory.Create(config, loggerFactory); 27 | // _transportClient.MessageReceived += OnMessageReceived; 28 | 29 | 30 | 31 | // var transport = await _clientTransport.ConnectAsync(); 32 | 33 | // _mcpClient = await McpClientFactory.CreateAsync(_clientTransport); 34 | } 35 | 36 | public async Task InitializeAsync() 37 | { 38 | if (McpClient != null) 39 | { 40 | throw new InvalidOperationException("Client is already initialized."); 41 | } 42 | 43 | // Connect to the MCP server and create the client 44 | McpClient = await McpClientFactory.CreateAsync(_clientTransport).ConfigureAwait(false); 45 | 46 | // Optionally, you can perform additional initialization here 47 | _logger?.LogInformation($"MCP Client '{Name}' initialized successfully."); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/McpClientInitializer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using Mcp.Links.Configuration; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace Mcp.Links.Aggregation; 6 | 7 | internal static class McpClientInitializer 8 | { 9 | 10 | public static async Task> InitializeClientsAsync( 11 | Dictionary mcpServers, 12 | ILoggerFactory? loggerFactory = null, 13 | CancellationToken cancellationToken = default) 14 | { 15 | var clientWrappers = new ConcurrentBag(); 16 | 17 | // 优化:预先过滤启用的服务器,减少不必要的并发任务 18 | var enabledServers = mcpServers 19 | .Where(kv => kv.Value.Enabled.GetValueOrDefault(true)) 20 | .ToList(); 21 | 22 | var parallelOptions = new ParallelOptions 23 | { 24 | MaxDegreeOfParallelism = Environment.ProcessorCount, 25 | CancellationToken = cancellationToken 26 | }; 27 | 28 | await Parallel.ForEachAsync( 29 | enabledServers, 30 | parallelOptions, 31 | async (serverConfig, ct) => 32 | { 33 | var serverId = serverConfig.Key; 34 | var config = serverConfig.Value; 35 | 36 | try 37 | { 38 | var clientWrapper = new McpClientWrapper(serverId, config, loggerFactory); 39 | await clientWrapper.InitializeAsync().ConfigureAwait(false); 40 | clientWrappers.Add(clientWrapper); 41 | } 42 | catch (Exception ex) 43 | { 44 | var logger = loggerFactory?.CreateLogger(typeof(McpClientInitializer)); 45 | logger?.LogError(ex, "Failed to initialize MCP client '{ServerId}': {ErrorMessage}", 46 | serverId, ex.Message); 47 | } 48 | } 49 | ).ConfigureAwait(false); 50 | 51 | return clientWrappers.ToList(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Layouts/BasicLayout.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http.Layouts 2 | @inherits LayoutComponentBase 3 | 4 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | @* *@ 30 | 31 | @code{ 32 | bool collapsed; 33 | 34 | public LinkItem[] Links = 35 | { 36 | new LinkItem 37 | { 38 | Key = "Ant Design Blazor", 39 | Title = "Ant Design Blazor", 40 | Href = "https://antblazor.com", 41 | BlankTarget = true, 42 | }, 43 | new LinkItem 44 | { 45 | Key = "github", 46 | Title = (RenderFragment)(@), 47 | Href = "https://github.com/ant-design-blazor/ant-design-pro-blazor", 48 | BlankTarget = true, 49 | }, 50 | new LinkItem 51 | { 52 | Key = "Blazor", 53 | Title = "Blazor", 54 | Href = "https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor?WT.mc_id=DT-MVP-5003987", 55 | BlankTarget = true, 56 | } 57 | }; 58 | 59 | void Toggle() 60 | { 61 | collapsed = !collapsed; 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Welcome.razor.css: -------------------------------------------------------------------------------- 1 | /* Welcome Page Styles */ 2 | .welcome-container { 3 | background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 4 | min-height: 100vh; 5 | padding: 24px; 6 | } 7 | 8 | .loading-container { 9 | display: flex; 10 | flex-direction: column; 11 | align-items: center; 12 | justify-content: center; 13 | height: 60vh; 14 | color: #666; 15 | } 16 | 17 | /* Grid Layouts */ 18 | .stats-grid { 19 | display: grid; 20 | grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); 21 | gap: 24px; 22 | } 23 | 24 | .quick-actions-grid { 25 | display: grid; 26 | grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); 27 | gap: 24px; 28 | } 29 | 30 | .activity-grid { 31 | display: grid; 32 | grid-template-columns: 1fr 1fr; 33 | gap: 24px; 34 | } 35 | 36 | .features-grid { 37 | display: grid; 38 | grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); 39 | gap: 24px; 40 | } 41 | 42 | /* Content styling */ 43 | .quick-action-item { 44 | text-align: center; 45 | padding: 24px; 46 | } 47 | 48 | .feature-item { 49 | text-align: center; 50 | padding: 24px; 51 | } 52 | 53 | /* Card Hover Effects */ 54 | .ant-card.ant-card-hoverable:hover { 55 | transform: translateY(-2px); 56 | box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); 57 | transition: all 0.3s ease; 58 | } 59 | 60 | /* Icon Animations */ 61 | .anticon { 62 | transition: all 0.3s ease; 63 | } 64 | 65 | .ant-card:hover .anticon { 66 | transform: scale(1.1); 67 | } 68 | 69 | /* Responsive Design */ 70 | @media (max-width: 768px) { 71 | .activity-grid { 72 | grid-template-columns: 1fr; 73 | } 74 | 75 | .quick-actions-grid { 76 | grid-template-columns: 1fr; 77 | } 78 | 79 | .features-grid { 80 | grid-template-columns: 1fr; 81 | } 82 | } 83 | 84 | @media (max-width: 576px) { 85 | .stats-grid { 86 | grid-template-columns: 1fr; 87 | } 88 | } 89 | 90 | /* Legacy styles for compatibility */ 91 | .pre { 92 | margin: 12px 0; 93 | padding: 12px 20px; 94 | background: #fff; 95 | box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 96 | 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09); 97 | } 98 | -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/AggregatedMcpServerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.DependencyInjection.Extensions; 3 | using ModelContextProtocol.Server; 4 | 5 | namespace Mcp.Links.Aggregation; 6 | 7 | public static class AggregatedMcpServerBuilderExtensions 8 | { 9 | public static IMcpServerBuilder AddAggregatedHttpMcpServer(this IServiceCollection services, Action? configureOptions = null) 10 | => services.AddMcpServer(configureOptions) 11 | .WithAggregatedTransport("http"); 12 | 13 | public static IMcpServerBuilder AddAggregatedStdioMcpServer(this IServiceCollection services, Action? configureOptions = null) 14 | => services.AddMcpServer(configureOptions) 15 | .WithAggregatedTransport("stdio"); 16 | 17 | 18 | private static IMcpServerBuilder WithAggregatedTransport(this IMcpServerBuilder builder, string transportType) 19 | { 20 | Throw.IfNull(builder); 21 | 22 | builder.Services.TryAddSingleton(); 23 | builder.Services.TryAddSingleton(); 24 | 25 | if (transportType.Equals("stdio", StringComparison.OrdinalIgnoreCase)) 26 | builder.WithStdioServerTransport(); 27 | else 28 | builder.WithHttpTransport(); 29 | 30 | builder.WithHttpTransport(); 31 | 32 | builder.ConfigureHandlers(); 33 | 34 | return builder; 35 | } 36 | 37 | 38 | private static void ConfigureHandlers(this IMcpServerBuilder builder) 39 | { 40 | builder.WithListToolsHandler( 41 | async (context, stoppingToken) => 42 | { 43 | if (context.Services is null) 44 | throw new InvalidOperationException("Service provider is null in the current context."); 45 | McpToolsHandler mcpToolsHandler = context.Services.GetRequiredService(); 46 | return await mcpToolsHandler.ListAggregatedToolsAsync(context, stoppingToken); 47 | }); 48 | 49 | builder.WithCallToolHandler(async (context, cancellationToken) => 50 | { 51 | if (context.Services is null) 52 | throw new InvalidOperationException("Service provider is null in the current context."); 53 | var mcpToolsHandler = context.Services.GetRequiredService(); 54 | return await mcpToolsHandler.CallAggregatedToolAsync(context, cancellationToken); 55 | }); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Mcp/Store.razor.css: -------------------------------------------------------------------------------- 1 | /* Markdown content styling */ 2 | .markdown-content { 3 | line-height: 1.6; 4 | } 5 | 6 | .markdown-content h1, 7 | .markdown-content h2, 8 | .markdown-content h3, 9 | .markdown-content h4, 10 | .markdown-content h5, 11 | .markdown-content h6 { 12 | margin-top: 1.5em; 13 | margin-bottom: 0.5em; 14 | font-weight: 600; 15 | color: #262626; 16 | } 17 | 18 | .markdown-content h1 { 19 | font-size: 1.5em; 20 | border-bottom: 1px solid #e8e8e8; 21 | padding-bottom: 0.3em; 22 | } 23 | 24 | .markdown-content h2 { 25 | font-size: 1.3em; 26 | border-bottom: 1px solid #e8e8e8; 27 | padding-bottom: 0.3em; 28 | } 29 | 30 | .markdown-content h3 { 31 | font-size: 1.1em; 32 | } 33 | 34 | .markdown-content h4, 35 | .markdown-content h5, 36 | .markdown-content h6 { 37 | font-size: 1em; 38 | } 39 | 40 | .markdown-content p { 41 | margin-bottom: 1em; 42 | color: #595959; 43 | } 44 | 45 | .markdown-content ul, 46 | .markdown-content ol { 47 | padding-left: 1.5em; 48 | margin-bottom: 1em; 49 | } 50 | 51 | .markdown-content li { 52 | margin-bottom: 0.25em; 53 | color: #595959; 54 | } 55 | 56 | .markdown-content code { 57 | background-color: #f6f6f6; 58 | padding: 0.2em 0.4em; 59 | border-radius: 3px; 60 | font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace; 61 | font-size: 0.9em; 62 | } 63 | 64 | .markdown-content pre { 65 | background-color: #f6f6f6; 66 | border: 1px solid #d9d9d9; 67 | border-radius: 6px; 68 | padding: 1em; 69 | overflow-x: auto; 70 | margin-bottom: 1em; 71 | } 72 | 73 | .markdown-content pre code { 74 | background-color: transparent; 75 | padding: 0; 76 | border-radius: 0; 77 | } 78 | 79 | .markdown-content blockquote { 80 | border-left: 4px solid #1890ff; 81 | background-color: #f6f8ff; 82 | padding: 0.8em 1em; 83 | margin: 1em 0; 84 | color: #595959; 85 | } 86 | 87 | .markdown-content table { 88 | width: 100%; 89 | border-collapse: collapse; 90 | margin-bottom: 1em; 91 | } 92 | 93 | .markdown-content th, 94 | .markdown-content td { 95 | border: 1px solid #d9d9d9; 96 | padding: 0.5em 1em; 97 | text-align: left; 98 | } 99 | 100 | .markdown-content th { 101 | background-color: #fafafa; 102 | font-weight: 600; 103 | } 104 | 105 | .markdown-content a { 106 | color: #1890ff; 107 | text-decoration: none; 108 | } 109 | 110 | .markdown-content a:hover { 111 | text-decoration: underline; 112 | } 113 | 114 | .markdown-content strong { 115 | font-weight: 600; 116 | } 117 | 118 | .markdown-content em { 119 | font-style: italic; 120 | } 121 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Authentication/AppKeyAuthenticationHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Claims; 3 | using System.Text.Encodings.Web; 4 | using Microsoft.AspNetCore.Authentication; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Mcp.Links.Http.Authentication; 8 | 9 | 10 | public class AppKeyAuthenticationHandler : AuthenticationHandler 11 | { 12 | private const string AppIdHeaderName = "X-AppId"; 13 | private const string AppKeyHeaderName = "X-AppKey"; 14 | public AppKeyAuthenticationHandler(IOptionsMonitor options, 15 | ILoggerFactory logger, 16 | UrlEncoder encoder) 17 | : base(options, logger, encoder) 18 | { 19 | } 20 | 21 | protected override Task HandleAuthenticateAsync() 22 | { 23 | // 只对 /mcp 端点进行认证检查 24 | if (!Request.Path.StartsWithSegments("/mcp")) 25 | { 26 | return Task.FromResult(AuthenticateResult.NoResult()); 27 | } 28 | 29 | if (!Request.Headers.TryGetValue(AppIdHeaderName, out var appIdHeaderValues)) 30 | { 31 | return Task.FromResult(AuthenticateResult.Fail("App ID is missing")); 32 | } 33 | 34 | if (!Request.Headers.TryGetValue(AppKeyHeaderName, out var appKeyHeaderValues)) 35 | { 36 | return Task.FromResult(AuthenticateResult.Fail("App Key is missing")); 37 | } 38 | 39 | var appId = appIdHeaderValues.FirstOrDefault(); 40 | var appKey = appKeyHeaderValues.FirstOrDefault(); 41 | 42 | if (string.IsNullOrEmpty(appId)) 43 | { 44 | return Task.FromResult(AuthenticateResult.Fail("App ID is empty")); 45 | } 46 | 47 | if (string.IsNullOrEmpty(appKey)) 48 | { 49 | return Task.FromResult(AuthenticateResult.Fail("App Key is empty")); 50 | } 51 | 52 | // Check if the App ID and App Key are valid 53 | var validApp = Options.Apps.FirstOrDefault(a => a.AppId == appId && a.AppKey == appKey); 54 | 55 | if (validApp.Equals(default(AppIdAndAppKey))) 56 | { 57 | return Task.FromResult(AuthenticateResult.Fail("Invalid App ID or App Key")); 58 | } 59 | 60 | var claims = new[] 61 | { 62 | new Claim(ClaimTypes.Name, appId), 63 | new Claim("AppId", appId) 64 | }; 65 | 66 | var identity = new ClaimsIdentity(claims, Scheme.Name); 67 | var principal = new ClaimsPrincipal(identity); 68 | var ticket = new AuthenticationTicket(principal, Scheme.Name); 69 | 70 | return Task.FromResult(AuthenticateResult.Success(ticket)); 71 | } 72 | } 73 | 74 | public class AppKeyAuthenticationOptions : AuthenticationSchemeOptions 75 | { 76 | public AppIdAndAppKey[] Apps { get; set; } 77 | } 78 | 79 | public record struct AppIdAndAppKey(string AppId, string AppKey); -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | a, .btn-link { 6 | color: #006bb7; 7 | } 8 | 9 | .btn-primary { 10 | color: #fff; 11 | background-color: #1b6ec2; 12 | border-color: #1861ac; 13 | } 14 | 15 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 16 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 17 | } 18 | 19 | .content { 20 | padding-top: 1.1rem; 21 | } 22 | 23 | h1:focus { 24 | outline: none; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid #e50000; 33 | } 34 | 35 | .validation-message { 36 | color: #e50000; 37 | } 38 | 39 | .blazor-error-boundary { 40 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 41 | padding: 1rem 1rem 1rem 3.7rem; 42 | color: white; 43 | } 44 | 45 | .blazor-error-boundary::after { 46 | content: "An error has occurred." 47 | } 48 | 49 | .darker-border-checkbox.form-check-input { 50 | border-color: #929292; 51 | } 52 | 53 | .form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { 54 | color: var(--bs-secondary-color); 55 | text-align: end; 56 | } 57 | 58 | .form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { 59 | text-align: start; 60 | } -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Services/IMcpClientAppService.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | 3 | namespace Mcp.Links.Http.Services; 4 | 5 | /// 6 | /// Service interface for managing MCP client app configurations. 7 | /// 8 | public interface IMcpClientAppService 9 | { 10 | /// 11 | /// Gets all MCP client app configurations. 12 | /// 13 | /// Array of MCP client app objects. 14 | Task GetAllClientAppsAsync(); 15 | 16 | /// 17 | /// Gets a specific MCP client app configuration by ID. 18 | /// 19 | /// The app ID to retrieve. 20 | /// The client app if found, null otherwise. 21 | Task GetClientAppAsync(string appId); 22 | 23 | /// 24 | /// Creates a new MCP client app configuration. 25 | /// 26 | /// The client app configuration. 27 | /// Task representing the asynchronous operation. 28 | Task CreateClientAppAsync(McpClientConfig clientApp); 29 | 30 | /// 31 | /// Updates an existing MCP client app configuration. 32 | /// 33 | /// The app ID to update. 34 | /// The updated client app configuration. 35 | /// Task representing the asynchronous operation. 36 | Task UpdateClientAppAsync(string appId, McpClientConfig clientApp); 37 | 38 | /// 39 | /// Deletes an MCP client app configuration. 40 | /// 41 | /// The app ID to delete. 42 | /// Task representing the asynchronous operation. 43 | Task DeleteClientAppAsync(string appId); 44 | 45 | /// 46 | /// Checks if a client app ID already exists. 47 | /// 48 | /// The app ID to check. 49 | /// True if the app ID exists, false otherwise. 50 | Task ClientAppExistsAsync(string appId); 51 | 52 | /// 53 | /// Validates a client app configuration. 54 | /// 55 | /// The client app configuration to validate. 56 | /// True if valid, false otherwise. 57 | bool ValidateClientApp(McpClientConfig clientApp); 58 | 59 | /// 60 | /// Gets validation errors for a client app configuration. 61 | /// 62 | /// The client app configuration to validate. 63 | /// Collection of validation error messages. 64 | IEnumerable GetValidationErrors(McpClientConfig clientApp); 65 | 66 | /// 67 | /// Generates a client configuration entry for the specified app and server. 68 | /// 69 | /// The app ID to generate configuration for. 70 | /// The server ID to generate configuration for. 71 | /// JSON configuration string for MCP client. 72 | Task GenerateClientConfigurationAsync(string appId, string serverId); 73 | } 74 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Result/Success/Success.razor: -------------------------------------------------------------------------------- 1 | @namespace Mcp.Links.Http.Pages.Result 2 | @page "/result/success" 3 | 4 | 5 | 6 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 23421 20 | Qu Lili 21 | 2016-12-12 ~ 2017-12-12 22 | 23 |
24 | 25 | 26 | 27 | Create project 28 | 29 | 30 |
31 |
32 | Qu Lili 33 | 34 |
35 |
2016-12-12 12:32
36 |
37 |
38 |
39 | 40 | 41 | Departmental preliminary review 42 | 43 | 44 |
45 |
46 | Zhou Maomao 47 | 48 | 49 | Urge 50 | 51 |
52 |
53 |
54 |
55 | 56 | 57 | Financial review 58 | 59 | 60 | 61 | 62 | Finish 63 | 64 | 65 |
66 |
67 |
68 |
69 |
-------------------------------------------------------------------------------- /src/Mcp.Links.Http/Services/IMcpStoreService.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | 3 | namespace Mcp.Links.Http.Services; 4 | 5 | /// 6 | /// Service interface for managing MCP store operations including server installation. 7 | /// 8 | public interface IMcpStoreService 9 | { 10 | /// 11 | /// Parses store item configuration and returns installation details. 12 | /// 13 | /// The store item to parse. 14 | /// Installation details including server type and configuration. 15 | Task ParseInstallationInfoAsync(McpStoreItem storeItem); 16 | 17 | /// 18 | /// Installs an MCP server from store configuration. 19 | /// 20 | /// The store item to install. 21 | /// Optional custom server ID. If not provided, one will be generated. 22 | /// The installed server ID. 23 | Task InstallServerFromStoreAsync(McpStoreItem storeItem, string? customServerId = null); 24 | 25 | /// 26 | /// Validates if a store item can be installed. 27 | /// 28 | /// The store item to validate. 29 | /// Validation result with details. 30 | Task ValidateStoreItemAsync(McpStoreItem storeItem); 31 | 32 | /// 33 | /// Generates a unique server ID from a store item. 34 | /// 35 | /// The store item to generate ID for. 36 | /// A unique server ID. 37 | Task GenerateServerIdAsync(McpStoreItem storeItem); 38 | 39 | /// 40 | /// Gets all MCP servers available in the store. 41 | /// 42 | /// List of MCP store items. 43 | Task> GetAllStoreServersAsync(); 44 | } 45 | 46 | /// 47 | /// Information about an MCP store item installation. 48 | /// 49 | public class McpStoreInstallationInfo 50 | { 51 | public required string ServerType { get; set; } // "stdio", "http", "sse" 52 | public required string GeneratedServerId { get; set; } 53 | public McpServerConfig? ServerConfig { get; set; } 54 | public string? Command { get; set; } 55 | public string[]? Args { get; set; } 56 | public Dictionary? Environment { get; set; } 57 | public string? Url { get; set; } 58 | public Dictionary? Headers { get; set; } 59 | public bool RequiresEnvironmentVariables { get; set; } 60 | public string[]? RequiredEnvironmentVars { get; set; } 61 | public string? InstallationNotes { get; set; } 62 | } 63 | 64 | /// 65 | /// Validation result for MCP store items. 66 | /// 67 | public class McpStoreValidationResult 68 | { 69 | public bool IsValid { get; set; } 70 | public List Errors { get; set; } = new(); 71 | public List Warnings { get; set; } = new(); 72 | public bool RequiresManualConfiguration { get; set; } 73 | public string[]? MissingEnvironmentVars { get; set; } 74 | } 75 | 76 | /// 77 | /// Data transfer object for MCP store items. 78 | /// 79 | public class McpStoreItem 80 | { 81 | public string Title { get; set; } = string.Empty; 82 | public string ImageUrl { get; set; } = string.Empty; 83 | public string Author { get; set; } = string.Empty; 84 | public string Address { get; set; } = string.Empty; 85 | public string Profile { get; set; } = string.Empty; 86 | public string Overview { get; set; } = string.Empty; 87 | public string Config { get; set; } = string.Empty; 88 | } 89 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/assets/logo.svg: -------------------------------------------------------------------------------- 1 | Group 28 Copy 5Created with Sketch. -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Layouts/BasicLayout.razor.cs: -------------------------------------------------------------------------------- 1 | using AntDesign.Extensions.Localization; 2 | using AntDesign.ProLayout; 3 | using Microsoft.AspNetCore.Components; 4 | using System.Globalization; 5 | using System.Net.Http.Json; 6 | 7 | namespace Mcp.Links.Http.Layouts 8 | { 9 | public partial class BasicLayout : LayoutComponentBase, IDisposable 10 | { 11 | private MenuDataItem[] _menuData = Array.Empty(); 12 | 13 | [Inject] private ReuseTabsService TabService { get; set; } = null!; 14 | 15 | protected override void OnInitialized() 16 | { 17 | _menuData = new[] { 18 | new MenuDataItem 19 | { 20 | Path = "/", 21 | Name = "Welcome", 22 | Key = "welcome", 23 | Icon = "smile", 24 | }, 25 | new MenuDataItem 26 | { 27 | Path = "/mcp/store", 28 | Name = "Store", 29 | Key = "mcp-store", 30 | Icon = "shop", 31 | }, 32 | new MenuDataItem 33 | { 34 | Path = "/mcp/servers", 35 | Name = "Servers", 36 | Key = "mcp-servers", 37 | Icon = "hdd", 38 | }, 39 | new MenuDataItem 40 | { 41 | Path = "/mcp/clients", 42 | Name = "Clients", 43 | Key = "mcp-client-apps", 44 | Icon = "appstore", 45 | }, 46 | new MenuDataItem 47 | { 48 | Path = "/mcp/inspector", 49 | Name = "Inspector", 50 | Key = "mcp-inspector", 51 | Icon = "bug", 52 | }, 53 | new MenuDataItem 54 | { 55 | Path = "/mcp/env-check", 56 | Name = "Environment Check", 57 | Key = "mcp-env-check", 58 | Icon = "check-circle", 59 | } 60 | // new MenuDataItem 61 | // { 62 | // Path = "/mcp", 63 | // Name = "MCP", 64 | // Key = "mcp", 65 | // Icon = "api", 66 | // Children = new[] 67 | // { 68 | // new MenuDataItem 69 | // { 70 | // Path = "/mcp/servers", 71 | // Name = "Servers", 72 | // Key = "mcp-servers", 73 | // Icon = "hdd", 74 | // }, 75 | // new MenuDataItem 76 | // { 77 | // Path = "/mcp/clients", 78 | // Name = "Clients", 79 | // Key = "mcp-client-apps", 80 | // Icon = "appstore", 81 | // }, 82 | // new MenuDataItem 83 | // { 84 | // Path = "/mcp/inspector", 85 | // Name = "Inspector", 86 | // Key = "mcp-inspector", 87 | // Icon = "bug", 88 | // } 89 | // } 90 | // } 91 | }; 92 | } 93 | void Reload() 94 | { 95 | TabService.ReloadPage(); 96 | } 97 | 98 | public void Dispose() 99 | { 100 | 101 | } 102 | 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Program.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Aggregation; 2 | using Mcp.Links.Configuration; 3 | using Mcp.Links.Http.Services; 4 | using Microsoft.Extensions.Options; 5 | using Microsoft.AspNetCore.Components; 6 | using AntDesign.ProLayout; 7 | using Mcp.Links.Http.Extensions; 8 | using Mcp.Links.Http; 9 | using Microsoft.AspNetCore.HttpOverrides; 10 | 11 | var builder = WebApplication.CreateBuilder(args); 12 | 13 | 14 | // read the MCP server configuration from the args 15 | builder.Configuration.AddCommandLine(args); 16 | 17 | var mcpFilePath = args.FirstOrDefault(a => a.StartsWith("--mcp-file="))?.Split('=')[1]; 18 | if (!string.IsNullOrEmpty(mcpFilePath) && File.Exists(mcpFilePath)) 19 | { 20 | builder.Configuration.AddJsonFile(mcpFilePath, optional: false, reloadOnChange: true); 21 | } 22 | else 23 | { 24 | // Fallback to the default mcp.json in the current directory 25 | builder.Configuration 26 | .SetBasePath(AppContext.BaseDirectory) 27 | .AddJsonFile("mcp.json", optional: false, reloadOnChange: true) 28 | .AddJsonFile("client-apps.json", optional: false, reloadOnChange: true); 29 | } 30 | 31 | 32 | // Register the configuration for MCP servers - bind to root since McpServerOptions expects the full JSON 33 | builder.Services.Configure(builder.Configuration); 34 | builder.Services.Configure(builder.Configuration); 35 | builder.Services.AddSingleton, McpServerConfigOptionsValidator>(); 36 | 37 | // Add APP key authentication only for MCP 38 | builder.Services.AddAppKeyAuthentication(builder.Configuration); 39 | 40 | // Register MCP server service 41 | builder.Services.AddScoped(); 42 | 43 | // Register MCP inspector service 44 | builder.Services.AddScoped(); 45 | 46 | // Register MCP client app service 47 | builder.Services.AddScoped(); 48 | 49 | // Register MCP store service 50 | builder.Services.AddScoped(); 51 | 52 | 53 | // Add services to the container. 54 | builder.Services.AddRazorPages(); 55 | builder.Services.AddServerSideBlazor(); 56 | builder.Services.AddAntDesign(); 57 | builder.Services.AddScoped(sp => new HttpClient 58 | { 59 | BaseAddress = new Uri(sp.GetService()!.BaseUri) 60 | }); 61 | 62 | 63 | builder.Services.Configure(builder.Configuration.GetSection("ProSettings")); 64 | builder.Services.AddInteractiveStringLocalizer(); 65 | builder.Services.AddLocalization(); 66 | 67 | builder.Services.AddHttpContextAccessor(); 68 | builder.Services.AddHostedService(); 69 | 70 | builder.Services.AddAggregatedHttpMcpServer(); 71 | 72 | builder.Services.Configure(options => 73 | { 74 | options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; 75 | options.KnownNetworks.Clear(); 76 | options.KnownProxies.Clear(); 77 | }); 78 | 79 | var app = builder.Build(); 80 | 81 | app.UseForwardedHeaders(); 82 | 83 | // Configure the HTTP request pipeline. 84 | if (!app.Environment.IsDevelopment()) 85 | { 86 | app.UseExceptionHandler("/Error", createScopeForErrors: true); 87 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 88 | app.UseHsts(); 89 | } 90 | 91 | // app.UseStatusCodePagesWithReExecute("/not-found", createScopeForErrors: true); 92 | 93 | app.UseHttpsRedirection(); 94 | 95 | // Add authentication middleware 96 | app.UseAuthentication(); 97 | 98 | app.UseStaticFiles(); 99 | 100 | app.UseRouting(); 101 | 102 | app.UseAuthorization(); 103 | 104 | app.MapMcp("/mcp") 105 | .RequireAuthorization(AppKeyAuthenticationExtensions.AuthorizationPolicyName); 106 | 107 | app.MapBlazorHub(); 108 | app.MapFallbackToPage("/_Host"); 109 | 110 | 111 | app.Run(); 112 | -------------------------------------------------------------------------------- /src/Mcp.Links/Configuration/McpServerConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace Mcp.Links.Configuration; 4 | 5 | /// 6 | /// Configuration for a single MCP server instance. 7 | /// 8 | public class McpServerConfig 9 | { 10 | 11 | /// 12 | /// if the server is enabled. Defaults to true. 13 | /// Set to false to disable the server without removing it from the configuration. 14 | /// 15 | public bool? Enabled { get; set; } = true; 16 | 17 | /// 18 | /// Type of the MCP server connection. Can be "command", "sse", or null for command type. 19 | /// 20 | [JsonPropertyName("type")] 21 | public string? Type { get; set; } 22 | 23 | 24 | 25 | private string? _command; 26 | /// 27 | /// Command to execute for command-type servers. 28 | /// 29 | [JsonPropertyName("command")] 30 | public string? Command 31 | { 32 | get => _command; 33 | set 34 | { 35 | _command = value; 36 | if (!string.IsNullOrEmpty(value)) 37 | { 38 | Type = "stdio"; // Default to stdio if command is provided 39 | } 40 | } 41 | } 42 | 43 | 44 | private string? _url; 45 | /// 46 | /// URL for SSE-type servers. 47 | /// 48 | [JsonPropertyName("url")] 49 | public string? Url 50 | { 51 | get => _url; 52 | set 53 | { 54 | _url = value; 55 | if (!string.IsNullOrEmpty(value)) 56 | { 57 | if (string.IsNullOrEmpty(Type)) 58 | Type = "sse"; // Default to sse if url is provided and type is not set 59 | } 60 | } 61 | } 62 | 63 | 64 | /// 65 | /// Arguments to pass to the command for command-type servers. 66 | /// 67 | [JsonPropertyName("args")] 68 | public string[]? Args { get; set; } 69 | 70 | /// 71 | /// Environment variables to set for command-type servers. 72 | /// 73 | [JsonPropertyName("env")] 74 | public Dictionary? Env { get; set; } 75 | 76 | /// 77 | /// HTTP headers to send with requests for SSE/HTTP-type servers. 78 | /// 79 | [JsonPropertyName("headers")] 80 | public Dictionary? Headers { get; set; } 81 | 82 | 83 | /// 84 | /// Validates the configuration based on the server type. 85 | /// 86 | /// True if the configuration is valid, otherwise false. 87 | public bool IsValid() 88 | { 89 | if(string.IsNullOrEmpty(Command) && string.IsNullOrEmpty(Url)) 90 | { 91 | // If both Command and Url are null or empty, it's invalid 92 | return false; 93 | } 94 | 95 | return Type switch 96 | { 97 | "stdio" => !string.IsNullOrEmpty(Command), 98 | "http" or "sse" => !string.IsNullOrEmpty(Url) && Uri.TryCreate(Url, UriKind.Absolute, out var uri) && 99 | (uri.Scheme == "http" || uri.Scheme == "https"), 100 | _ => false 101 | }; 102 | } 103 | 104 | /// 105 | /// Gets validation error messages for invalid configurations. 106 | /// 107 | /// Collection of validation error messages. 108 | public IEnumerable GetValidationErrors() 109 | { 110 | var errors = new List(); 111 | 112 | switch (Type) 113 | { 114 | case "stdio": 115 | if (string.IsNullOrEmpty(Command)) 116 | errors.Add("Command is required for stdio-type servers"); 117 | break; 118 | case "http": 119 | case "sse": 120 | if (string.IsNullOrEmpty(Url)) 121 | errors.Add("URL is required for SSE-type servers"); 122 | else if (!Uri.TryCreate(Url, UriKind.Absolute, out var uri) || 123 | (uri.Scheme != "http" && uri.Scheme != "https")) 124 | errors.Add("URL must be a valid HTTP or HTTPS URL for SSE-type servers"); 125 | break; 126 | 127 | default: 128 | errors.Add($"Unsupported server type: {Type}"); 129 | break; 130 | } 131 | 132 | return errors; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /README_zh-cn.md: -------------------------------------------------------------------------------- 1 | [English](README.md) | [简体中文](README_zh-cn.md) 2 | 3 | ![](./doc/imgs/intro.png) 4 | 5 | # Mcp.Links 6 | 7 | 一个基于 .NET 9.0 构建的强大的模型上下文协议 (MCP) 聚合器,能够无缝集成和管理多个 MCP 服务器。该项目提供 HTTP 和命令行接口,将各种 MCP 服务器聚合到统一平台中。 8 | 9 | ## 🚀 特性 10 | 11 | - **多协议支持**: 通过 stdio、HTTP 和 SSE 协议聚合 MCP 服务器 12 | - **Web 管理界面**: 基于 Blazor 的直观 UI,用于管理 MCP 服务器和客户端应用 13 | - **MCP 商店**: 内置市场,用于发现和安装预配置的 MCP 服务器 14 | - **身份验证**: 内置 API 密钥认证,确保安全访问 15 | - **实时检查器**: 监控和检查 MCP 服务器通信 16 | - **客户端应用管理**: 配置不同的客户端应用,授予特定 MCP 服务器访问权限 17 | - **工具聚合**: 无缝组合多个 MCP 服务器的工具 18 | - **Docker 支持**: 可即时部署的容器化解决方案 19 | - **多环境支持**: 可配置开发和生产环境 20 | 21 | ## 📦 安装和使用 22 | 23 | ### ⚡ 快速开始 24 | 25 | 使用预构建的 Docker 镜像快速启动: 26 | 27 | ```bash 28 | # 使用默认配置运行 29 | docker run -p 8080:8080 ghcr.io/sheng-jie/mcp-links:v0.4 30 | 31 | # 使用自定义配置文件运行 32 | docker run -p 8080:8080 \ 33 | -v $(pwd)/mcp.json:/app/mcp.json \ 34 | -v $(pwd)/client-apps.json:/app/client-apps.json \ 35 | ghcr.io/sheng-jie/mcp-links:v0.4 36 | ``` 37 | 38 | 应用程序将在 `http://localhost:8080` 可用,MCP 端点位于 `/mcp`。 39 | 40 | ### 📋 前置条件 41 | 42 | - .NET 9.0 SDK 43 | - Node.js(用于运行基于 Node 的 MCP 服务器) 44 | - Python 3.x 带 uv/uvx(用于基于 Python 的 MCP 服务器) 45 | 46 | ### 1. HTTP 服务器模式(推荐) 47 | 48 | 运行基于 Web 的管理界面: 49 | 50 | ```bash 51 | dotnet run --project src/Mcp.Links.Http/Mcp.Links.Http.csproj 52 | ``` 53 | 54 | 服务器将在 `http://localhost:5146` 启动,MCP 端点可在 `/mcp` 访问。 55 | 56 | 访问 `http://localhost:5146/mcp/env-check` 来检查本地环境是否满足要求。 57 | 58 | ### 2. 配置 59 | 60 | #### MCP 服务器配置 (`mcp.json`) 61 | 62 | ```json 63 | { 64 | "mcpServers": { 65 | "fetch": { 66 | "enabled": true, 67 | "type": "stdio", 68 | "command": "uvx", 69 | "args": ["mcp-server-fetch"], 70 | "env": { 71 | "node-env": "dev", 72 | "port": "3300" 73 | } 74 | }, 75 | "time": { 76 | "enabled": true, 77 | "type": "stdio", 78 | "command": "uvx", 79 | "args": ["mcp-server-time", "--local-timezone=Asia/Shanghai"] 80 | }, 81 | "microsoft-learn": { 82 | "enabled": false, 83 | "type": "http", 84 | "url": "https://learn.microsoft.com/api/mcp" 85 | } 86 | } 87 | } 88 | ``` 89 | 90 | #### 客户端应用配置 (`client-apps.json`) 91 | 92 | ```json 93 | { 94 | "mcpClients": [ 95 | { 96 | "appId": "vscode", 97 | "appKey": "your-api-key-here", 98 | "name": "VS Code", 99 | "description": "VS Code MCP 客户端", 100 | "mcpServerIds": ["fetch", "time"] 101 | } 102 | ] 103 | } 104 | ``` 105 | 106 | ### 3. 构建和部署 Docker 107 | 108 | 使用 Docker 构建和运行: 109 | 110 | ```bash 111 | # 构建镜像 112 | docker build -t mcp-links . 113 | 114 | # 运行容器 115 | docker run -p 8080:8080 \ 116 | -v $(pwd)/mcp.json:/app/mcp.json \ 117 | -v $(pwd)/client-apps.json:/app/client-apps.json \ 118 | mcp-links 119 | ``` 120 | 121 | ### 4. 自定义配置文件 122 | 123 | 指定自定义配置文件: 124 | 125 | ```bash 126 | dotnet run --project src/Mcp.Links.Http/Mcp.Links.Http.csproj --mcp-file=/path/to/custom-mcp.json 127 | ``` 128 | 129 | ## 🔧 支持的 MCP 服务器类型 130 | 131 | ### Stdio 服务器 132 | - **基于 Python**: 使用 `uvx` 或 `pip` 安装的包 133 | - **基于 .NET**: 使用 `dnx` 命令和 .NET 工具 134 | - **基于 Node.js**: 使用 `npx` 或全局安装的包 135 | 136 | ### HTTP 服务器 137 | - 具有标准 HTTP 端点的 RESTful MCP 服务器 138 | - 支持自定义认证头 139 | 140 | ### SSE (Server-Sent Events) 141 | - 实时流式 MCP 服务器 142 | - 基于事件的通信 143 | 144 | ## 🎯 使用场景 145 | 146 | - **AI 开发**: 将多个 AI 工具和服务聚合到单一 MCP 接口 147 | - **企业集成**: 集中管理各种业务工具和 API 148 | - **开发工作流**: 组合代码分析、文档和部署工具 149 | - **研究平台**: 集成数据分析、可视化和机器学习工具 150 | - **快速原型开发**: 从内置商店快速发现和集成 MCP 服务器 151 | - **多客户端管理**: 为不同的 AI 客户端(VS Code、Cursor、Claude Desktop)配置不同的工具集 152 | 153 | ## 🔒 安全特性 154 | 155 | - **API 密钥认证**: 客户端应用的安全访问控制 156 | - **客户端特定服务器访问**: 不同客户端应用的细粒度权限 157 | - **环境隔离**: 不同环境的独立配置 158 | - **请求验证**: 内置请求验证和错误处理 159 | 160 | ## 🌐 Web 界面功能 161 | 162 | Web 管理界面提供: 163 | 164 | - **服务器管理**: 添加、编辑、禁用/启用 MCP 服务器 165 | - **MCP 商店**: 浏览和安装来自精选市场的 MCP 服务器,包含 40+ 个预配置服务器: 166 | - **AI 服务**: 时间转换、网络搜索(Brave、Perplexity、智谱)、图像生成(EverArt、MiniMax) 167 | - **开发工具**: GitHub/GitLab 集成、Figma 上下文、浏览器自动化(Playwright、Puppeteer) 168 | - **数据库访问**: PostgreSQL、Redis、Neon 数据库管理 169 | - **内容与通信**: Slack 集成、邮件发送(Mailtrap)、笔记记录(Flomo) 170 | - **位置服务**: Google Maps、百度地图、高德地图,支持地理编码和路线规划 171 | - **专业工具**: Blender 3D 建模、序列思维、AWS 知识库检索 172 | - **实时监控**: 查看服务器状态和通信日志 173 | - **工具检查器**: 浏览所有连接服务器的可用工具 174 | - **客户端应用管理**: 为不同客户端配置 API 密钥和服务器访问权限 175 | - **配置编辑器**: 直接编辑 JSON 配置文件 176 | - **国际化**: 支持多种语言(英文、中文) 177 | 178 | ## 📊 监控和调试 179 | 180 | - **健康检查**: 监控所有连接的 MCP 服务器状态 181 | - **请求日志**: 跟踪所有 MCP 通信用于调试 182 | - **错误处理**: 全面的错误报告和恢复 183 | - **性能指标**: 监控响应时间和服务器性能 184 | 185 | ## 🚀 开发和扩展 186 | 187 | ### 添加新的 MCP 服务器 188 | 189 | 1. 更新您的 `mcp.json` 配置 190 | 2. 重启应用程序或使用热重载 191 | 3. 通过 Web 界面验证连接性 192 | 193 | ### 自定义传输类型 194 | 195 | 系统支持通过在核心库中实现传输接口来扩展自定义传输实现。 196 | 197 | ## 🤝 贡献 198 | 199 | 欢迎贡献!请随时提交 pull request、报告问题或建议新功能。 200 | 201 | ## 📄 许可证 202 | 203 | 本项目在 [LICENSE.txt](LICENSE.txt) 文件中指定的条款下获得许可。 204 | 205 | --- 206 | 207 | **使用 .NET 9.0、AntBlazor 和 MCP C# SDK 用 ❤️ 构建** 208 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # ============================================================ 2 | # Stage 1: Build and publish the application 3 | # ============================================================ 4 | 5 | # Base Image - .NET 9.0 SDK with Debian for building the application 6 | FROM mcr.microsoft.com/dotnet/sdk:9.0-bookworm-slim AS build 7 | ARG BUILD_CONFIGURATION=Release 8 | 9 | # 设置国内镜像源加速apt-get 10 | RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources \ 11 | && sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources 12 | 13 | WORKDIR /src 14 | 15 | # Copy project files first for better caching 16 | COPY ["src/Mcp.Links.Http/Mcp.Links.Http.csproj", "src/Mcp.Links.Http/"] 17 | COPY ["src/Mcp.Links/Mcp.Links.csproj", "src/Mcp.Links/"] 18 | 19 | # Restore NuGet packages 20 | RUN dotnet restore "src/Mcp.Links.Http/Mcp.Links.Http.csproj" 21 | 22 | # Copy source code 23 | COPY . . 24 | 25 | # Build and publish the application 26 | WORKDIR "/src/src/Mcp.Links.Http" 27 | RUN dotnet build "Mcp.Links.Http.csproj" -c $BUILD_CONFIGURATION -o /app/build 28 | 29 | # Publish the application 30 | RUN dotnet publish "Mcp.Links.Http.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false 31 | 32 | # ============================================================ 33 | # Stage 2: Final runtime image 34 | # ============================================================ 35 | 36 | # Base Image - .NET 9.0 ASP.NET Core runtime with Debian for running the application 37 | FROM mcr.microsoft.com/dotnet/aspnet:9.0-bookworm-slim AS final 38 | 39 | # 设置国内镜像源加速apt-get 40 | RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources \ 41 | && sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources 42 | 43 | # Install basic system packages 44 | RUN apt-get update && apt-get install -y \ 45 | curl \ 46 | wget \ 47 | ca-certificates \ 48 | && rm -rf /var/lib/apt/lists/* 49 | 50 | # Install Python and related packages 51 | RUN apt-get update && apt-get install -y \ 52 | python3 \ 53 | python3-pip \ 54 | python3-venv \ 55 | && rm -rf /var/lib/apt/lists/* 56 | 57 | # Install Node.js 58 | RUN (curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - || echo "Failed to setup NodeSource repository") \ 59 | && (apt-get install -y nodejs || echo "Failed to install nodejs") \ 60 | && rm -rf /var/lib/apt/lists/* \ 61 | && (npm config set registry https://registry.npmmirror.com || true) \ 62 | && (npm config set disturl https://npmmirror.com/mirrors/node || true) \ 63 | && (npm config set electron_mirror https://npmmirror.com/mirrors/electron || true) \ 64 | && (npm config set chromedriver_cdnurl https://npmmirror.com/mirrors/chromedriver || true) 65 | 66 | # Install .NET 10 SDK and create symlinks 67 | RUN curl -fsSL https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.sh | bash -s -- --version latest --channel 10.0 --install-dir /usr/share/dotnet \ 68 | && ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet-10 \ 69 | && echo '#!/bin/bash\n/usr/bin/dotnet-10 dnx "$@"' > /usr/local/bin/dnx \ 70 | && chmod +x /usr/local/bin/dnx 71 | 72 | # Install uv (Python package manager) and create symlinks 73 | RUN export UV_INSTALLER_GHE_BASE_URL="https://ghfast.top/https://github.com" \ 74 | && curl -LsSf https://astral.sh/uv/install.sh | sh || true \ 75 | && (ls -la /root/.local/bin/ || echo "uv installation may have failed") \ 76 | && (cp /root/.local/bin/uv /usr/local/bin/uv || true) \ 77 | && (cp /root/.local/bin/uvx /usr/local/bin/uvx || true) \ 78 | && chmod +x /usr/local/bin/uv /usr/local/bin/uvx || true 79 | 80 | # Configure uv/uvx to use Chinese mirrors for faster package downloads 81 | RUN mkdir -p /etc/uv \ 82 | && echo 'index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"' > /etc/uv/uv.toml \ 83 | && echo 'extra-index-url = ["https://mirrors.aliyun.com/pypi/simple/"]' >> /etc/uv/uv.toml \ 84 | && mkdir -p /root/.config/uv \ 85 | && cp /etc/uv/uv.toml /root/.config/uv/uv.toml || true 86 | 87 | # Verify installations 88 | RUN dotnet --version && node --version && npm --version && python3 --version && dotnet-10 --version && dotnet-10 --list-sdks && dnx --help && (uv --version || echo "uv not available") 89 | 90 | WORKDIR /app 91 | 92 | # Copy published application from build stage 93 | COPY --from=build /app/publish . 94 | 95 | # Set environment variables 96 | ENV ASPNETCORE_ENVIRONMENT=Production 97 | ENV ASPNETCORE_URLS=http://+:8080 98 | # Set mirrors for package managers 99 | ENV UV_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple 100 | ENV UV_EXTRA_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ 101 | ENV NPM_CONFIG_REGISTRY=https://registry.npmmirror.com 102 | 103 | # Expose the port the application listens on 104 | EXPOSE 8080 105 | 106 | # Configure health check - using root path since no specific health endpoint is configured 107 | HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ 108 | CMD curl -f http://localhost:8080/ || exit 1 109 | 110 | # Switch to non-root user for security 111 | # USER $APP_UID 112 | 113 | # Set the entry point for the application 114 | ENTRYPOINT ["dotnet", "Mcp.Links.Http.dll"] 115 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Mcp/ServerDetail.razor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using AntDesign.TableModels; 4 | using AntDesign; 5 | using global::Mcp.Links.Configuration; 6 | using global::Mcp.Links.Http.Services; 7 | using Microsoft.Extensions.Options; 8 | using System.Text.Json; 9 | using System.Text.Json.Serialization; 10 | using System.Text.Encodings.Web; 11 | using System.ComponentModel.DataAnnotations; 12 | using Microsoft.AspNetCore.Components; 13 | 14 | namespace Mcp.Links.Http.Pages.Mcp 15 | { 16 | public partial class ServerDetailBase : ComponentBase 17 | { 18 | [Parameter] public string ServerId { get; set; } = ""; 19 | 20 | [Inject] protected IMcpServerService McpServerService { get; set; } = default!; 21 | [Inject] protected IMessageService MessageService { get; set; } = default!; 22 | [Inject] protected NavigationManager Navigation { get; set; } = default!; 23 | 24 | protected McpServerInfo? serverInfo; 25 | protected McpToolInfo[] tools = Array.Empty(); 26 | protected McpPromptInfo[] prompts = Array.Empty(); 27 | protected McpResourceInfo[] resources = Array.Empty(); 28 | 29 | protected bool loading = true; 30 | protected bool loadingTools = false; 31 | protected bool loadingPrompts = false; 32 | protected bool loadingResources = false; 33 | 34 | protected override async Task OnInitializedAsync() 35 | { 36 | await LoadServerData(); 37 | } 38 | 39 | protected override async Task OnParametersSetAsync() 40 | { 41 | if (!string.IsNullOrEmpty(ServerId)) 42 | { 43 | await LoadServerData(); 44 | } 45 | } 46 | 47 | protected async Task LoadServerData() 48 | { 49 | loading = true; 50 | try 51 | { 52 | serverInfo = await McpServerService.GetServerAsync(ServerId); 53 | if (serverInfo != null) 54 | { 55 | await LoadAllData(); 56 | } 57 | } 58 | catch (System.Exception ex) 59 | { 60 | MessageService.Error($"Failed to load server data: {ex.Message}"); 61 | } 62 | finally 63 | { 64 | loading = false; 65 | } 66 | } 67 | 68 | protected async Task LoadAllData() 69 | { 70 | await Task.WhenAll( 71 | LoadTools(), 72 | LoadPrompts(), 73 | LoadResources() 74 | ); 75 | } 76 | 77 | protected async Task LoadTools() 78 | { 79 | loadingTools = true; 80 | try 81 | { 82 | tools = await McpServerService.GetServerToolsAsync(ServerId); 83 | } 84 | catch (System.Exception ex) 85 | { 86 | MessageService.Error($"Failed to load tools: {ex.Message}"); 87 | tools = Array.Empty(); 88 | } 89 | finally 90 | { 91 | loadingTools = false; 92 | } 93 | } 94 | 95 | protected async Task LoadPrompts() 96 | { 97 | loadingPrompts = true; 98 | try 99 | { 100 | prompts = await McpServerService.GetServerPromptsAsync(ServerId); 101 | } 102 | catch (System.Exception ex) 103 | { 104 | MessageService.Error($"Failed to load prompts: {ex.Message}"); 105 | prompts = Array.Empty(); 106 | } 107 | finally 108 | { 109 | loadingPrompts = false; 110 | } 111 | } 112 | 113 | protected async Task LoadResources() 114 | { 115 | loadingResources = true; 116 | try 117 | { 118 | resources = await McpServerService.GetServerResourcesAsync(ServerId); 119 | } 120 | catch (System.Exception ex) 121 | { 122 | MessageService.Error($"Failed to load resources: {ex.Message}"); 123 | resources = Array.Empty(); 124 | } 125 | finally 126 | { 127 | loadingResources = false; 128 | } 129 | } 130 | 131 | protected async Task RefreshData() 132 | { 133 | await LoadServerData(); 134 | MessageService.Success("Server data refreshed successfully."); 135 | } 136 | 137 | protected async Task RefreshTools() 138 | { 139 | await LoadTools(); 140 | StateHasChanged(); 141 | } 142 | 143 | protected async Task RefreshPrompts() 144 | { 145 | await LoadPrompts(); 146 | StateHasChanged(); 147 | } 148 | 149 | protected async Task RefreshResources() 150 | { 151 | await LoadResources(); 152 | StateHasChanged(); 153 | } 154 | 155 | protected void GoBack() 156 | { 157 | Navigation.NavigateTo("/mcp/servers"); 158 | } 159 | 160 | protected void OnCollapseChange(string[] keys) 161 | { 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/McpToolsHandler.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging; 5 | using Microsoft.Extensions.Options; 6 | using ModelContextProtocol.Client; 7 | using ModelContextProtocol.Protocol; 8 | using ModelContextProtocol.Server; 9 | 10 | namespace Mcp.Links.Aggregation; 11 | 12 | public sealed class McpToolsHandler 13 | { 14 | private readonly IHttpContextAccessor _httpContextAccessor; 15 | 16 | private readonly IOptionsMonitor _clientConfigOptions; 17 | private readonly McpClientsFactory _mcpClientsFactory; 18 | private readonly ILogger _logger; 19 | 20 | public McpToolsHandler(IHttpContextAccessor httpContextAccessor, 21 | IOptionsMonitor clientConfigOptions, 22 | McpClientsFactory mcpClientsFactory, ILogger logger) 23 | { 24 | _httpContextAccessor = httpContextAccessor; 25 | _clientConfigOptions = clientConfigOptions; 26 | _mcpClientsFactory = mcpClientsFactory; 27 | _logger = logger; 28 | } 29 | 30 | 31 | /// 32 | /// Retrieves a list of instances associated with the specified application ID. 33 | /// 34 | /// The application ID to filter clients by. 35 | /// A cancellation token for the asynchronous operation. 36 | /// A list of objects matching the application ID. 37 | private async Task> GetClientWrappersByAppId(string appId, CancellationToken cancellation) 38 | { 39 | if (string.IsNullOrEmpty(appId)) 40 | return new List(); 41 | 42 | var clientWrappersTask = _mcpClientsFactory.GetOrCreateClientsAsync(cancellation); 43 | var clientInfo = _clientConfigOptions.CurrentValue.McpClients? 44 | .FirstOrDefault(c => string.Equals(c.AppId, appId, StringComparison.OrdinalIgnoreCase)); 45 | 46 | if (clientInfo?.McpServerIds == null || clientInfo.McpServerIds.Length == 0) 47 | return new List(); 48 | 49 | var serverIdSet = new HashSet(clientInfo.McpServerIds, StringComparer.OrdinalIgnoreCase); 50 | var clientWrappers = await clientWrappersTask.ConfigureAwait(false); 51 | 52 | return clientWrappers 53 | .Where(cw => serverIdSet.Contains(cw.Name)) 54 | .ToList(); 55 | } 56 | 57 | public async ValueTask ListAggregatedToolsAsync(RequestContext request, CancellationToken cancellation) 58 | { 59 | var appId = _httpContextAccessor.HttpContext?.Request.Headers["X-AppId"].FirstOrDefault(); 60 | 61 | var clientWrappers = await GetClientWrappersByAppId(appId ?? string.Empty, cancellation).ConfigureAwait(false); 62 | var toolListTasks = clientWrappers.Select(async clientWrapper => 63 | { 64 | try 65 | { 66 | var clientTools = await clientWrapper.McpClient.ListToolsAsync(cancellationToken: cancellation); 67 | return clientTools.Select(tool => 68 | { 69 | var protocolTool = tool.ProtocolTool; 70 | protocolTool.Name = $"{clientWrapper.Name}-{protocolTool.Name}"; 71 | return protocolTool; 72 | }).ToList(); 73 | } 74 | catch (Exception ex) 75 | { 76 | _logger.LogError(ex, "Failed to list tools from MCP client '{ClientName}': {ErrorMessage}", 77 | clientWrapper.Name, ex.Message); 78 | return new List(); 79 | } 80 | }); 81 | 82 | var toolLists = await Task.WhenAll(toolListTasks).ConfigureAwait(false); 83 | 84 | return new ListToolsResult 85 | { 86 | Tools = toolLists.SelectMany(t => t).ToList() 87 | }; 88 | } 89 | 90 | public async ValueTask CallAggregatedToolAsync(RequestContext request, CancellationToken cancellation) 91 | { 92 | var clientWrappers = await _mcpClientsFactory.GetOrCreateClientsAsync(cancellation).ConfigureAwait(false); 93 | 94 | var splitToolNames = request.Params?.Name.Split('-'); 95 | if (splitToolNames == null || splitToolNames.Length != 2) 96 | { 97 | throw new ArgumentException("Tool name must be in the format 'ClientName-ToolName'.", nameof(request)); 98 | } 99 | 100 | var targetClientName = splitToolNames[0]; 101 | var toolName = splitToolNames[1]; 102 | var clientWrapper = clientWrappers.FirstOrDefault(cw => cw.Name == targetClientName); 103 | 104 | if (clientWrapper == null) 105 | { 106 | throw new InvalidOperationException($"No client found for tool '{toolName}'"); 107 | } 108 | 109 | var convertedArguments = request.Params?.Arguments? 110 | .ToDictionary( 111 | kvp => kvp.Key, 112 | kvp => (object?)kvp.Value); 113 | 114 | return await clientWrapper.McpClient.CallToolAsync( 115 | toolName: toolName, 116 | arguments: convertedArguments, 117 | cancellationToken: cancellation); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Services/IMcpServerService.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | 3 | namespace Mcp.Links.Http.Services; 4 | 5 | /// 6 | /// Service interface for managing MCP server configurations. 7 | /// 8 | public interface IMcpServerService 9 | { 10 | /// 11 | /// Gets all MCP server configurations. 12 | /// 13 | /// Array of MCP server information objects. 14 | Task GetAllServersAsync(); 15 | 16 | /// 17 | /// Gets a specific MCP server configuration by ID. 18 | /// 19 | /// The server ID to retrieve. 20 | /// The server information if found, null otherwise. 21 | Task GetServerAsync(string serverId); 22 | 23 | /// 24 | /// Creates a new MCP server configuration. 25 | /// 26 | /// The unique server ID. 27 | /// The server configuration. 28 | /// Task representing the asynchronous operation. 29 | Task CreateServerAsync(string serverId, McpServerConfig serverConfig); 30 | 31 | /// 32 | /// Updates an existing MCP server configuration. 33 | /// 34 | /// The server ID to update. 35 | /// The updated server configuration. 36 | /// Task representing the asynchronous operation. 37 | Task UpdateServerAsync(string serverId, McpServerConfig serverConfig); 38 | 39 | /// 40 | /// Deletes an MCP server configuration. 41 | /// 42 | /// The server ID to delete. 43 | /// Task representing the asynchronous operation. 44 | Task DeleteServerAsync(string serverId); 45 | 46 | /// 47 | /// Toggles the enabled status of an MCP server. 48 | /// 49 | /// The server ID to toggle. 50 | /// The new enabled status. 51 | /// Task representing the asynchronous operation. 52 | Task ToggleServerStatusAsync(string serverId, bool enabled); 53 | 54 | /// 55 | /// Validates a server configuration. 56 | /// 57 | /// The server configuration to validate. 58 | /// True if valid, false otherwise. 59 | bool ValidateServerConfig(McpServerConfig serverConfig); 60 | 61 | /// 62 | /// Gets validation errors for a server configuration. 63 | /// 64 | /// The server configuration to validate. 65 | /// Collection of validation error messages. 66 | IEnumerable GetValidationErrors(McpServerConfig serverConfig); 67 | 68 | /// 69 | /// Checks if a server ID already exists. 70 | /// 71 | /// The server ID to check. 72 | /// True if the server ID exists, false otherwise. 73 | Task ServerExistsAsync(string serverId); 74 | 75 | /// 76 | /// Gets tools for a specific MCP server. 77 | /// 78 | /// The server ID to get tools for. 79 | /// List of tools for the specified server. 80 | Task GetServerToolsAsync(string serverId); 81 | 82 | /// 83 | /// Gets prompts for a specific MCP server. 84 | /// 85 | /// The server ID to get prompts for. 86 | /// List of prompts for the specified server. 87 | Task GetServerPromptsAsync(string serverId); 88 | 89 | /// 90 | /// Gets resources for a specific MCP server. 91 | /// 92 | /// The server ID to get resources for. 93 | /// List of resources for the specified server. 94 | Task GetServerResourcesAsync(string serverId); 95 | 96 | /// 97 | /// Gets the raw mcp.json configuration file content. 98 | /// 99 | /// The raw JSON content of the mcp.json file. 100 | Task GetMcpJsonContentAsync(); 101 | } 102 | 103 | /// 104 | /// Data transfer object for MCP server information. 105 | /// 106 | public class McpServerInfo 107 | { 108 | public required string ServerId { get; set; } 109 | public required string Type { get; set; } 110 | public bool Enabled { get; set; } 111 | public string? Command { get; set; } 112 | public string? Url { get; set; } 113 | public string[]? Args { get; set; } 114 | public int EnvCount { get; set; } 115 | public Dictionary? Environment { get; set; } 116 | public int HeadersCount { get; set; } 117 | public Dictionary? Headers { get; set; } 118 | public bool IsValid { get; set; } 119 | public string[] ValidationErrors { get; set; } = Array.Empty(); 120 | public required string Configuration { get; set; } 121 | } 122 | 123 | /// 124 | /// Data transfer object for MCP tool information. 125 | /// 126 | public class McpToolInfo 127 | { 128 | public required string Name { get; set; } 129 | public string? Description { get; set; } 130 | public object? InputSchema { get; set; } 131 | } 132 | 133 | /// 134 | /// Data transfer object for MCP prompt information. 135 | /// 136 | public class McpPromptInfo 137 | { 138 | public required string Name { get; set; } 139 | public string? Description { get; set; } 140 | public object[]? Arguments { get; set; } 141 | } 142 | 143 | /// 144 | /// Data transfer object for MCP resource information. 145 | /// 146 | public class McpResourceInfo 147 | { 148 | public required string Uri { get; set; } 149 | public required string Name { get; set; } 150 | public string? Description { get; set; } 151 | public string? MimeType { get; set; } 152 | } 153 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Welcome.razor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components; 2 | using Mcp.Links.Http.Services; 3 | using Mcp.Links.Configuration; 4 | using System.Text.Json; 5 | 6 | namespace Mcp.Links.Http.Pages; 7 | 8 | public partial class Welcome 9 | { 10 | [Inject] private IMcpServerService McpServerService { get; set; } = default!; 11 | [Inject] private IMcpClientAppService McpClientAppService { get; set; } = default!; 12 | [Inject] private IMcpStoreService McpStoreService { get; set; } = default!; 13 | [Inject] private NavigationManager Navigation { get; set; } = default!; 14 | 15 | private DashboardStats stats = new(); 16 | private bool isLoading = true; 17 | private string[] recentActivities = Array.Empty(); 18 | 19 | protected override async Task OnInitializedAsync() 20 | { 21 | await LoadDashboardData(); 22 | } 23 | 24 | private async Task LoadDashboardData() 25 | { 26 | try 27 | { 28 | isLoading = true; 29 | 30 | // Load server configurations 31 | var servers = await McpServerService.GetAllServersAsync(); 32 | var clientApps = await McpClientAppService.GetAllClientAppsAsync(); 33 | var storeServers = await McpStoreService.GetAllStoreServersAsync(); 34 | 35 | stats = new DashboardStats 36 | { 37 | StoreServers = storeServers.Count, 38 | InstalledServers = servers.Length, 39 | ConnectedServers = servers.Count(s => s.Enabled && s.IsValid), 40 | ClientApps = clientApps.Length, 41 | TotalServers = servers.Length, 42 | EnabledServers = servers.Count(s => s.Enabled), 43 | TotalClientApps = clientApps.Length, 44 | AvailableTools = await GetTotalToolsCount(servers), 45 | AvailableResources = await GetTotalResourcesCount(servers) 46 | }; 47 | 48 | // Generate recent activities 49 | recentActivities = GenerateRecentActivities(servers, clientApps); 50 | } 51 | catch (System.Exception ex) 52 | { 53 | // Handle error gracefully 54 | stats = new DashboardStats(); 55 | recentActivities = new[] { $"Error loading data: {ex.Message}" }; 56 | } 57 | finally 58 | { 59 | isLoading = false; 60 | } 61 | } 62 | 63 | private async Task GetTotalToolsCount(McpServerInfo[] servers) 64 | { 65 | int totalTools = 0; 66 | foreach (var server in servers.Where(s => s.Enabled && s.IsValid)) 67 | { 68 | try 69 | { 70 | var tools = await McpServerService.GetServerToolsAsync(server.ServerId); 71 | totalTools += tools.Length; 72 | } 73 | catch 74 | { 75 | // If unable to get tools, estimate 2 tools per server 76 | totalTools += 2; 77 | } 78 | } 79 | return totalTools; 80 | } 81 | 82 | private async Task GetTotalResourcesCount(McpServerInfo[] servers) 83 | { 84 | int totalResources = 0; 85 | foreach (var server in servers.Where(s => s.Enabled && s.IsValid)) 86 | { 87 | try 88 | { 89 | var resources = await McpServerService.GetServerResourcesAsync(server.ServerId); 90 | totalResources += resources.Length; 91 | } 92 | catch 93 | { 94 | // If unable to get resources, estimate 1 resource per server 95 | totalResources += 1; 96 | } 97 | } 98 | return totalResources; 99 | } 100 | 101 | private string[] GenerateRecentActivities(McpServerInfo[] servers, McpClientConfig[] clientApps) 102 | { 103 | var activities = new List(); 104 | 105 | var enabledServers = servers.Where(s => s.Enabled).Take(3); 106 | foreach (var server in enabledServers) 107 | { 108 | if (server.IsValid) 109 | { 110 | activities.Add($"Server '{server.ServerId}' is running ({server.Type})"); 111 | } 112 | else 113 | { 114 | activities.Add($"Server '{server.ServerId}' has configuration issues"); 115 | } 116 | } 117 | 118 | if (clientApps.Any()) 119 | { 120 | activities.Add($"Configured {clientApps.Length} client app(s)"); 121 | } 122 | 123 | var disabledCount = servers.Count(s => !s.Enabled); 124 | if (disabledCount > 0) 125 | { 126 | activities.Add($"{disabledCount} server(s) are disabled"); 127 | } 128 | 129 | if (!activities.Any()) 130 | { 131 | activities.Add("No recent activity - Add your first server to get started"); 132 | } 133 | 134 | return activities.ToArray(); 135 | } 136 | 137 | private void NavigateToServers() 138 | { 139 | Navigation.NavigateTo("/mcp/servers"); 140 | } 141 | 142 | private void NavigateToInspector() 143 | { 144 | Navigation.NavigateTo("/mcp/inspector"); 145 | } 146 | 147 | private void NavigateToEnvCheck() 148 | { 149 | Navigation.NavigateTo("/mcp/env-check"); 150 | } 151 | 152 | private void NavigateToStore() 153 | { 154 | Navigation.NavigateTo("/mcp/store"); 155 | } 156 | 157 | private void NavigateToClientApps() 158 | { 159 | Navigation.NavigateTo("/mcp/clients"); 160 | } 161 | 162 | private void NavigateToGitHub() 163 | { 164 | Navigation.NavigateTo("https://github.com/sheng-jie/Mcp.Links"); 165 | } 166 | 167 | public class DashboardStats 168 | { 169 | public int StoreServers { get; set; } 170 | public int InstalledServers { get; set; } 171 | public int ConnectedServers { get; set; } 172 | public int ClientApps { get; set; } 173 | public int TotalServers { get; set; } 174 | public int EnabledServers { get; set; } 175 | public int TotalClientApps { get; set; } 176 | public int AvailableTools { get; set; } 177 | public int AvailableResources { get; set; } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Resources/I18n.zh-CN.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 个人中心 122 | 123 | 124 | 退出登录 125 | 126 | 127 | 个人设置 128 | 129 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Resources/I18n.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | Account Center 122 | 123 | 124 | Logout 125 | 126 | 127 | Settings 128 | 129 | -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/AggregatedMcpServerFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using Mcp.Links.Configuration; 4 | using ModelContextProtocol; 5 | using ModelContextProtocol.Client; 6 | using ModelContextProtocol.Protocol; 7 | using ModelContextProtocol.Server; 8 | 9 | namespace Mcp.Links.Aggregation; 10 | 11 | [Obsolete("This class is obsolete and will be removed in a future version.")] 12 | public class AggregatedMcpServerFactory 13 | { 14 | private readonly IEnumerable _clientWrappers; 15 | 16 | public AggregatedMcpServerFactory(IEnumerable clientWrappers) 17 | { 18 | _clientWrappers = clientWrappers; 19 | } 20 | 21 | public IMcpServer CreateAggregatedServer() 22 | { 23 | McpServerOptions options = new() 24 | { 25 | ServerInfo = new Implementation 26 | { 27 | Name = "Aggregated MCP Server", 28 | Version = "1.0.0", 29 | Title = "An aggregated MCP server that combines multiple client functionalities.", 30 | }, 31 | ProtocolVersion = "2025-06-18", 32 | Capabilities = new ServerCapabilities 33 | { 34 | Tools = ConfigureTools(), 35 | Resources = ConfigureResources(), 36 | Prompts = ConfigurePrompts(), 37 | // Logging = ConfigureLogging(), 38 | // Completions = ConfigureCompletions(), 39 | }, 40 | ServerInstructions = "This server aggregates multiple MCP clients. Use the tools provided to interact with the underlying clients.", 41 | }; 42 | 43 | var stdioTransport = new StdioServerTransport("AggregatedMcpServer"); 44 | IMcpServer server = McpServerFactory.Create(stdioTransport, options); 45 | 46 | return server; 47 | } 48 | 49 | private CompletionsCapability ConfigureCompletions() 50 | { 51 | throw new NotImplementedException(); 52 | } 53 | 54 | private LoggingCapability ConfigureLogging() 55 | { 56 | 57 | return new LoggingCapability 58 | { 59 | SetLoggingLevelHandler = async (request, cancellationToken) => 60 | { 61 | if (request.Params?.Level is null) 62 | { 63 | throw new McpException("Missing required argument 'level'", McpErrorCode.InvalidParams); 64 | } 65 | 66 | // _minimumLoggingLevel = request.Params.Level; 67 | 68 | return new EmptyResult(); 69 | } 70 | }; 71 | } 72 | 73 | private PromptsCapability ConfigurePrompts() 74 | { 75 | 76 | return new PromptsCapability 77 | { 78 | ListPromptsHandler = async (request, cancellation) => 79 | { 80 | var prompts = new List(); 81 | foreach (var clientWrapper in _clientWrappers) 82 | { 83 | var clientPrompts = await clientWrapper.McpClient.ListPromptsAsync(cancellationToken: cancellation); 84 | prompts.AddRange(clientPrompts.Select(p => p.ProtocolPrompt)); 85 | } 86 | 87 | return new ListPromptsResult 88 | { 89 | Prompts = prompts 90 | }; 91 | } 92 | }; 93 | } 94 | 95 | private ResourcesCapability ConfigureResources() 96 | { 97 | return new ResourcesCapability 98 | { 99 | ListResourcesHandler = async (request, cancellation) => 100 | { 101 | var resources = new List(); 102 | foreach (var clientWrapper in _clientWrappers) 103 | { 104 | var clientResources = await clientWrapper.McpClient.ListResourcesAsync(cancellationToken: cancellation); 105 | resources.AddRange(clientResources.Select(r => r.ProtocolResource)); 106 | } 107 | 108 | return new ListResourcesResult 109 | { 110 | Resources = resources 111 | }; 112 | } 113 | }; 114 | } 115 | 116 | private ToolsCapability ConfigureTools() 117 | { 118 | return new ToolsCapability 119 | { 120 | ListToolsHandler = ListAggregatedToolsAsync, 121 | CallToolHandler = CallAggregatedToolAsync 122 | }; 123 | } 124 | 125 | private async ValueTask ListAggregatedToolsAsync(RequestContext request, CancellationToken cancellation) 126 | { 127 | var toolLists = await Task.WhenAll( 128 | _clientWrappers.Select(async clientWrapper => 129 | { 130 | var clientTools = await clientWrapper.McpClient.ListToolsAsync(cancellationToken: cancellation); 131 | return clientTools.Select(tool => 132 | { 133 | var protocolTool = tool.ProtocolTool; 134 | protocolTool.Name = $"{clientWrapper.Name}.{protocolTool.Name}"; 135 | return protocolTool; 136 | }); 137 | }) 138 | ).ConfigureAwait(false); 139 | 140 | return new ListToolsResult 141 | { 142 | Tools = toolLists.SelectMany(t => t).ToList() 143 | }; 144 | } 145 | 146 | private async ValueTask CallAggregatedToolAsync(RequestContext request, CancellationToken cancellation) 147 | { 148 | var splitToolNames = request.Params?.Name.Split('.'); 149 | if (splitToolNames == null || splitToolNames.Length != 2) 150 | { 151 | throw new ArgumentException("Tool name must be in the format 'ClientName.ToolName'.", nameof(request)); 152 | } 153 | 154 | var targetClientName = splitToolNames[0]; 155 | var toolName = splitToolNames[1]; 156 | var clientWrapper = _clientWrappers.FirstOrDefault(cw => cw.Name == targetClientName); 157 | 158 | if (clientWrapper == null) 159 | { 160 | throw new InvalidOperationException($"No client found for tool '{toolName}'"); 161 | } 162 | 163 | var convertedArguments = request.Params?.Arguments? 164 | .ToDictionary( 165 | kvp => kvp.Key, 166 | kvp => (object?)kvp.Value); 167 | 168 | return await clientWrapper.McpClient.CallToolAsync( 169 | toolName: toolName, 170 | arguments: convertedArguments, 171 | cancellationToken: cancellation); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Services/IMcpInspectorService.cs: -------------------------------------------------------------------------------- 1 | using ModelContextProtocol.Protocol; 2 | 3 | namespace Mcp.Links.Http.Services; 4 | 5 | /// 6 | /// Service interface for MCP Inspector functionality. 7 | /// Provides methods for connecting to and interacting with MCP servers for testing and debugging. 8 | /// 9 | public interface IMcpInspectorService 10 | { 11 | /// 12 | /// Tests connection to a specific MCP server. 13 | /// 14 | /// The server ID to test. 15 | /// Connection test result. 16 | Task TestConnectionAsync(string serverId); 17 | 18 | /// 19 | /// Gets all available tools from a specific MCP server. 20 | /// 21 | /// The server ID to get tools from. 22 | /// List of available tools. 23 | Task GetServerToolsAsync(string serverId); 24 | 25 | /// 26 | /// Calls a specific tool on an MCP server. 27 | /// 28 | /// The server ID. 29 | /// The name of the tool to call. 30 | /// The tool arguments. 31 | /// The tool call result. 32 | Task CallToolAsync(string serverId, string toolName, Dictionary? arguments = null); 33 | 34 | /// 35 | /// Gets all available resources from a specific MCP server. 36 | /// 37 | /// The server ID to get resources from. 38 | /// List of available resources. 39 | Task GetServerResourcesAsync(string serverId); 40 | 41 | /// 42 | /// Reads a specific resource from an MCP server. 43 | /// 44 | /// The server ID. 45 | /// The URI of the resource to read. 46 | /// The resource content. 47 | Task ReadResourceAsync(string serverId, string resourceUri); 48 | 49 | /// 50 | /// Gets all available prompts from a specific MCP server. 51 | /// 52 | /// The server ID to get prompts from. 53 | /// List of available prompts. 54 | Task GetServerPromptsAsync(string serverId); 55 | 56 | /// 57 | /// Gets a specific prompt from an MCP server. 58 | /// 59 | /// The server ID. 60 | /// The name of the prompt to get. 61 | /// The prompt arguments. 62 | /// The prompt content. 63 | Task GetPromptAsync(string serverId, string promptName, Dictionary? arguments = null); 64 | 65 | /// 66 | /// Gets server information and capabilities. 67 | /// 68 | /// The server ID. 69 | /// Server information. 70 | Task GetServerInfoAsync(string serverId); 71 | 72 | /// 73 | /// Exports a server configuration for use in other MCP clients. 74 | /// 75 | /// The server ID to export. 76 | /// The exported configuration. 77 | Task ExportServerConfigAsync(string serverId); 78 | 79 | /// 80 | /// Exports all servers configuration as a complete mcp.json file. 81 | /// 82 | /// The complete mcp.json configuration. 83 | Task ExportAllServersConfigAsync(); 84 | } 85 | 86 | /// 87 | /// Result of a connection test to an MCP server. 88 | /// 89 | public class McpConnectionTestResult 90 | { 91 | public bool IsConnected { get; set; } 92 | public string? ErrorMessage { get; set; } 93 | public TimeSpan ConnectionTime { get; set; } 94 | public string? ServerVersion { get; set; } 95 | public ServerCapabilities? Capabilities { get; set; } 96 | } 97 | 98 | /// 99 | /// Extended tool information for the inspector. 100 | /// 101 | public class McpInspectorTool 102 | { 103 | public required string Name { get; set; } 104 | public string? Description { get; set; } 105 | public object? InputSchema { get; set; } 106 | public bool IsParameterless => InputSchema == null || 107 | (InputSchema is System.Text.Json.JsonElement elem && elem.ValueKind == System.Text.Json.JsonValueKind.Object && !elem.EnumerateObject().Any()); 108 | } 109 | 110 | /// 111 | /// Result of a tool call. 112 | /// 113 | public class McpToolCallResult 114 | { 115 | public bool IsSuccess { get; set; } 116 | public string? ErrorMessage { get; set; } 117 | public object? Result { get; set; } 118 | public string? RawResponse { get; set; } 119 | public TimeSpan ExecutionTime { get; set; } 120 | } 121 | 122 | /// 123 | /// Extended resource information for the inspector. 124 | /// 125 | public class McpInspectorResource 126 | { 127 | public required string Uri { get; set; } 128 | public required string Name { get; set; } 129 | public string? Description { get; set; } 130 | public string? MimeType { get; set; } 131 | } 132 | 133 | /// 134 | /// Content of a resource. 135 | /// 136 | public class McpResourceContent 137 | { 138 | public required string Uri { get; set; } 139 | public required string Content { get; set; } 140 | public string? MimeType { get; set; } 141 | public long? Size { get; set; } 142 | } 143 | 144 | /// 145 | /// Extended prompt information for the inspector. 146 | /// 147 | public class McpInspectorPrompt 148 | { 149 | public required string Name { get; set; } 150 | public string? Description { get; set; } 151 | public object[]? Arguments { get; set; } 152 | public bool HasArguments => Arguments != null && Arguments.Length > 0; 153 | } 154 | 155 | /// 156 | /// Content of a prompt. 157 | /// 158 | public class McpPromptContent 159 | { 160 | public required string Name { get; set; } 161 | public required object[] Messages { get; set; } 162 | public string? Description { get; set; } 163 | } 164 | 165 | /// 166 | /// Server export configuration. 167 | /// 168 | public class McpServerExport 169 | { 170 | public required string ServerId { get; set; } 171 | public required object Configuration { get; set; } 172 | public required string ConfigType { get; set; } // "server-entry" or "complete-file" 173 | } 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [简体中文](README_zh-cn.md) | [English](README.md) 2 | 3 | 4 | ![](./doc/imgs/intro.png) 5 | 6 | # Mcp.Links 7 | 8 | A powerful Model Context Protocol (MCP) aggregator built with .NET 9.0 that enables seamless integration and management of multiple MCP servers. This project provides both HTTP and command-line interfaces for aggregating various MCP servers into a unified platform. 9 | 10 | ## 🚀 Features 11 | 12 | - **Multi-Protocol Support**: Aggregates MCP servers via stdio, HTTP, and SSE protocols 13 | - **Web Management Interface**: Intuitive Blazor-based UI for managing MCP servers and client applications 14 | - **MCP Store**: Built-in marketplace for discovering and installing pre-configured MCP servers 15 | - **Authentication**: Built-in API key authentication for secure access 16 | - **Real-time Inspector**: Monitor and inspect MCP server communications 17 | - **Client App Management**: Configure different client applications with specific MCP server access 18 | - **Tool Aggregation**: Seamlessly combine tools from multiple MCP servers 19 | - **Docker Support**: Ready-to-deploy containerized solution 20 | - **Multi-environment Support**: Configurable for development and production environments 21 | 22 | ## 📦 Installation & Usage 23 | 24 | ### ⚡ Quick Start 25 | 26 | Get started quickly using the pre-built Docker image: 27 | 28 | ```bash 29 | # Run with default configuration 30 | docker run -p 8080:8080 ghcr.io/sheng-jie/mcp-links:v0.4 31 | 32 | # Run with custom configuration files 33 | docker run -p 8080:8080 \ 34 | -v $(pwd)/mcp.json:/app/mcp.json \ 35 | -v $(pwd)/client-apps.json:/app/client-apps.json \ 36 | ghcr.io/sheng-jie/mcp-links:v0.4 37 | ``` 38 | 39 | The application will be available at `http://localhost:8080` with the MCP endpoint at `/mcp`. 40 | 41 | ### 📋 Prerequisites 42 | 43 | - .NET 9.0 SDK 44 | - Node.js (for running Node-based MCP servers) 45 | - Python 3.x with uv/uvx (for Python-based MCP servers) 46 | 47 | ### 1. HTTP Server Mode (Recommended) 48 | 49 | Run the web-based management interface: 50 | 51 | ```bash 52 | dotnet run --project src/Mcp.Links.Http/Mcp.Links.Http.csproj 53 | ``` 54 | 55 | The server will start on `http://localhost:5146` with the MCP endpoint available at `/mcp`. 56 | 57 | Visit `http://localhost:5146/mcp/env-check` to check if your local environment is satisfied. 58 | 59 | ### 2. Configuration 60 | 61 | #### MCP Servers Configuration (`mcp.json`) 62 | 63 | ```json 64 | { 65 | "mcpServers": { 66 | "fetch": { 67 | "enabled": true, 68 | "type": "stdio", 69 | "command": "uvx", 70 | "args": ["mcp-server-fetch"], 71 | "env": { 72 | "node-env": "dev", 73 | "port": "3300" 74 | } 75 | }, 76 | "time": { 77 | "enabled": true, 78 | "type": "stdio", 79 | "command": "uvx", 80 | "args": ["mcp-server-time", "--local-timezone=Asia/Shanghai"] 81 | }, 82 | "microsoft-learn": { 83 | "enabled": false, 84 | "type": "http", 85 | "url": "https://learn.microsoft.com/api/mcp" 86 | } 87 | } 88 | } 89 | ``` 90 | 91 | #### Client Applications Configuration (`client-apps.json`) 92 | 93 | ```json 94 | { 95 | "mcpClients": [ 96 | { 97 | "appId": "vscode", 98 | "appKey": "your-api-key-here", 99 | "name": "VS Code", 100 | "description": "VS Code MCP client", 101 | "mcpServerIds": ["fetch", "time"] 102 | } 103 | ] 104 | } 105 | ``` 106 | 107 | ### 3. Build and Deploy with Docker 108 | 109 | Build and run with Docker: 110 | 111 | ```bash 112 | # Build the image 113 | docker build -t mcp-links . 114 | 115 | # Run the container 116 | docker run -p 8080:8080 \ 117 | -v $(pwd)/mcp.json:/app/mcp.json \ 118 | -v $(pwd)/client-apps.json:/app/client-apps.json \ 119 | mcp-links 120 | ``` 121 | 122 | ### 4. Custom Configuration File 123 | 124 | Specify a custom configuration file: 125 | 126 | ```bash 127 | dotnet run --project src/Mcp.Links.Http/Mcp.Links.Http.csproj --mcp-file=/path/to/custom-mcp.json 128 | ``` 129 | 130 | 131 | ## 🔧 Supported MCP Server Types 132 | 133 | ### Stdio Servers 134 | - **Python-based**: Using `uvx` or `pip` installed packages 135 | - **.NET-based**: Using `dnx` command with .NET tools 136 | - **Node.js-based**: Using `npx` or globally installed packages 137 | 138 | ### HTTP Servers 139 | - RESTful MCP servers with standard HTTP endpoints 140 | - Custom authentication header support 141 | 142 | ### SSE (Server-Sent Events) 143 | - Real-time streaming MCP servers 144 | - Event-based communication 145 | 146 | ## 🎯 Use Cases 147 | 148 | - **AI Development**: Aggregate multiple AI tools and services into a single MCP interface 149 | - **Enterprise Integration**: Centralize various business tools and APIs 150 | - **Development Workflow**: Combine code analysis, documentation, and deployment tools 151 | - **Research Platform**: Integrate data analysis, visualization, and machine learning tools 152 | - **Rapid Prototyping**: Quickly discover and integrate MCP servers from the built-in store 153 | - **Multi-client Management**: Configure different tool sets for various AI clients (VS Code, Cursor, Claude Desktop) 154 | 155 | ## 🔒 Security Features 156 | 157 | - **API Key Authentication**: Secure access control for client applications 158 | - **Client-specific Server Access**: Granular permissions for different client applications 159 | - **Environment Isolation**: Separate configurations for different environments 160 | - **Request Validation**: Built-in request validation and error handling 161 | 162 | ## 🌐 Web Interface Features 163 | 164 | The web management interface provides: 165 | 166 | - **Server Management**: Add, edit, disable/enable MCP servers 167 | - **MCP Store**: Browse and install MCP servers from a curated marketplace featuring 40+ pre-configured servers including: 168 | - **AI Services**: Time conversion, web search (Brave, Perplexity, Zhipu), image generation (EverArt, MiniMax) 169 | - **Development Tools**: GitHub/GitLab integration, Figma context, browser automation (Playwright, Puppeteer) 170 | - **Database Access**: PostgreSQL, Redis, Neon database management 171 | - **Content & Communication**: Slack integration, email sending (Mailtrap), note-taking (Flomo) 172 | - **Location Services**: Google Maps, Baidu Maps, Amap Maps with geocoding and routing 173 | - **Specialized Tools**: Blender 3D modeling, sequential thinking, AWS knowledge base retrieval 174 | - **Real-time Monitoring**: View server status and communication logs 175 | - **Tool Inspector**: Browse available tools from all connected servers 176 | - **Client App Management**: Configure API keys and server access for different clients 177 | - **Configuration Editor**: Direct editing of JSON configuration files 178 | - **Internationalization**: Support for multiple languages (English, Chinese) 179 | 180 | ## 📊 Monitoring & Debugging 181 | 182 | - **Health Checks**: Monitor the status of all connected MCP servers 183 | - **Request Logging**: Track all MCP communications for debugging 184 | - **Error Handling**: Comprehensive error reporting and recovery 185 | - **Performance Metrics**: Monitor response times and server performance 186 | 187 | ## 🚀 Development & Extension 188 | 189 | ### Adding New MCP Servers 190 | 191 | 1. Update your `mcp.json` configuration 192 | 2. Restart the application or use hot-reload 193 | 3. Verify connectivity through the web interface 194 | 195 | ### Custom Transport Types 196 | 197 | The system supports extending with custom transport implementations by implementing the transport interfaces in the core library. 198 | 199 | ## 🤝 Contributing 200 | 201 | Contributions are welcome! Please feel free to submit pull requests, report issues, or suggest new features. 202 | 203 | ## 📄 License 204 | 205 | This project is licensed under the terms specified in the [LICENSE.txt](LICENSE.txt) file. 206 | 207 | --- 208 | 209 | **Built with ❤️ using .NET 9.0, AntBlazor, and the MCP C# SDK** 210 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Ant Design Pro Blazor 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 180 |
188 | logo 189 |
190 |
191 | 194 |
195 |
196 |
197 | 199 | Ant Design Blazor
200 |
201 |
202 |
203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Reboot v5.3.3 (https://getbootstrap.com/) 3 | * Copyright 2011-2024 The Bootstrap Authors 4 | * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) 5 | */:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, 0.175);--bs-border-radius:0.375rem;--bs-border-radius-sm:0.25rem;--bs-border-radius-lg:0.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width:0.25rem;--bs-focus-ring-opacity:0.25;--bs-focus-ring-color:rgba(13, 110, 253, 0.25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, 0.5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherit;--bs-link-color:#6ea8fe;--bs-link-hover-color:#8bb9fe;--bs-link-color-rgb:110,168,254;--bs-link-hover-color-rgb:139,185,254;--bs-code-color:#e685b5;--bs-highlight-color:#dee2e6;--bs-highlight-bg:#664d03;--bs-border-color:#495057;--bs-border-color-translucent:rgba(255, 255, 255, 0.15);--bs-form-valid-color:#75b798;--bs-form-valid-border-color:#75b798;--bs-form-invalid-color:#ea868f;--bs-form-invalid-border-color:#ea868f}*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;border:0;border-top:var(--bs-border-width) solid;opacity:.25}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2;color:var(--bs-heading-color)}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-left:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.1875em;color:var(--bs-highlight-color);background-color:var(--bs-highlight-bg)}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:rgba(var(--bs-link-color-rgb),var(--bs-link-opacity,1));text-decoration:underline}a:hover{--bs-link-color-rgb:var(--bs-link-hover-color-rgb)}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:var(--bs-font-monospace);font-size:1em}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:var(--bs-code-color);word-wrap:break-word}a>code{color:inherit}kbd{padding:.1875rem .375rem;font-size:.875em;color:var(--bs-body-bg);background-color:var(--bs-body-color);border-radius:.25rem}kbd kbd{padding:0;font-size:1em}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:var(--bs-secondary-color);text-align:left}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]:not([type=date]):not([type=datetime-local]):not([type=month]):not([type=week]):not([type=time])::-webkit-calendar-picker-indicator{display:none!important}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:left;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:left}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}::file-selector-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important} 6 | /*# sourceMappingURL=bootstrap-reboot.min.css.map */ -------------------------------------------------------------------------------- /src/Mcp.Links.Http/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.min.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Reboot v5.3.3 (https://getbootstrap.com/) 3 | * Copyright 2011-2024 The Bootstrap Authors 4 | * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) 5 | */:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, 0.175);--bs-border-radius:0.375rem;--bs-border-radius-sm:0.25rem;--bs-border-radius-lg:0.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width:0.25rem;--bs-focus-ring-opacity:0.25;--bs-focus-ring-color:rgba(13, 110, 253, 0.25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, 0.5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherit;--bs-link-color:#6ea8fe;--bs-link-hover-color:#8bb9fe;--bs-link-color-rgb:110,168,254;--bs-link-hover-color-rgb:139,185,254;--bs-code-color:#e685b5;--bs-highlight-color:#dee2e6;--bs-highlight-bg:#664d03;--bs-border-color:#495057;--bs-border-color-translucent:rgba(255, 255, 255, 0.15);--bs-form-valid-color:#75b798;--bs-form-valid-border-color:#75b798;--bs-form-invalid-color:#ea868f;--bs-form-invalid-border-color:#ea868f}*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;border:0;border-top:var(--bs-border-width) solid;opacity:.25}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2;color:var(--bs-heading-color)}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-right:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-right:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.1875em;color:var(--bs-highlight-color);background-color:var(--bs-highlight-bg)}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:rgba(var(--bs-link-color-rgb),var(--bs-link-opacity,1));text-decoration:underline}a:hover{--bs-link-color-rgb:var(--bs-link-hover-color-rgb)}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:var(--bs-font-monospace);font-size:1em}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:var(--bs-code-color);word-wrap:break-word}a>code{color:inherit}kbd{padding:.1875rem .375rem;font-size:.875em;color:var(--bs-body-bg);background-color:var(--bs-body-color);border-radius:.25rem}kbd kbd{padding:0;font-size:1em}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:var(--bs-secondary-color);text-align:right}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]:not([type=date]):not([type=datetime-local]):not([type=month]):not([type=week]):not([type=time])::-webkit-calendar-picker-indicator{display:none!important}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:right;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:right}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=email],[type=number],[type=tel],[type=url]{direction:ltr}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}::file-selector-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important} 6 | /*# sourceMappingURL=bootstrap-reboot.rtl.min.css.map */ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from `dotnet new gitignore` 5 | 6 | # dotenv files 7 | .env 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | 41 | .vscode/ 42 | # Uncomment if you have tasks that create the project's static files in wwwroot 43 | #wwwroot/ 44 | 45 | # Visual Studio 2017 auto generated files 46 | Generated\ Files/ 47 | 48 | # MSTest test Results 49 | [Tt]est[Rr]esult*/ 50 | [Bb]uild[Ll]og.* 51 | 52 | # NUnit 53 | *.VisualState.xml 54 | TestResult.xml 55 | nunit-*.xml 56 | 57 | # Build Results of an ATL Project 58 | [Dd]ebugPS/ 59 | [Rr]eleasePS/ 60 | dlldata.c 61 | 62 | # Benchmark Results 63 | BenchmarkDotNet.Artifacts/ 64 | 65 | # .NET 66 | project.lock.json 67 | project.fragment.lock.json 68 | artifacts/ 69 | 70 | # Tye 71 | .tye/ 72 | 73 | # ASP.NET Scaffolding 74 | ScaffoldingReadMe.txt 75 | 76 | # StyleCop 77 | StyleCopReport.xml 78 | 79 | # Files built by Visual Studio 80 | *_i.c 81 | *_p.c 82 | *_h.h 83 | *.ilk 84 | *.meta 85 | *.obj 86 | *.iobj 87 | *.pch 88 | *.pdb 89 | *.ipdb 90 | *.pgc 91 | *.pgd 92 | *.rsp 93 | *.sbr 94 | *.tlb 95 | *.tli 96 | *.tlh 97 | *.tmp 98 | *.tmp_proj 99 | *_wpftmp.csproj 100 | *.log 101 | *.tlog 102 | *.vspscc 103 | *.vssscc 104 | .builds 105 | *.pidb 106 | *.svclog 107 | *.scc 108 | 109 | # Chutzpah Test files 110 | _Chutzpah* 111 | 112 | # Visual C++ cache files 113 | ipch/ 114 | *.aps 115 | *.ncb 116 | *.opendb 117 | *.opensdf 118 | *.sdf 119 | *.cachefile 120 | *.VC.db 121 | *.VC.VC.opendb 122 | 123 | # Visual Studio profiler 124 | *.psess 125 | *.vsp 126 | *.vspx 127 | *.sap 128 | 129 | # Visual Studio Trace Files 130 | *.e2e 131 | 132 | # TFS 2012 Local Workspace 133 | $tf/ 134 | 135 | # Guidance Automation Toolkit 136 | *.gpState 137 | 138 | # ReSharper is a .NET coding add-in 139 | _ReSharper*/ 140 | *.[Rr]e[Ss]harper 141 | *.DotSettings.user 142 | 143 | # TeamCity is a build add-in 144 | _TeamCity* 145 | 146 | # DotCover is a Code Coverage Tool 147 | *.dotCover 148 | 149 | # AxoCover is a Code Coverage Tool 150 | .axoCover/* 151 | !.axoCover/settings.json 152 | 153 | # Coverlet is a free, cross platform Code Coverage Tool 154 | coverage*.json 155 | coverage*.xml 156 | coverage*.info 157 | 158 | # Visual Studio code coverage results 159 | *.coverage 160 | *.coveragexml 161 | 162 | # NCrunch 163 | _NCrunch_* 164 | .*crunch*.local.xml 165 | nCrunchTemp_* 166 | 167 | # MightyMoose 168 | *.mm.* 169 | AutoTest.Net/ 170 | 171 | # Web workbench (sass) 172 | .sass-cache/ 173 | 174 | # Installshield output folder 175 | [Ee]xpress/ 176 | 177 | # DocProject is a documentation generator add-in 178 | DocProject/buildhelp/ 179 | DocProject/Help/*.HxT 180 | DocProject/Help/*.HxC 181 | DocProject/Help/*.hhc 182 | DocProject/Help/*.hhk 183 | DocProject/Help/*.hhp 184 | DocProject/Help/Html2 185 | DocProject/Help/html 186 | 187 | # Click-Once directory 188 | publish/ 189 | 190 | # Publish Web Output 191 | *.[Pp]ublish.xml 192 | *.azurePubxml 193 | # Note: Comment the next line if you want to checkin your web deploy settings, 194 | # but database connection strings (with potential passwords) will be unencrypted 195 | *.pubxml 196 | *.publishproj 197 | 198 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 199 | # checkin your Azure Web App publish settings, but sensitive information contained 200 | # in these scripts will be unencrypted 201 | PublishScripts/ 202 | 203 | # NuGet Packages 204 | *.nupkg 205 | # NuGet Symbol Packages 206 | *.snupkg 207 | # The packages folder can be ignored because of Package Restore 208 | **/[Pp]ackages/* 209 | # except build/, which is used as an MSBuild target. 210 | !**/[Pp]ackages/build/ 211 | # Uncomment if necessary however generally it will be regenerated when needed 212 | #!**/[Pp]ackages/repositories.config 213 | # NuGet v3's project.json files produces more ignorable files 214 | *.nuget.props 215 | *.nuget.targets 216 | 217 | # Microsoft Azure Build Output 218 | csx/ 219 | *.build.csdef 220 | 221 | # Microsoft Azure Emulator 222 | ecf/ 223 | rcf/ 224 | 225 | # Windows Store app package directories and files 226 | AppPackages/ 227 | BundleArtifacts/ 228 | Package.StoreAssociation.xml 229 | _pkginfo.txt 230 | *.appx 231 | *.appxbundle 232 | *.appxupload 233 | 234 | # Visual Studio cache files 235 | # files ending in .cache can be ignored 236 | *.[Cc]ache 237 | # but keep track of directories ending in .cache 238 | !?*.[Cc]ache/ 239 | 240 | # Others 241 | ClientBin/ 242 | ~$* 243 | *~ 244 | *.dbmdl 245 | *.dbproj.schemaview 246 | *.jfm 247 | *.pfx 248 | *.publishsettings 249 | orleans.codegen.cs 250 | 251 | # Including strong name files can present a security risk 252 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 253 | #*.snk 254 | 255 | # Since there are multiple workflows, uncomment next line to ignore bower_components 256 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 257 | #bower_components/ 258 | 259 | # RIA/Silverlight projects 260 | Generated_Code/ 261 | 262 | # Backup & report files from converting an old project file 263 | # to a newer Visual Studio version. Backup files are not needed, 264 | # because we have git ;-) 265 | _UpgradeReport_Files/ 266 | Backup*/ 267 | UpgradeLog*.XML 268 | UpgradeLog*.htm 269 | ServiceFabricBackup/ 270 | *.rptproj.bak 271 | 272 | # SQL Server files 273 | *.mdf 274 | *.ldf 275 | *.ndf 276 | 277 | # Business Intelligence projects 278 | *.rdl.data 279 | *.bim.layout 280 | *.bim_*.settings 281 | *.rptproj.rsuser 282 | *- [Bb]ackup.rdl 283 | *- [Bb]ackup ([0-9]).rdl 284 | *- [Bb]ackup ([0-9][0-9]).rdl 285 | 286 | # Microsoft Fakes 287 | FakesAssemblies/ 288 | 289 | # GhostDoc plugin setting file 290 | *.GhostDoc.xml 291 | 292 | # Node.js Tools for Visual Studio 293 | .ntvs_analysis.dat 294 | node_modules/ 295 | 296 | # Visual Studio 6 build log 297 | *.plg 298 | 299 | # Visual Studio 6 workspace options file 300 | *.opt 301 | 302 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 303 | *.vbw 304 | 305 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 306 | *.vbp 307 | 308 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 309 | *.dsw 310 | *.dsp 311 | 312 | # Visual Studio 6 technical files 313 | *.ncb 314 | *.aps 315 | 316 | # Visual Studio LightSwitch build output 317 | **/*.HTMLClient/GeneratedArtifacts 318 | **/*.DesktopClient/GeneratedArtifacts 319 | **/*.DesktopClient/ModelManifest.xml 320 | **/*.Server/GeneratedArtifacts 321 | **/*.Server/ModelManifest.xml 322 | _Pvt_Extensions 323 | 324 | # Paket dependency manager 325 | .paket/paket.exe 326 | paket-files/ 327 | 328 | # FAKE - F# Make 329 | .fake/ 330 | 331 | # CodeRush personal settings 332 | .cr/personal 333 | 334 | # Python Tools for Visual Studio (PTVS) 335 | __pycache__/ 336 | *.pyc 337 | 338 | # Cake - Uncomment if you are using it 339 | # tools/** 340 | # !tools/packages.config 341 | 342 | # Tabs Studio 343 | *.tss 344 | 345 | # Telerik's JustMock configuration file 346 | *.jmconfig 347 | 348 | # BizTalk build output 349 | *.btp.cs 350 | *.btm.cs 351 | *.odx.cs 352 | *.xsd.cs 353 | 354 | # OpenCover UI analysis results 355 | OpenCover/ 356 | 357 | # Azure Stream Analytics local run output 358 | ASALocalRun/ 359 | 360 | # MSBuild Binary and Structured Log 361 | *.binlog 362 | 363 | # NVidia Nsight GPU debugger configuration file 364 | *.nvuser 365 | 366 | # MFractors (Xamarin productivity tool) working folder 367 | .mfractor/ 368 | 369 | # Local History for Visual Studio 370 | .localhistory/ 371 | 372 | # Visual Studio History (VSHistory) files 373 | .vshistory/ 374 | 375 | # BeatPulse healthcheck temp database 376 | healthchecksdb 377 | 378 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 379 | MigrationBackup/ 380 | 381 | # Ionide (cross platform F# VS Code tools) working folder 382 | .ionide/ 383 | 384 | # Fody - auto-generated XML schema 385 | FodyWeavers.xsd 386 | 387 | # VS Code files for those working on multiple tools 388 | .vscode/* 389 | !.vscode/settings.json 390 | !.vscode/tasks.json 391 | !.vscode/launch.json 392 | !.vscode/extensions.json 393 | *.code-workspace 394 | 395 | # Local History for Visual Studio Code 396 | .history/ 397 | 398 | # Windows Installer files from build outputs 399 | *.cab 400 | *.msi 401 | *.msix 402 | *.msm 403 | *.msp 404 | 405 | # JetBrains Rider 406 | *.sln.iml 407 | .idea/ 408 | 409 | ## 410 | ## Visual studio for Mac 411 | ## 412 | 413 | 414 | # globs 415 | Makefile.in 416 | *.userprefs 417 | *.usertasks 418 | config.make 419 | config.status 420 | aclocal.m4 421 | install-sh 422 | autom4te.cache/ 423 | *.tar.gz 424 | tarballs/ 425 | test-results/ 426 | 427 | # Mac bundle stuff 428 | *.dmg 429 | *.app 430 | 431 | # content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore 432 | # General 433 | .DS_Store 434 | .AppleDouble 435 | .LSOverride 436 | 437 | # Icon must end with two \r 438 | Icon 439 | 440 | 441 | # Thumbnails 442 | ._* 443 | 444 | # Files that might appear in the root of a volume 445 | .DocumentRevisions-V100 446 | .fseventsd 447 | .Spotlight-V100 448 | .TemporaryItems 449 | .Trashes 450 | .VolumeIcon.icns 451 | .com.apple.timemachine.donotpresent 452 | 453 | # Directories potentially created on remote AFP share 454 | .AppleDB 455 | .AppleDesktop 456 | Network Trash Folder 457 | Temporary Items 458 | .apdisk 459 | 460 | # content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore 461 | # Windows thumbnail cache files 462 | Thumbs.db 463 | ehthumbs.db 464 | ehthumbs_vista.db 465 | 466 | # Dump file 467 | *.stackdump 468 | 469 | # Folder config file 470 | [Dd]esktop.ini 471 | 472 | # Recycle Bin used on file shares 473 | $RECYCLE.BIN/ 474 | 475 | # Windows Installer files 476 | *.cab 477 | *.msi 478 | *.msix 479 | *.msm 480 | *.msp 481 | 482 | # Windows shortcuts 483 | *.lnk 484 | 485 | # Vim temporary swap files 486 | *.swp 487 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Pages/Welcome.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | 5 | 6 | 7 |
8 | @if (isLoading) 9 | { 10 |
11 | 12 |
Loading dashboard...
13 |
14 | } 15 | else 16 | { 17 | 18 | 19 |
20 | 21 | <Icon Type="api" Theme="IconThemeType.TwoTone" Style="margin-right: 12px;" /> 22 | MCP Links 23 | 24 | 25 | A powerful platform for managing and integrating multiple Model Context Protocol (MCP) servers. 26 | Streamline your AI tool interactions with centralized server management, real-time monitoring, and easy configuration. 27 | 28 | 29 | 30 | 34 | 35 | 36 | 40 | 41 | 42 |
43 | 44 | Active Servers: @stats.EnabledServers / @stats.TotalServers 45 | 46 |
47 |
48 |
49 | 50 | 51 |
52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 |
81 | 82 | 83 | Quick Actions 84 |
85 | 86 |
87 | 88 | MCP Store 89 | 90 | Browse and discover available MCP servers from the community store. 91 | 92 |
93 |
94 | 95 |
96 | 97 | Server Management 98 | 99 | Configure, enable, and monitor your MCP servers. Add new servers or modify existing ones. 100 | 101 |
102 |
103 | 104 |
105 | 106 | Client Apps 107 | 108 | Manage client applications and their configurations for different use cases. 109 | 110 |
111 |
112 | 113 |
114 | 115 | Tool Inspector 116 | 117 | Test and debug tools, resources, and prompts from your connected MCP servers. 118 | 119 |
120 |
121 |
122 | 123 | 124 |
125 | 126 | @if (recentActivities.Any()) 127 | { 128 | 129 | @foreach (var activity in recentActivities.Take(5)) 130 | { 131 | 132 | 133 | @activity 134 | 135 | } 136 | 137 | } 138 | else 139 | { 140 | 141 | 142 | 145 | 146 | 147 | } 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 |
158 | 159 | 160 | 163 | 164 | 165 | 168 | 169 | 170 |
171 |
172 |
173 | 174 | 175 | Key Features 176 |
177 | 178 |
179 | 180 | Multi-Protocol Support 181 | Support for stdio, SSE, and HTTP MCP server types with seamless integration. 182 |
183 |
184 | 185 |
186 | 187 | Real-time Monitoring 188 | Monitor server status, tool availability, and system health in real-time. 189 |
190 |
191 | 192 |
193 | 194 | Easy Integration 195 | Simple configuration and export options for popular MCP clients like Cursor and Claude. 196 |
197 |
198 |
199 | } 200 |
201 | -------------------------------------------------------------------------------- /src/Mcp.Links/Aggregation/McpClientsFactory.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Options; 4 | using ModelContextProtocol.Client; 5 | using System.Collections.Concurrent; 6 | 7 | namespace Mcp.Links.Aggregation; 8 | 9 | public sealed class McpClientsFactory 10 | { 11 | private readonly ILoggerFactory _loggerFactory; 12 | private readonly ILogger _logger; 13 | 14 | private readonly ConcurrentDictionary _clientWrappers = new(); 15 | private readonly object _initializationLock = new(); 16 | private readonly SemaphoreSlim InitializeSemaphore = new(1, 1); 17 | private volatile bool _isInitialized = false; 18 | 19 | private readonly IOptionsMonitor _mcpServerConfigOptions; 20 | 21 | public McpClientsFactory(IOptionsMonitor options, ILoggerFactory loggerFactory) 22 | { 23 | _mcpServerConfigOptions = options; 24 | 25 | _loggerFactory = loggerFactory; 26 | _logger = loggerFactory.CreateLogger(); 27 | } 28 | public async Task> GetOrCreateClientsAsync(CancellationToken cancellationToken = default) 29 | { 30 | var currentOptions = _mcpServerConfigOptions.CurrentValue; 31 | if (currentOptions.McpServers is null || !currentOptions.McpServers.Any()) 32 | { 33 | throw new InvalidOperationException("No MCP servers configured."); 34 | } 35 | 36 | if (_isInitialized) 37 | { 38 | // 如果已经初始化过客户端,直接返回现有的客户端列表 39 | return _clientWrappers.Values.ToList(); 40 | } 41 | 42 | // Use a more robust approach to prevent concurrent initialization 43 | await InitializeSemaphore.WaitAsync(cancellationToken); 44 | try 45 | { 46 | // Double-check after acquiring the semaphore 47 | if (_isInitialized) 48 | { 49 | return _clientWrappers.Values.ToList(); 50 | } 51 | 52 | // Initialize clients 53 | var clients = await McpClientInitializer.InitializeClientsAsync( 54 | currentOptions.McpServers, _loggerFactory, cancellationToken); 55 | 56 | // Add clients to the collection 57 | foreach (var client in clients) 58 | { 59 | _clientWrappers.TryAdd(client.Name, client); 60 | } 61 | 62 | _isInitialized = true; 63 | return _clientWrappers.Values.ToList(); 64 | } 65 | finally 66 | { 67 | InitializeSemaphore.Release(); 68 | } 69 | } 70 | 71 | /// 72 | /// Gets a specific MCP client by server ID. 73 | /// 74 | /// The server ID to get the client for. 75 | /// Cancellation token. 76 | /// The MCP client if found and initialized, null otherwise. 77 | public async Task GetMcpClientAsync(string serverId, CancellationToken cancellationToken = default) 78 | { 79 | if (string.IsNullOrWhiteSpace(serverId)) 80 | return null; 81 | 82 | var clientWrappers = await GetOrCreateClientsAsync(cancellationToken); 83 | if (_clientWrappers.TryGetValue(serverId, out var clientWrapper)) 84 | { 85 | return clientWrapper.McpClient; 86 | } 87 | 88 | return null; 89 | } 90 | 91 | /// 92 | /// Adds a new MCP client for the specified server. 93 | /// 94 | /// The server ID to add a client for. 95 | /// Cancellation token. 96 | /// A task representing the asynchronous operation. 97 | public async Task AddClientAsync(string serverId, CancellationToken cancellationToken = default) 98 | { 99 | if (string.IsNullOrWhiteSpace(serverId)) 100 | throw new ArgumentException("Server ID cannot be null or empty", nameof(serverId)); 101 | 102 | var currentOptions = _mcpServerConfigOptions.CurrentValue; 103 | if (!currentOptions.McpServers.TryGetValue(serverId, out var serverConfig)) 104 | { 105 | throw new ArgumentException($"Server '{serverId}' not found in configuration"); 106 | } 107 | 108 | // Check if server is enabled 109 | if (!serverConfig.Enabled.GetValueOrDefault(true)) 110 | { 111 | _logger.LogInformation("Skipping disabled server '{ServerId}'", serverId); 112 | return; 113 | } 114 | 115 | lock (_initializationLock) 116 | { 117 | // Check if client already exists 118 | if (_clientWrappers.ContainsKey(serverId)) 119 | { 120 | _logger.LogWarning("Client for server '{ServerId}' already exists", serverId); 121 | return; 122 | } 123 | } 124 | 125 | try 126 | { 127 | _logger.LogInformation("Adding MCP client for server '{ServerId}'", serverId); 128 | 129 | var clientWrapper = new McpClientWrapper(serverId, serverConfig, _loggerFactory); 130 | await clientWrapper.InitializeAsync(); 131 | 132 | lock (_initializationLock) 133 | { 134 | _clientWrappers.TryAdd(serverId, clientWrapper); 135 | } 136 | 137 | _logger.LogInformation("Successfully added MCP client for server '{ServerId}'", serverId); 138 | } 139 | catch (Exception ex) 140 | { 141 | _logger.LogError(ex, "Failed to add MCP client for server '{ServerId}'", serverId); 142 | throw; 143 | } 144 | } 145 | 146 | /// 147 | /// Updates an existing MCP client for the specified server. 148 | /// 149 | /// The server ID to update the client for. 150 | /// Cancellation token. 151 | /// A task representing the asynchronous operation. 152 | public async Task UpdateClientAsync(string serverId, CancellationToken cancellationToken = default) 153 | { 154 | if (string.IsNullOrWhiteSpace(serverId)) 155 | throw new ArgumentException("Server ID cannot be null or empty", nameof(serverId)); 156 | 157 | var currentOptions = _mcpServerConfigOptions.CurrentValue; 158 | if (!currentOptions.McpServers.TryGetValue(serverId, out var serverConfig)) 159 | { 160 | throw new ArgumentException($"Server '{serverId}' not found in configuration"); 161 | } 162 | 163 | _logger.LogInformation("Updating MCP client for server '{ServerId}'", serverId); 164 | 165 | // Remove the existing client first 166 | await RemoveClientAsync(serverId); 167 | 168 | // Add the new client if the server is enabled 169 | if (serverConfig.Enabled.GetValueOrDefault(true)) 170 | { 171 | await AddClientAsync(serverId, cancellationToken); 172 | } 173 | else 174 | { 175 | _logger.LogInformation("Server '{ServerId}' is disabled, client not recreated", serverId); 176 | } 177 | } 178 | 179 | /// 180 | /// Removes an MCP client for the specified server. 181 | /// 182 | /// The server ID to remove the client for. 183 | /// A task representing the asynchronous operation. 184 | public async Task RemoveClientAsync(string serverId) 185 | { 186 | if (string.IsNullOrWhiteSpace(serverId)) 187 | throw new ArgumentException("Server ID cannot be null or empty", nameof(serverId)); 188 | 189 | if (_clientWrappers.TryRemove(serverId, out var clientToRemove)) 190 | { 191 | _logger.LogInformation("Removing MCP client for server '{ServerId}'", serverId); 192 | DisposeClient(clientToRemove); 193 | _logger.LogInformation("Successfully removed MCP client for server '{ServerId}'", serverId); 194 | } 195 | else 196 | { 197 | _logger.LogWarning("No MCP client found for server '{ServerId}' to remove", serverId); 198 | } 199 | 200 | await Task.CompletedTask; 201 | } 202 | 203 | /// 204 | /// Reinitializes all MCP clients with the latest configuration. 205 | /// This method should be called when the MCP server configuration changes. 206 | /// 207 | /// Cancellation token. 208 | /// A task representing the asynchronous operation. 209 | public async Task ReinitializeClientsAsync(CancellationToken cancellationToken = default) 210 | { 211 | _logger.LogInformation("Reinitializing MCP clients due to configuration change..."); 212 | 213 | lock (_initializationLock) 214 | { 215 | // Dispose existing clients first 216 | DisposeExistingClients(); 217 | 218 | // Clear the collection and reset initialization flag 219 | _clientWrappers.Clear(); 220 | _isInitialized = false; 221 | } 222 | 223 | // Reinitialize with the new configuration 224 | await GetOrCreateClientsAsync(cancellationToken); 225 | 226 | _logger.LogInformation("MCP clients reinitialized successfully."); 227 | } 228 | 229 | /// 230 | /// Disposes all existing MCP clients to free up resources. 231 | /// 232 | private void DisposeExistingClients() 233 | { 234 | foreach (var kvp in _clientWrappers) 235 | { 236 | DisposeClient(kvp.Value); 237 | } 238 | } 239 | 240 | /// 241 | /// Disposes a single MCP client to free up resources. 242 | /// 243 | /// The client wrapper to dispose. 244 | private void DisposeClient(McpClientWrapper clientWrapper) 245 | { 246 | try 247 | { 248 | // Dispose the client if it implements IDisposable 249 | if (clientWrapper.McpClient is IDisposable disposableClient) 250 | { 251 | disposableClient.Dispose(); 252 | } 253 | 254 | // Try to dispose the wrapper itself if it implements IDisposable 255 | if (clientWrapper is IDisposable disposableWrapper) 256 | { 257 | disposableWrapper.Dispose(); 258 | } 259 | 260 | _logger.LogDebug("Disposed MCP client '{ClientName}'", clientWrapper.Name); 261 | } 262 | catch (Exception ex) 263 | { 264 | _logger.LogWarning(ex, "Error disposing MCP client '{ClientName}'", clientWrapper.Name); 265 | } 266 | } 267 | 268 | } 269 | -------------------------------------------------------------------------------- /src/Mcp.Links.Http/Services/McpClientAppService.cs: -------------------------------------------------------------------------------- 1 | using Mcp.Links.Configuration; 2 | using Microsoft.Extensions.Options; 3 | using System.Text.Json; 4 | using System.Text.Encodings.Web; 5 | 6 | namespace Mcp.Links.Http.Services; 7 | 8 | /// 9 | /// Service implementation for managing MCP client app configurations. 10 | /// 11 | public class McpClientAppService : IMcpClientAppService 12 | { 13 | private readonly ILogger _logger; 14 | private readonly IOptionsMonitor _clientConfigOptions; 15 | private readonly IHttpContextAccessor _httpContextAccessor; 16 | private readonly string _clientAppsFilePath; 17 | private readonly JsonSerializerOptions _jsonOptions; 18 | 19 | public McpClientAppService(ILogger logger, IOptionsMonitor clientConfigOptions, IHttpContextAccessor httpContextAccessor) 20 | { 21 | _logger = logger; 22 | _clientConfigOptions = clientConfigOptions; 23 | _httpContextAccessor = httpContextAccessor; 24 | 25 | // Use a client-apps.json file in the same directory as the main app 26 | _clientAppsFilePath = Path.Combine(AppContext.BaseDirectory, "client-apps.json"); 27 | 28 | _jsonOptions = new JsonSerializerOptions 29 | { 30 | WriteIndented = true, 31 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 32 | }; 33 | } 34 | 35 | public async Task GetAllClientAppsAsync() 36 | { 37 | try 38 | { 39 | // Always read from file-based approach for dynamic data 40 | if (!File.Exists(_clientAppsFilePath)) 41 | { 42 | _logger.LogInformation("Client apps file not found at {FilePath}, checking configuration fallback", _clientAppsFilePath); 43 | 44 | // Fallback to configuration options only if file doesn't exist 45 | var configOptions = _clientConfigOptions.CurrentValue; 46 | if (configOptions?.McpClients != null && configOptions.McpClients.Length > 0) 47 | { 48 | _logger.LogDebug("Loaded {Count} client apps from configuration as fallback", configOptions.McpClients.Length); 49 | // Save the configuration data to file for consistency 50 | await SaveClientAppsAsync(configOptions.McpClients); 51 | return configOptions.McpClients; 52 | } 53 | 54 | _logger.LogInformation("No client apps found in configuration, returning empty array"); 55 | return Array.Empty(); 56 | } 57 | 58 | var json = await File.ReadAllTextAsync(_clientAppsFilePath); 59 | if (string.IsNullOrWhiteSpace(json)) 60 | { 61 | return Array.Empty(); 62 | } 63 | 64 | var wrapper = JsonSerializer.Deserialize(json, _jsonOptions); 65 | var result = wrapper?.McpClients ?? Array.Empty(); 66 | 67 | _logger.LogDebug("Loaded {Count} client apps from file {FilePath}", result.Length, _clientAppsFilePath); 68 | return result; 69 | } 70 | catch (Exception ex) 71 | { 72 | _logger.LogError(ex, "Failed to load client apps"); 73 | throw new InvalidOperationException($"Failed to load client apps: {ex.Message}", ex); 74 | } 75 | } 76 | 77 | public async Task GetClientAppAsync(string appId) 78 | { 79 | var clientApps = await GetAllClientAppsAsync(); 80 | return clientApps.FirstOrDefault(app => app.AppId == appId); 81 | } 82 | 83 | public async Task CreateClientAppAsync(McpClientConfig clientApp) 84 | { 85 | if (!ValidateClientApp(clientApp)) 86 | { 87 | var errors = GetValidationErrors(clientApp); 88 | throw new ArgumentException($"Client app validation failed: {string.Join(", ", errors)}"); 89 | } 90 | 91 | if (await ClientAppExistsAsync(clientApp.AppId)) 92 | { 93 | throw new ArgumentException($"Client app with ID '{clientApp.AppId}' already exists"); 94 | } 95 | 96 | var clientApps = (await GetAllClientAppsAsync()).ToList(); 97 | clientApps.Add(clientApp); 98 | 99 | await SaveClientAppsAsync(clientApps.ToArray()); 100 | _logger.LogInformation("Created client app with ID: {AppId}", clientApp.AppId); 101 | } 102 | 103 | public async Task UpdateClientAppAsync(string appId, McpClientConfig clientApp) 104 | { 105 | if (!ValidateClientApp(clientApp)) 106 | { 107 | var errors = GetValidationErrors(clientApp); 108 | throw new ArgumentException($"Client app validation failed: {string.Join(", ", errors)}"); 109 | } 110 | 111 | var clientApps = (await GetAllClientAppsAsync()).ToList(); 112 | var existingIndex = clientApps.FindIndex(app => app.AppId == appId); 113 | 114 | if (existingIndex == -1) 115 | { 116 | throw new ArgumentException($"Client app with ID '{appId}' not found"); 117 | } 118 | 119 | // Ensure the app ID matches 120 | clientApp.AppId = appId; 121 | clientApps[existingIndex] = clientApp; 122 | 123 | await SaveClientAppsAsync(clientApps.ToArray()); 124 | _logger.LogInformation("Updated client app with ID: {AppId}", appId); 125 | } 126 | 127 | public async Task DeleteClientAppAsync(string appId) 128 | { 129 | var clientApps = (await GetAllClientAppsAsync()).ToList(); 130 | var existingIndex = clientApps.FindIndex(app => app.AppId == appId); 131 | 132 | if (existingIndex == -1) 133 | { 134 | throw new ArgumentException($"Client app with ID '{appId}' not found"); 135 | } 136 | 137 | clientApps.RemoveAt(existingIndex); 138 | await SaveClientAppsAsync(clientApps.ToArray()); 139 | _logger.LogInformation("Deleted client app with ID: {AppId}", appId); 140 | } 141 | 142 | public async Task ClientAppExistsAsync(string appId) 143 | { 144 | var clientApps = await GetAllClientAppsAsync(); 145 | return clientApps.Any(app => app.AppId == appId); 146 | } 147 | 148 | public bool ValidateClientApp(McpClientConfig clientApp) 149 | { 150 | return !GetValidationErrors(clientApp).Any(); 151 | } 152 | 153 | public IEnumerable GetValidationErrors(McpClientConfig clientApp) 154 | { 155 | var errors = new List(); 156 | 157 | if (string.IsNullOrWhiteSpace(clientApp.AppId)) 158 | errors.Add("App ID is required"); 159 | 160 | if (string.IsNullOrWhiteSpace(clientApp.AppKey)) 161 | errors.Add("App Key is required"); 162 | 163 | if (string.IsNullOrWhiteSpace(clientApp.Name)) 164 | errors.Add("Name is required"); 165 | 166 | if (clientApp.McpServerIds == null) 167 | errors.Add("MCP Server IDs cannot be null"); 168 | 169 | return errors; 170 | } 171 | 172 | public async Task GenerateClientConfigurationAsync(string appId, string serverId) 173 | { 174 | try 175 | { 176 | _logger.LogInformation("Generating client configuration for app '{AppId}' and server '{ServerId}'", appId, serverId); 177 | 178 | // Get the client app 179 | var clientApp = await GetClientAppAsync(appId); 180 | if (clientApp == null) 181 | { 182 | throw new ArgumentException($"Client app with ID '{appId}' not found"); 183 | } 184 | 185 | // Check if the server is associated with this client app 186 | if (clientApp.McpServerIds == null || !clientApp.McpServerIds.Contains(serverId)) 187 | { 188 | throw new ArgumentException($"Server '{serverId}' is not associated with client app '{appId}'"); 189 | } 190 | 191 | // Get the current request URL to build the proper MCP endpoint 192 | var request = _httpContextAccessor.HttpContext?.Request; 193 | var baseUrl = request != null 194 | ? $"{request.Scheme}://{request.Host}" 195 | : "http://localhost:5146"; // Fallback for non-HTTP contexts 196 | 197 | // Create the configuration entry for aggregated MCP server 198 | // All clients use the same "mcp-links" configuration with different App ID and App Key 199 | var configuration = new 200 | { 201 | mcpServers = new Dictionary 202 | { 203 | ["mcp-links"] = new 204 | { 205 | url = $"{baseUrl}/mcp", 206 | type = "http", 207 | headers = new Dictionary 208 | { 209 | ["X-AppId"] = appId, 210 | ["X-AppKey"] = clientApp.AppKey 211 | } 212 | } 213 | } 214 | }; 215 | 216 | var jsonOptions = new JsonSerializerOptions 217 | { 218 | WriteIndented = true, 219 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 220 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping 221 | }; 222 | 223 | var configJson = JsonSerializer.Serialize(configuration, jsonOptions); 224 | 225 | _logger.LogDebug("Generated client configuration for app '{AppId}' and server '{ServerId}'", appId, serverId); 226 | return configJson; 227 | } 228 | catch (Exception ex) 229 | { 230 | _logger.LogError(ex, "Failed to generate client configuration for app '{AppId}' and server '{ServerId}'", appId, serverId); 231 | throw; 232 | } 233 | } 234 | 235 | private async Task SaveClientAppsAsync(McpClientConfig[] clientApps) 236 | { 237 | try 238 | { 239 | var wrapper = new McpClientConfigOptions { McpClients = clientApps }; 240 | var json = JsonSerializer.Serialize(wrapper, _jsonOptions); 241 | 242 | // Ensure directory exists 243 | var directory = Path.GetDirectoryName(_clientAppsFilePath); 244 | if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) 245 | { 246 | Directory.CreateDirectory(directory); 247 | } 248 | 249 | await File.WriteAllTextAsync(_clientAppsFilePath, json); 250 | _logger.LogDebug("Saved client apps to {FilePath}", _clientAppsFilePath); 251 | } 252 | catch (Exception ex) 253 | { 254 | _logger.LogError(ex, "Failed to save client apps to {FilePath}", _clientAppsFilePath); 255 | throw new InvalidOperationException($"Failed to save client apps: {ex.Message}", ex); 256 | } 257 | } 258 | } 259 | --------------------------------------------------------------------------------