using System; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using OpenHarbor.MCP.Core; namespace CodexMcpServer.Tools; /// /// MCP tool for retrieving all sections of a specific CODEX document. /// Calls CODEX API GET /api/documents/{id}/sections endpoint. /// public class GetDocumentSectionsTool : IMcpTool { private readonly HttpClient _httpClient; private static readonly JsonDocument _schema = JsonDocument.Parse(""" { "type": "object", "properties": { "id": { "type": "string", "description": "Document ID to retrieve sections from" } }, "required": ["id"] } """); public GetDocumentSectionsTool(HttpClient httpClient) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); // Set base address if not already set if (_httpClient.BaseAddress == null) { _httpClient.BaseAddress = new Uri("http://localhost:5050"); } } /// public string Name => "get_document_sections"; /// public string Description => "Retrieve all sections of a specific CODEX document. Returns structured sections with titles and content."; /// public JsonDocument Schema => _schema; /// public async Task ExecuteAsync(JsonDocument? arguments) { try { // Validate arguments if (arguments == null) { return CreateErrorResponse("Arguments cannot be null. Expected {\"id\": \"document_id\"}"); } var root = arguments.RootElement; if (!root.TryGetProperty("id", out var idElement)) { return CreateErrorResponse("Missing required parameter 'id'"); } var id = idElement.GetString(); if (string.IsNullOrWhiteSpace(id)) { return CreateErrorResponse("Document ID cannot be empty"); } // Call CODEX API var response = await _httpClient.GetAsync($"/api/documents/{id}/sections"); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); return CreateErrorResponse( $"CODEX API returned error: {response.StatusCode}. {errorContent}" ); } // Parse and return response var responseContent = await response.Content.ReadAsStringAsync(); try { return JsonDocument.Parse(responseContent); } catch (JsonException ex) { return CreateErrorResponse($"Failed to parse CODEX API response: {ex.Message}"); } } catch (HttpRequestException ex) { return CreateErrorResponse($"HTTP request failed: {ex.Message}"); } catch (Exception ex) { return CreateErrorResponse($"Unexpected error: {ex.Message}"); } } private static JsonDocument CreateErrorResponse(string message) { var error = new { error = message }; return JsonDocument.Parse(JsonSerializer.Serialize(error)); } }