| 1 | using System.Text.Json; |
| 2 | using ModelContextProtocol.Protocol; |
| 3 | using Tool = ModelContextProtocol.Protocol.Tool; |
| 4 | |
| 5 | namespace AgentForge.Mcp; |
| 6 | |
| 7 | internal static class ForgeMcpCursorToolDescriptorSync |
| 8 | { |
| 9 | private static readonly JsonSerializerOptions WriteOptions = new() |
| 10 | { |
| 11 | WriteIndented = true, |
| 12 | }; |
| 13 | |
| 14 | internal static void TrySync(IReadOnlyList<Tool> tools, ForgeMcpSettings settings) |
| 15 | { |
| 16 | if (!settings.SyncCursorToolDescriptors) |
| 17 | return; |
| 18 | |
| 19 | var directory = ResolveDirectory(settings); |
| 20 | if (directory is null) |
| 21 | { |
| 22 | Console.Error.WriteLine( |
| 23 | "Forge MCP: sync_cursor_tool_descriptors is enabled but tool_descriptors_dir / FORGE_CURSOR_TOOLS_DIR is not set."); |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | try |
| 28 | { |
| 29 | Directory.CreateDirectory(directory); |
| 30 | foreach (var tool in tools) |
| 31 | { |
| 32 | var path = Path.Combine(directory, $"{ToFileStem(tool.Name)}.json"); |
| 33 | var payload = new CursorToolDescriptorFile |
| 34 | { |
| 35 | Name = tool.Name, |
| 36 | Description = tool.Description ?? string.Empty, |
| 37 | Arguments = tool.InputSchema, |
| 38 | }; |
| 39 | File.WriteAllText(path, JsonSerializer.Serialize(payload, WriteOptions)); |
| 40 | } |
| 41 | } |
| 42 | catch (Exception ex) |
| 43 | { |
| 44 | Console.Error.WriteLine($"Forge MCP: failed to sync Cursor tool descriptors to '{directory}': {ex.Message}"); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | internal static string ToFileStem(string toolName) => toolName.Replace('.', '_'); |
| 49 | |
| 50 | private static string? ResolveDirectory(ForgeMcpSettings settings) |
| 51 | { |
| 52 | var configured = FirstNonEmpty( |
| 53 | Environment.GetEnvironmentVariable("FORGE_CURSOR_TOOLS_DIR"), |
| 54 | settings.CursorToolDescriptorsDir); |
| 55 | return string.IsNullOrWhiteSpace(configured) ? null : Path.GetFullPath(configured.Trim()); |
| 56 | } |
| 57 | |
| 58 | private static string? FirstNonEmpty(params string?[] values) |
| 59 | { |
| 60 | foreach (var value in values) |
| 61 | { |
| 62 | if (!string.IsNullOrWhiteSpace(value)) |
| 63 | return value.Trim(); |
| 64 | } |
| 65 | |
| 66 | return null; |
| 67 | } |
| 68 | |
| 69 | private sealed class CursorToolDescriptorFile |
| 70 | { |
| 71 | public required string Name { get; init; } |
| 72 | |
| 73 | public required string Description { get; init; } |
| 74 | |
| 75 | public required JsonElement Arguments { get; init; } |
| 76 | } |
| 77 | } |
| 78 | |