|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Text.Json; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Azure.DataApiBuilder.Auth; |
| 10 | +using Azure.DataApiBuilder.Config.DatabasePrimitives; |
| 11 | +using Azure.DataApiBuilder.Config.ObjectModel; |
| 12 | +using Azure.DataApiBuilder.Core.Authorization; |
| 13 | +using Azure.DataApiBuilder.Core.Configurations; |
| 14 | +using Azure.DataApiBuilder.Core.Services; |
| 15 | +using Azure.DataApiBuilder.Core.Services.MetadataProviders; |
| 16 | +using Azure.DataApiBuilder.Mcp.BuiltInTools; |
| 17 | +using Azure.DataApiBuilder.Mcp.Model; |
| 18 | +using Microsoft.AspNetCore.Http; |
| 19 | +using Microsoft.Extensions.DependencyInjection; |
| 20 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 21 | +using ModelContextProtocol.Protocol; |
| 22 | +using Moq; |
| 23 | + |
| 24 | +namespace Azure.DataApiBuilder.Service.Tests.Configuration |
| 25 | +{ |
| 26 | + [TestClass] |
| 27 | + public class McpDmlToolViewSupportTests |
| 28 | + { |
| 29 | + [DataTestMethod] |
| 30 | + [DataRow("CreateRecord", "Table", "{\"entity\": \"Book\", \"data\": {\"id\": 1, \"title\": \"Test\"}}", DisplayName = "CreateRecord allows Table")] |
| 31 | + [DataRow("CreateRecord", "View", "{\"entity\": \"BookView\", \"data\": {\"id\": 1, \"title\": \"Test\"}}", DisplayName = "CreateRecord allows View")] |
| 32 | + [DataRow("ReadRecords", "Table", "{\"entity\": \"Book\"}", DisplayName = "ReadRecords allows Table")] |
| 33 | + [DataRow("ReadRecords", "View", "{\"entity\": \"BookView\"}", DisplayName = "ReadRecords allows View")] |
| 34 | + [DataRow("UpdateRecord", "Table", "{\"entity\": \"Book\", \"keys\": {\"id\": 1}, \"fields\": {\"title\": \"Updated\"}}", DisplayName = "UpdateRecord allows Table")] |
| 35 | + [DataRow("UpdateRecord", "View", "{\"entity\": \"BookView\", \"keys\": {\"id\": 1}, \"fields\": {\"title\": \"Updated\"}}", DisplayName = "UpdateRecord allows View")] |
| 36 | + [DataRow("DeleteRecord", "Table", "{\"entity\": \"Book\", \"keys\": {\"id\": 1}}", DisplayName = "DeleteRecord allows Table")] |
| 37 | + [DataRow("DeleteRecord", "View", "{\"entity\": \"BookView\", \"keys\": {\"id\": 1}}", DisplayName = "DeleteRecord allows View")] |
| 38 | + public async Task DmlTool_AllowsTablesAndViews(string toolType, string sourceType, string jsonArguments) |
| 39 | + { |
| 40 | + RuntimeConfig config = sourceType == "View" |
| 41 | + ? CreateRuntimeConfigWithSourceType("BookView", EntitySourceType.View, "dbo.vBooks") |
| 42 | + : CreateRuntimeConfigWithSourceType("Book", EntitySourceType.Table, "books"); |
| 43 | + |
| 44 | + IServiceProvider serviceProvider = CreateMcpToolServiceProvider(config); |
| 45 | + IMcpTool tool = CreateTool(toolType); |
| 46 | + JsonDocument arguments = JsonDocument.Parse(jsonArguments); |
| 47 | + |
| 48 | + CallToolResult result = await tool.ExecuteAsync(arguments, serviceProvider, CancellationToken.None); |
| 49 | + if (result.IsError == true) |
| 50 | + { |
| 51 | + JsonElement content = ParseResultContent(result); |
| 52 | + if (content.TryGetProperty("error", out JsonElement error) && |
| 53 | + error.TryGetProperty("type", out JsonElement errorType)) |
| 54 | + { |
| 55 | + Assert.AreNotEqual("InvalidEntity", errorType.GetString() ?? string.Empty, |
| 56 | + $"{sourceType} entities should not be blocked with InvalidEntity"); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private static RuntimeConfig CreateRuntimeConfigWithSourceType(string entityName, EntitySourceType sourceType, string sourceObject) |
| 62 | + { |
| 63 | + Dictionary<string, Entity> entities = new() |
| 64 | + { |
| 65 | + [entityName] = new Entity( |
| 66 | + Source: new EntitySource( |
| 67 | + Object: sourceObject, |
| 68 | + Type: sourceType, |
| 69 | + Parameters: null, |
| 70 | + KeyFields: new[] { "id" } |
| 71 | + ), |
| 72 | + GraphQL: new(entityName, entityName + "s"), |
| 73 | + Fields: null, |
| 74 | + Rest: new(Enabled: true), |
| 75 | + Permissions: new[] |
| 76 | + { |
| 77 | + new EntityPermission(Role: "anonymous", Actions: new[] |
| 78 | + { |
| 79 | + new EntityAction(Action: EntityActionOperation.Read, Fields: null, Policy: null), |
| 80 | + new EntityAction(Action: EntityActionOperation.Create, Fields: null, Policy: null), |
| 81 | + new EntityAction(Action: EntityActionOperation.Update, Fields: null, Policy: null), |
| 82 | + new EntityAction(Action: EntityActionOperation.Delete, Fields: null, Policy: null) |
| 83 | + }) |
| 84 | + }, |
| 85 | + Mappings: null, |
| 86 | + Relationships: null |
| 87 | + ) |
| 88 | + }; |
| 89 | + |
| 90 | + return new RuntimeConfig( |
| 91 | + Schema: "test-schema", |
| 92 | + DataSource: new DataSource(DatabaseType: DatabaseType.MSSQL, ConnectionString: "", Options: null), |
| 93 | + Runtime: new( |
| 94 | + Rest: new(), |
| 95 | + GraphQL: new(), |
| 96 | + Mcp: new( |
| 97 | + Enabled: true, |
| 98 | + Path: "/mcp", |
| 99 | + DmlTools: new( |
| 100 | + describeEntities: true, |
| 101 | + readRecords: true, |
| 102 | + createRecord: true, |
| 103 | + updateRecord: true, |
| 104 | + deleteRecord: true, |
| 105 | + executeEntity: true)), |
| 106 | + Host: new(Cors: null, Authentication: null, Mode: HostMode.Development)), |
| 107 | + Entities: new RuntimeEntities(entities)); |
| 108 | + } |
| 109 | + |
| 110 | + private static IServiceProvider CreateMcpToolServiceProvider(RuntimeConfig config) |
| 111 | + { |
| 112 | + ServiceCollection services = new(); |
| 113 | + |
| 114 | + RuntimeConfigProvider configProvider = TestHelper.GenerateInMemoryRuntimeConfigProvider(config); |
| 115 | + services.AddSingleton(configProvider); |
| 116 | + |
| 117 | + Mock<IAuthorizationResolver> mockAuthResolver = new(); |
| 118 | + mockAuthResolver.Setup(x => x.IsValidRoleContext(It.IsAny<HttpContext>())).Returns(true); |
| 119 | + services.AddSingleton(mockAuthResolver.Object); |
| 120 | + |
| 121 | + Mock<HttpContext> mockHttpContext = new(); |
| 122 | + Mock<HttpRequest> mockRequest = new(); |
| 123 | + mockRequest.Setup(x => x.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER]).Returns("anonymous"); |
| 124 | + mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object); |
| 125 | + |
| 126 | + Mock<IHttpContextAccessor> mockHttpContextAccessor = new(); |
| 127 | + mockHttpContextAccessor.Setup(x => x.HttpContext).Returns(mockHttpContext.Object); |
| 128 | + services.AddSingleton(mockHttpContextAccessor.Object); |
| 129 | + |
| 130 | + Mock<ISqlMetadataProvider> mockSqlMetadataProvider = new(); |
| 131 | + Dictionary<string, DatabaseObject> entityToDatabaseObject = new(); |
| 132 | + foreach (KeyValuePair<string, Entity> entry in config.Entities) |
| 133 | + { |
| 134 | + EntitySourceType mappedSourceType = entry.Value.Source.Type ?? EntitySourceType.Table; |
| 135 | + DatabaseObject dbObject = mappedSourceType == EntitySourceType.View |
| 136 | + ? new DatabaseView("dbo", entry.Value.Source.Object) { SourceType = EntitySourceType.View } |
| 137 | + : new DatabaseTable("dbo", entry.Value.Source.Object) { SourceType = EntitySourceType.Table }; |
| 138 | + |
| 139 | + entityToDatabaseObject[entry.Key] = dbObject; |
| 140 | + } |
| 141 | + |
| 142 | + mockSqlMetadataProvider.Setup(x => x.EntityToDatabaseObject).Returns(entityToDatabaseObject); |
| 143 | + mockSqlMetadataProvider.Setup(x => x.GetDatabaseType()).Returns(DatabaseType.MSSQL); |
| 144 | + |
| 145 | + Mock<IMetadataProviderFactory> mockMetadataProviderFactory = new(); |
| 146 | + mockMetadataProviderFactory.Setup(x => x.GetMetadataProvider(It.IsAny<string>())).Returns(mockSqlMetadataProvider.Object); |
| 147 | + services.AddSingleton(mockMetadataProviderFactory.Object); |
| 148 | + services.AddLogging(); |
| 149 | + |
| 150 | + return services.BuildServiceProvider(); |
| 151 | + } |
| 152 | + |
| 153 | + private static JsonElement ParseResultContent(CallToolResult result) |
| 154 | + { |
| 155 | + TextContentBlock firstContent = (TextContentBlock)result.Content[0]; |
| 156 | + return JsonDocument.Parse(firstContent.Text).RootElement; |
| 157 | + } |
| 158 | + |
| 159 | + private static IMcpTool CreateTool(string toolType) |
| 160 | + { |
| 161 | + return toolType switch |
| 162 | + { |
| 163 | + "ReadRecords" => new ReadRecordsTool(), |
| 164 | + "CreateRecord" => new CreateRecordTool(), |
| 165 | + "UpdateRecord" => new UpdateRecordTool(), |
| 166 | + "DeleteRecord" => new DeleteRecordTool(), |
| 167 | + _ => throw new ArgumentException($"Unknown tool type: {toolType}", nameof(toolType)) |
| 168 | + }; |
| 169 | + } |
| 170 | + } |
| 171 | +} |
0 commit comments