MutationToolTests.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. using ModelContextProtocol.Client;
  2. using RackPeek.Domain.Api;
  3. using RackPeek.Domain.Resources.Connections;
  4. using RackPeek.Mcp.Tools;
  5. namespace Tests.Mcp;
  6. /// <summary>
  7. /// The write half of the tool surface. Every assertion here is made against what
  8. /// actually lands in config.yaml — the file is the product, not the tool response.
  9. /// </summary>
  10. public class MutationToolTests {
  11. private const string _newServerYaml =
  12. """
  13. version: 4
  14. resources:
  15. - kind: Server
  16. name: new-server
  17. ram:
  18. size: 64
  19. ports:
  20. - type: rj45
  21. speed: 1
  22. count: 2
  23. """;
  24. // -- upsert_resources ----------------------------------------------------------------
  25. [Fact]
  26. public async Task Upserting_a_new_resource_persists_it_as_schema_conformant_yaml() {
  27. using var api = new McpFixture(TestData.Seed);
  28. await using McpClient client = await api.ConnectAsync();
  29. ImportYamlResponse response = await client.CallOkAsync<ImportYamlResponse>(
  30. "upsert_resources", new Dictionary<string, object?> { ["yaml"] = _newServerYaml });
  31. Assert.Equal(["new-server"], response.Added);
  32. Assert.Contains("new-server", api.StoredYaml);
  33. SchemaAssert.ConformsToSchema(api.StoredYaml);
  34. }
  35. [Fact]
  36. public async Task A_dry_run_reports_the_diff_but_writes_nothing() {
  37. using var api = new McpFixture(TestData.Seed);
  38. await using McpClient client = await api.ConnectAsync();
  39. var before = api.StoredYaml;
  40. ImportYamlResponse response = await client.CallOkAsync<ImportYamlResponse>(
  41. "upsert_resources",
  42. new Dictionary<string, object?> { ["yaml"] = _newServerYaml, ["dryRun"] = true });
  43. Assert.Equal(["new-server"], response.Added);
  44. Assert.Contains("new-server", Assert.Contains("new-server", response.NewYaml));
  45. Assert.Equal(before, api.StoredYaml);
  46. }
  47. [Fact]
  48. public async Task Merge_updates_fields_and_reports_old_and_new_yaml() {
  49. using var api = new McpFixture(TestData.Seed);
  50. await using McpClient client = await api.ConnectAsync();
  51. ImportYamlResponse response = await client.CallOkAsync<ImportYamlResponse>(
  52. "upsert_resources", new Dictionary<string, object?> {
  53. ["yaml"] =
  54. """
  55. version: 4
  56. resources:
  57. - kind: System
  58. name: host-os
  59. cores: 16
  60. """
  61. });
  62. Assert.Equal(["host-os"], response.Updated);
  63. Assert.Contains("cores: 8", response.OldYaml["host-os"]);
  64. Assert.Contains("cores: 16", response.NewYaml["host-os"]);
  65. Assert.Contains("cores: 16", api.StoredYaml);
  66. // Merge only adds and updates — everything not mentioned stays.
  67. Assert.Contains("env: prod", api.StoredYaml);
  68. Assert.Contains("ip: 10.0.0.5", api.StoredYaml);
  69. }
  70. [Fact]
  71. public async Task Replace_mode_swaps_the_resource_in_wholesale() {
  72. using var api = new McpFixture(TestData.Seed);
  73. await using McpClient client = await api.ConnectAsync();
  74. ImportYamlResponse response = await client.CallOkAsync<ImportYamlResponse>(
  75. "upsert_resources", new Dictionary<string, object?> {
  76. ["yaml"] =
  77. """
  78. version: 4
  79. resources:
  80. - kind: System
  81. name: host-os
  82. type: vm
  83. os: alpine
  84. """,
  85. ["mode"] = "Replace"
  86. });
  87. Assert.Equal(["host-os"], response.Replaced);
  88. Assert.Contains("os: alpine", api.StoredYaml);
  89. Assert.DoesNotContain("env: prod", api.StoredYaml); // replaced, so the old labels are gone
  90. // Replace swaps the named resource only; the rest of the file is untouched.
  91. Assert.Contains("grafana", api.StoredYaml);
  92. }
  93. [Theory]
  94. [InlineData("not: [valid", "Import failed")]
  95. [InlineData("version: 4", "resources")]
  96. [InlineData("", "Invalid input")]
  97. public async Task Broken_documents_are_errors_that_name_the_problem(string yaml, string expected) {
  98. using var api = new McpFixture(TestData.Seed);
  99. await using McpClient client = await api.ConnectAsync();
  100. var before = api.StoredYaml;
  101. var error = await client.CallErrorAsync(
  102. "upsert_resources", new Dictionary<string, object?> { ["yaml"] = yaml });
  103. Assert.Contains(expected, error);
  104. Assert.Equal(before, api.StoredYaml);
  105. }
  106. [Fact]
  107. public async Task The_first_mcp_write_after_a_restart_does_not_destroy_the_existing_inventory() {
  108. // Same guarantee the inventory API pins down: the server loads the config before
  109. // serving, so a fresh boot's first merge happens against the user's file rather
  110. // than an empty collection (which would persist and wipe everything else).
  111. using var api = new McpFixture(TestData.Seed);
  112. await using McpClient client = await api.ConnectAsync();
  113. await client.CallOkAsync<ImportYamlResponse>(
  114. "upsert_resources", new Dictionary<string, object?> { ["yaml"] = _newServerYaml });
  115. Assert.Contains("rack-server", api.StoredYaml);
  116. Assert.Contains("grafana", api.StoredYaml);
  117. Assert.Contains("new-server", api.StoredYaml);
  118. }
  119. // -- delete_resource -----------------------------------------------------------------
  120. [Fact]
  121. public async Task Deleting_hardware_detaches_dependants_and_unplugs_its_connections() {
  122. using var api = new McpFixture(TestData.Seed);
  123. await using McpClient client = await api.ConnectAsync();
  124. await client.CallTextAsync(
  125. "delete_resource", new Dictionary<string, object?> { ["name"] = "rack-server" });
  126. var stored = api.StoredYaml;
  127. Assert.DoesNotContain("rack-server", stored);
  128. SchemaAssert.ConformsToSchema(stored);
  129. ConnectionList connections = await client.CallOkAsync<ConnectionList>("list_connections");
  130. Assert.Equal(0, connections.Count);
  131. ResourceDetail hostOs = await client.CallOkAsync<ResourceDetail>(
  132. "get_resource", new Dictionary<string, object?> { ["name"] = "host-os" });
  133. Assert.DoesNotContain("rack-server", hostOs.Yaml);
  134. }
  135. [Fact]
  136. public async Task Deleting_something_that_does_not_exist_is_an_error() {
  137. using var api = new McpFixture(TestData.Seed);
  138. await using McpClient client = await api.ConnectAsync();
  139. var error = await client.CallErrorAsync(
  140. "delete_resource", new Dictionary<string, object?> { ["name"] = "ghost" });
  141. Assert.Contains("ghost", error);
  142. }
  143. // -- rename_resource -----------------------------------------------------------------
  144. [Fact]
  145. public async Task Renaming_rewrites_runs_on_links_and_connection_endpoints() {
  146. using var api = new McpFixture(TestData.Seed);
  147. await using McpClient client = await api.ConnectAsync();
  148. await client.CallTextAsync("rename_resource", new Dictionary<string, object?> {
  149. ["name"] = "rack-server",
  150. ["newName"] = "compute-01"
  151. });
  152. var stored = api.StoredYaml;
  153. Assert.DoesNotContain("rack-server", stored);
  154. SchemaAssert.ConformsToSchema(stored);
  155. ResourceDetail hostOs = await client.CallOkAsync<ResourceDetail>(
  156. "get_resource", new Dictionary<string, object?> { ["name"] = "host-os" });
  157. Assert.Contains("compute-01", hostOs.Yaml);
  158. ConnectionList connections = await client.CallOkAsync<ConnectionList>("list_connections");
  159. Assert.Equal("compute-01", Assert.Single(connections.Connections).A.Resource);
  160. }
  161. [Fact]
  162. public async Task Renaming_onto_a_taken_name_is_a_conflict() {
  163. using var api = new McpFixture(TestData.Seed);
  164. await using McpClient client = await api.ConnectAsync();
  165. var error = await client.CallErrorAsync("rename_resource", new Dictionary<string, object?> {
  166. ["name"] = "rack-server",
  167. ["newName"] = "rack-switch"
  168. });
  169. Assert.Contains("already exists", error);
  170. }
  171. // -- clone_resource ------------------------------------------------------------------
  172. [Fact]
  173. public async Task A_clone_copies_the_kind_specific_fields_but_never_the_discovery_id() {
  174. using var api = new McpFixture(TestData.Seed);
  175. await using McpClient client = await api.ConnectAsync();
  176. await client.CallTextAsync("clone_resource", new Dictionary<string, object?> {
  177. ["name"] = "rack-server",
  178. ["cloneName"] = "compute-02"
  179. });
  180. ResourceDetail clone = await client.CallOkAsync<ResourceDetail>(
  181. "get_resource", new Dictionary<string, object?> { ["name"] = "compute-02" });
  182. Assert.Contains("kind: Server", clone.Yaml);
  183. // The deep copy went through the concrete Server type: the ports survived.
  184. Assert.Contains("ports:", clone.Yaml);
  185. Assert.Contains("count: 4", clone.Yaml);
  186. // A discoveryId names one machine; a copy of its card is not that machine.
  187. Assert.DoesNotContain("discoveryId", clone.Yaml);
  188. SchemaAssert.ConformsToSchema(api.StoredYaml);
  189. }
  190. [Fact]
  191. public async Task Cloning_guards_both_names() {
  192. using var api = new McpFixture(TestData.Seed);
  193. await using McpClient client = await api.ConnectAsync();
  194. Assert.Contains("not found", await client.CallErrorAsync("clone_resource",
  195. new Dictionary<string, object?> { ["name"] = "ghost", ["cloneName"] = "copy" }));
  196. Assert.Contains("already exists", await client.CallErrorAsync("clone_resource",
  197. new Dictionary<string, object?> { ["name"] = "rack-server", ["cloneName"] = "rack-switch" }));
  198. }
  199. // -- edit_tags / edit_labels ---------------------------------------------------------
  200. [Fact]
  201. public async Task Tags_can_be_added_and_removed_in_one_call() {
  202. using var api = new McpFixture(TestData.Seed);
  203. await using McpClient client = await api.ConnectAsync();
  204. TagsResult result = await client.CallOkAsync<TagsResult>("edit_tags",
  205. new Dictionary<string, object?> {
  206. ["name"] = "rack-server",
  207. ["add"] = new[] { "rack-a", "critical" },
  208. ["remove"] = new[] { "prod" }
  209. });
  210. Assert.Equal(["rack-a", "critical"], result.Tags);
  211. Assert.Contains("rack-a", api.StoredYaml);
  212. Assert.DoesNotContain("- prod", api.StoredYaml);
  213. }
  214. [Fact]
  215. public async Task Labels_can_be_set_overwritten_and_removed() {
  216. using var api = new McpFixture(TestData.Seed);
  217. await using McpClient client = await api.ConnectAsync();
  218. LabelsResult result = await client.CallOkAsync<LabelsResult>("edit_labels",
  219. new Dictionary<string, object?> {
  220. ["name"] = "host-os",
  221. ["set"] = new Dictionary<string, string> { ["env"] = "staging", ["owner"] = "tim" },
  222. ["remove"] = new[] { "owner" }
  223. });
  224. Assert.Equal("staging", Assert.Contains("env", result.Labels));
  225. Assert.DoesNotContain("owner", result.Labels.Keys);
  226. Assert.Contains("env: staging", api.StoredYaml);
  227. }
  228. [Fact]
  229. public async Task Editing_tags_or_labels_needs_something_to_do() {
  230. using var api = new McpFixture(TestData.Seed);
  231. await using McpClient client = await api.ConnectAsync();
  232. Assert.Contains("at least one", await client.CallErrorAsync("edit_tags",
  233. new Dictionary<string, object?> { ["name"] = "rack-server" }));
  234. Assert.Contains("at least one", await client.CallErrorAsync("edit_labels",
  235. new Dictionary<string, object?> { ["name"] = "host-os" }));
  236. }
  237. // -- add_connection / remove_connection ------------------------------------------------
  238. private static Dictionary<string, object?> Connect(
  239. string a, int groupA, int indexA, string b, int groupB, int indexB) => new() {
  240. ["resourceA"] = a,
  241. ["portGroupA"] = groupA,
  242. ["portIndexA"] = indexA,
  243. ["resourceB"] = b,
  244. ["portGroupB"] = groupB,
  245. ["portIndexB"] = indexB
  246. };
  247. [Fact]
  248. public async Task Connecting_two_free_ports_is_persisted() {
  249. using var api = new McpFixture(TestData.Seed);
  250. await using McpClient client = await api.ConnectAsync();
  251. await client.CallTextAsync("add_connection",
  252. Connect("rack-server", 0, 1, "rack-switch", 0, 2));
  253. ConnectionList connections = await client.CallOkAsync<ConnectionList>("list_connections");
  254. Assert.Equal(2, connections.Count);
  255. SchemaAssert.ConformsToSchema(api.StoredYaml);
  256. }
  257. [Fact]
  258. public async Task Connecting_an_occupied_port_replaces_what_was_plugged_into_it() {
  259. using var api = new McpFixture(TestData.Seed);
  260. await using McpClient client = await api.ConnectAsync();
  261. // rack-server port 0/0 is already cabled to rack-switch 0/0 in the seed.
  262. await client.CallTextAsync("add_connection",
  263. Connect("rack-server", 0, 0, "rack-switch", 0, 5));
  264. ConnectionList connections = await client.CallOkAsync<ConnectionList>("list_connections");
  265. Connection connection = Assert.Single(connections.Connections);
  266. Assert.Equal(5, connection.B.PortIndex);
  267. }
  268. [Fact]
  269. public async Task Impossible_connections_are_named_errors() {
  270. using var api = new McpFixture(TestData.Seed);
  271. await using McpClient client = await api.ConnectAsync();
  272. Assert.Contains("itself", await client.CallErrorAsync("add_connection",
  273. Connect("rack-server", 0, 0, "rack-server", 0, 0)));
  274. Assert.Contains("no ports", await client.CallErrorAsync("add_connection",
  275. Connect("host-os", 0, 0, "rack-switch", 0, 1)));
  276. Assert.Contains("not found", await client.CallErrorAsync("add_connection",
  277. Connect("rack-server", 0, 99, "rack-switch", 0, 1)));
  278. }
  279. [Fact]
  280. public async Task Removing_a_connection_unplugs_the_port_and_removing_again_is_a_no_op() {
  281. using var api = new McpFixture(TestData.Seed);
  282. await using McpClient client = await api.ConnectAsync();
  283. var args = new Dictionary<string, object?> {
  284. ["resource"] = "rack-switch",
  285. ["portGroup"] = 0,
  286. ["portIndex"] = 0
  287. };
  288. await client.CallTextAsync("remove_connection", args);
  289. await client.CallTextAsync("remove_connection", args); // idempotent
  290. ConnectionList connections = await client.CallOkAsync<ConnectionList>("list_connections");
  291. Assert.Equal(0, connections.Count);
  292. Assert.DoesNotContain("portIndex", api.StoredYaml);
  293. }
  294. }