From b46f1e2e1b3df9895c2b3a9195f8d04f9997c180 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 12:19:10 +0100 Subject: [PATCH 1/7] Serve the API reference lookups from the docs API The CLI and other HTTP clients can now search, read and list API Explorer operations without speaking MCP. The gateway moves to the search project, and a shared ApiReferenceService holds the argument checks and grouping, so the MCP tools and the new /api-reference endpoints answer the same way. Co-Authored-By: Claude Opus 5.5 --- .../MappingsExtensions.cs | 57 +++++ .../SerializationContext.cs | 5 + .../ServicesExtension.cs | 1 + .../Gateways/DocumentGateway.cs | 1 + .../McpFeatureModule.cs | 2 +- .../Responses/McpResponses.cs | 62 +---- .../Tools/ApiTools.cs | 207 ++++------------ .../Tools/DocumentTools.cs | 2 +- .../ApiReference}/ApiGateway.cs | 2 +- .../ApiReference/ApiReferenceService.cs | 224 ++++++++++++++++++ .../ApiReference}/ApiRouteMatch.cs | 2 +- .../ApiReference}/IApiGateway.cs | 2 +- .../Elastic.Documentation.Search.csproj | 3 + .../ServicesExtension.cs | 12 + .../ApiToolsIntegrationTests.cs | 3 +- .../McpToolsIntegrationTestsBase.cs | 3 +- .../ApiReferenceEndpointTests.cs | 173 ++++++++++++++ tests/Mcp.Remote.Tests/ApiGatewayTests.cs | 2 +- tests/Mcp.Remote.Tests/ApiRouteMatchTests.cs | 2 +- tests/Mcp.Remote.Tests/ApiToolsTests.cs | 32 +-- 20 files changed, 559 insertions(+), 238 deletions(-) rename src/{api/Elastic.Documentation.Mcp.Remote/Gateways => services/search/Elastic.Documentation.Search/ApiReference}/ApiGateway.cs (99%) create mode 100644 src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs rename src/{api/Elastic.Documentation.Mcp.Remote/Gateways => services/search/Elastic.Documentation.Search/ApiReference}/ApiRouteMatch.cs (98%) rename src/{api/Elastic.Documentation.Mcp.Remote/Gateways => services/search/Elastic.Documentation.Search/ApiReference}/IApiGateway.cs (98%) create mode 100644 tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index 9d77f72296..06d690f611 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -7,6 +7,7 @@ using Elastic.Documentation.Api.AskAi; using Elastic.Documentation.Api.PageFeedback; using Elastic.Documentation.Search; +using Elastic.Documentation.Search.ApiReference; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -26,6 +27,7 @@ public static void MapElasticDocsApiEndpoints(this IEndpointRouteBuilder group) MapFullSearch(group); MapChanges(group); MapPageFeedback(group); + MapApiReference(group); } private static void MapAskAiEndpoint(IEndpointRouteBuilder group) @@ -185,6 +187,61 @@ Cancel ctx return Results.Ok(response); }); + // The same lookups as the search_api_operations, get_api_operation and list_api_operations MCP tools. + private static void MapApiReference(IEndpointRouteBuilder group) + { + var apiGroup = group.MapGroup("/api-reference"); + _ = apiGroup.MapGet( + "/", + async ( + [FromQuery(Name = "api")] string? api, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "group")] string? apiGroupName, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult(await apiReference.ListAsync(api, version, apiGroupName, ctx)) + ); + + _ = apiGroup.MapGet( + "/search", + async ( + [FromQuery(Name = "q")] string query, + [FromQuery(Name = "api")] string? api, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, + [FromQuery(Name = "page")] int? pageNumber, + [FromQuery(Name = "size")] int? pageSize, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult( + await apiReference.SearchAsync(query, api, version, includeDeprecated ?? false, pageNumber ?? 1, pageSize ?? 10, ctx) + ) + ); + + _ = apiGroup.MapGet( + "/operation", + async ( + [FromQuery(Name = "api")] string? api, + [FromQuery(Name = "operation_id")] string? operationId, + [FromQuery(Name = "endpoint")] string? endpoint, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "include_body")] bool? includeBody, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult(await apiReference.GetAsync(api, operationId, endpoint, version, includeBody ?? false, ctx)) + ); + } + + private static IResult ToResult(ApiReferenceReply reply) => reply switch + { + ApiOperationSearchResponse r => Results.Ok(r), + ApiOperationResponse r => Results.Ok(r), + ApiListResponse r => Results.Ok(r), + ApiOperationListResponse r => Results.Ok(r), + ApiReferenceRejection r when r.ErrorType.EndsWith("_not_found", StringComparison.Ordinal) => Results.NotFound(r), + ApiReferenceRejection r => Results.BadRequest(r) + }; + private static void MapPageFeedback(IEndpointRouteBuilder group) { _ = group.MapPut("/page-feedback/{feedbackId:guid}", async ( diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index 7bea35457a..dcff84e6d4 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -40,5 +40,10 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(FullSearchAggregations))] [JsonSerializable(typeof(ChangesResponse))] [JsonSerializable(typeof(ChangedPageDto))] +[JsonSerializable(typeof(Search.ApiReference.ApiOperationSearchResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiOperationResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiListResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiOperationListResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiReferenceRejection))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] public partial class ApiJsonContext : JsonSerializerContext; diff --git a/src/api/Elastic.Documentation.Api/ServicesExtension.cs b/src/api/Elastic.Documentation.Api/ServicesExtension.cs index 583e96b23b..f979096883 100644 --- a/src/api/Elastic.Documentation.Api/ServicesExtension.cs +++ b/src/api/Elastic.Documentation.Api/ServicesExtension.cs @@ -221,6 +221,7 @@ private static void AddSearchServices(IServiceCollection services, AppEnv appEnv // Use the shared search service for DI registration _ = services.AddSearchServices(); + _ = services.AddApiReferenceServices(); logger?.LogInformation("Full search service registered with hybrid RRF support"); } } diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/DocumentGateway.cs b/src/api/Elastic.Documentation.Mcp.Remote/Gateways/DocumentGateway.cs index 7bd178ad0c..fed87e4723 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/DocumentGateway.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Gateways/DocumentGateway.cs @@ -4,6 +4,7 @@ using Elastic.Clients.Elasticsearch; using Elastic.Documentation.Search; +using Elastic.Documentation.Search.ApiReference; using Elastic.Documentation.Search.Common; using Elastic.Documentation.Search.Contract; using Microsoft.Extensions.Logging; diff --git a/src/api/Elastic.Documentation.Mcp.Remote/McpFeatureModule.cs b/src/api/Elastic.Documentation.Mcp.Remote/McpFeatureModule.cs index 916c2c2f8a..f32fe9cb76 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/McpFeatureModule.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/McpFeatureModule.cs @@ -66,7 +66,7 @@ internal static class McpFeatureModules "Use {tool:list_api_operations} to browse the available APIs and their operations." ], ToolType: typeof(ApiTools), - RegisterServices: services => _ = services.AddScoped() + RegisterServices: services => _ = services.AddApiReferenceServices() ); public static readonly McpFeatureModule Coherence = new(Name: "Coherence", Capability: "analyze", WhenToUse: [ diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs b/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs index 32f75ab947..482c3d8da0 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information using System.Text.Json.Serialization; -using Elastic.Documentation.Mcp.Remote.Gateways; +using Elastic.Documentation.Search.ApiReference; namespace Elastic.Documentation.Mcp.Remote.Responses; @@ -13,10 +13,8 @@ public sealed record ErrorResponse(string Error, List? Details = null); public static class ResponseBody { /// The note a response carries when it leaves out a body the caller can still ask for. - public static string? Note(string? body, bool includeBody) => - !includeBody && body is { Length: > 0 } - ? "The body is omitted by default. Call this tool again with includeBody=true to read it." - : null; + public static string? Note(int bodyLength, bool includeBody) => + !includeBody && bodyLength > 0 ? "The body is omitted by default. Call this tool again with includeBody=true to read it." : null; } // SemanticSearch response @@ -174,60 +172,6 @@ public sealed record AiEnrichmentStatusDto public required bool HasUseCases { get; init; } } -// search_api_operations response -public sealed record ApiOperationSearchResponse -{ - public required string Query { get; init; } - public required long TotalHits { get; init; } - public required IReadOnlyList Results { get; init; } -} - -// get_api_operation response -public sealed record ApiOperationResponse -{ - public required ApiOperationSummary Operation { get; init; } - public required string[] Versions { get; init; } - public required IReadOnlyList Fields { get; init; } - public string? AiShortSummary { get; init; } - public string? Body { get; init; } - public int BodyLength { get; init; } - public string? BodyNote { get; init; } - public required IReadOnlyList OtherMatches { get; init; } -} - -// list_api_operations response without an API key -public sealed record ApiListResponse -{ - public required IReadOnlyList Apis { get; init; } -} - -// list_api_operations response for one API -public sealed record ApiOperationListResponse -{ - public required string Api { get; init; } - public string? Version { get; init; } - public required int TotalOperations { get; init; } - public required IReadOnlyList Groups { get; init; } - public string? Note { get; init; } -} - -public sealed record ApiOperationGroupDto -{ - public required string Name { get; init; } - public required int Count { get; init; } - public IReadOnlyList? Operations { get; init; } -} - -public sealed record ApiOperationListItemDto -{ - public required string Title { get; init; } - public required string Url { get; init; } - public required string Method { get; init; } - public required string Path { get; init; } - public required string OperationId { get; init; } - public bool Deprecated { get; init; } -} - [JsonSourceGenerationOptions(WriteIndented = false, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] [JsonSerializable(typeof(ErrorResponse))] [JsonSerializable(typeof(SemanticSearchResponse))] diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs b/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs index 95d9f43a63..0833d24ed8 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs @@ -3,10 +3,9 @@ // See the LICENSE file in the project root for more information using System.ComponentModel; -using System.Text.Json; using Elastic.Documentation.Assembler.Mcp; -using Elastic.Documentation.Mcp.Remote.Gateways; using Elastic.Documentation.Mcp.Remote.Responses; +using Elastic.Documentation.Search.ApiReference; using Microsoft.Extensions.Logging; using ModelContextProtocol.Server; @@ -14,17 +13,8 @@ namespace Elastic.Documentation.Mcp.Remote.Tools; /// MCP tools for the REST API reference that API Explorer publishes. [McpServerToolType] -public class ApiTools(IApiGateway apiGateway, ILogger logger) +public class ApiTools(ApiReferenceService apiReference, ILogger logger) { - // Above this many operations, listing an API without a group returns the group names only. - internal const int MaxListedOperations = 150; - private const string UngroupedName = "Other"; - - private static readonly ToolRejected VersionNeedsApi = new( - "invalid_arguments", - "version needs api: pass the API key the version belongs to." - ); - [McpServerTool(ReadOnly = true, Idempotent = true, Destructive = false, OpenWorld = false), McpToolName("search_api_operations"), Description("Searches the Elastic REST API reference for operations. " + "Use when the user asks which API call does something, names an endpoint such as 'GET /_cluster/health', " + "or names a request or response field such as 'retriever' or 'track_total_hits'. " @@ -41,25 +31,22 @@ public Task SearchApiOperations( [Description("Number of results per page (default: 10, max: 50)")] int pageSize = 10, CancellationToken cancellationToken = default ) => - McpToolRunner.RunAsync(logger, "search_api_operations", new Dictionary - { - ["query"] = query, - ["api"] = api, - ["version"] = version, - ["includeDeprecated"] = includeDeprecated, - ["pageNumber"] = pageNumber, - ["pageSize"] = pageSize - }, async () => - { - if (VersionWithoutApi(api, version)) - return VersionNeedsApi; - var scope = ToScope(api, version); - - var search = new ApiOperationSearch(query, scope, includeDeprecated, Math.Max(1, pageNumber), Math.Clamp(pageSize, 1, 50)); - var page = await apiGateway.SearchOperationsAsync(search, cancellationToken); - var response = new ApiOperationSearchResponse { Query = query, TotalHits = page.Total, Results = page.Hits }; - return ToolSucceeded.Serialize(response, McpJsonContext.Default.ApiOperationSearchResponse); - }); + McpToolRunner.RunAsync( + logger, + "search_api_operations", + new Dictionary + { + ["query"] = query, + ["api"] = api, + ["version"] = version, + ["includeDeprecated"] = includeDeprecated, + ["pageNumber"] = pageNumber, + ["pageSize"] = pageSize + }, + async () => ToToolReply( + await apiReference.SearchAsync(query, api, version, includeDeprecated, pageNumber, pageSize, cancellationToken) + ) + ); [McpServerTool(ReadOnly = true, Idempotent = true, Destructive = false, OpenWorld = false), McpToolName("get_api_operation"), Description("Retrieves one operation from the Elastic REST API reference. " + "Use when you know the endpoint or the operation id and need its parameters, request body and response fields. " @@ -77,29 +64,22 @@ public Task GetApiOperation( false, CancellationToken cancellationToken = default ) => - McpToolRunner.RunAsync(logger, "get_api_operation", new Dictionary - { - ["api"] = api, - ["operationId"] = operationId, - ["endpoint"] = endpoint, - ["version"] = version, - ["includeBody"] = includeBody - }, async () => - { - if (VersionWithoutApi(api, version)) - return VersionNeedsApi; - var scope = ToScope(api, version); - if (ToOperationKey(operationId, endpoint) is not { } key) - return new ToolRejected("invalid_arguments", "Pass exactly one of operationId or endpoint."); - - var detail = await apiGateway.GetOperationAsync(new ApiOperationLookup(scope, key), cancellationToken); - return detail is null - ? new ToolRejected( - "operation_not_found", - $"No API operation matches {operationId ?? endpoint}{(api is null ? "" : $" in {api}")}." - ) - : ToolSucceeded.Serialize(ToResponse(detail, includeBody), McpJsonContext.Default.ApiOperationResponse); - }); + McpToolRunner.RunAsync( + logger, + "get_api_operation", + new Dictionary + { + ["api"] = api, + ["operationId"] = operationId, + ["endpoint"] = endpoint, + ["version"] = version, + ["includeBody"] = includeBody + }, + async () => ToToolReply( + await apiReference.GetAsync(api, operationId, endpoint, version, includeBody, cancellationToken), + includeBody + ) + ); [McpServerTool(ReadOnly = true, Idempotent = true, Destructive = false, OpenWorld = false), McpToolName("list_api_operations"), Description("Lists the Elastic REST APIs, or the operations of one API. " + "Use when the user wants to browse what an API offers, or you need an API key for the other API tools. " @@ -112,106 +92,23 @@ public Task ListApiOperations( [Description("Only the operations of this group, e.g. 'ES|QL' or 'cluster'")] string? group = null, CancellationToken cancellationToken = default ) => - McpToolRunner.RunAsync(logger, "list_api_operations", new Dictionary - { - ["api"] = api, - ["version"] = version, - ["group"] = group - }, async () => - { - if (VersionWithoutApi(api, version)) - return VersionNeedsApi; - var scope = ToScope(api, version); - if (scope is null) - { - var apis = await apiGateway.ListApisAsync(cancellationToken); - return ToolSucceeded.Serialize(new ApiListResponse { Apis = apis }, McpJsonContext.Default.ApiListResponse); - } - - var operations = await apiGateway.ListOperationsAsync(scope, cancellationToken); - return operations.Count == 0 - ? new ToolRejected( - "api_not_found", - $"No operations found for API '{api}'{(version is null ? "" : $" version '{version}'")}." - ) - : GroupOperations(scope, operations, group); - }); - - internal static ToolReply GroupOperations(ApiScope scope, IReadOnlyList operations, string? group) - { - var groups = operations - .GroupBy(o => o.Group ?? UngroupedName, StringComparer.OrdinalIgnoreCase) - .OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase) - .ToList(); - if (group is not null) - { - groups = [.. groups.Where(g => string.Equals(g.Key, group.Trim(), StringComparison.OrdinalIgnoreCase))]; - if (groups.Count == 0) - return new ToolRejected( - "group_not_found", - $"API '{scope.Key}' has no group '{group}'. Call list_api_operations without group to see its groups." - ); - } - - var listOperations = group is not null || operations.Count <= MaxListedOperations; - var response = new ApiOperationListResponse - { - Api = scope.Key, - Version = scope.Version, - TotalOperations = groups.Sum(g => g.Count()), - Groups = [.. groups.Select(g => ToGroup(g, listOperations))], - Note = listOperations ? null : $"This API has {operations.Count} operations. Pass group to list the operations of one group." - }; - return ToolSucceeded.Serialize(response, McpJsonContext.Default.ApiOperationListResponse); - } - - private static ApiOperationGroupDto ToGroup(IGrouping group, bool listOperations) => - new() - { - Name = group.Key, - Count = group.Count(), - Operations = listOperations - ? [.. group.OrderBy(o => o.Path, StringComparer.Ordinal).ThenBy(o => o.Method, StringComparer.Ordinal).Select(ToListItem)] - : null - }; - - private static ApiOperationListItemDto ToListItem(ApiOperationSummary operation) => - new() - { - Title = operation.Title, - Url = operation.Url, - Method = operation.Method, - Path = operation.Path, - OperationId = operation.OperationId, - Deprecated = operation.Deprecated - }; - - private static ApiOperationResponse ToResponse(ApiOperationDetail detail, bool includeBody) => - new() - { - Operation = detail.Operation, - Versions = detail.Versions, - Fields = detail.Fields, - AiShortSummary = detail.AiShortSummary, - Body = includeBody ? detail.Body : null, - BodyLength = detail.Body?.Length ?? 0, - BodyNote = ResponseBody.Note(detail.Body, includeBody), - OtherMatches = detail.OtherMatches - }; - - private static bool VersionWithoutApi(string? api, string? version) => - string.IsNullOrWhiteSpace(api) && !string.IsNullOrWhiteSpace(version); - - private static ApiScope? ToScope(string? api, string? version) => - string.IsNullOrWhiteSpace(api) - ? null - : new ApiScope(api.Trim().ToLowerInvariant(), string.IsNullOrWhiteSpace(version) ? null : version.Trim().ToLowerInvariant()); - - private static ApiOperationKey? ToOperationKey(string? operationId, string? endpoint) + McpToolRunner.RunAsync( + logger, + "list_api_operations", + new Dictionary { ["api"] = api, ["version"] = version, ["group"] = group }, + async () => ToToolReply(await apiReference.ListAsync(api, version, group, cancellationToken)) + ); + + internal static ToolReply ToToolReply(ApiReferenceReply reply, bool includeBody = false) => reply switch { - var hasId = !string.IsNullOrWhiteSpace(operationId); - if (hasId == !string.IsNullOrWhiteSpace(endpoint)) - return null; - return hasId ? new ApiOperationIdKey(operationId!.Trim()) : new ApiEndpointKey(endpoint!.Trim()); - } + ApiOperationSearchResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiOperationSearchResponse), + ApiOperationResponse r => + ToolSucceeded.Serialize( + r with { BodyNote = ResponseBody.Note(r.BodyLength, includeBody) }, + McpJsonContext.Default.ApiOperationResponse + ), + ApiListResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiListResponse), + ApiOperationListResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiOperationListResponse), + ApiReferenceRejection r => new ToolRejected(r.ErrorType, r.Message) + }; } diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Tools/DocumentTools.cs b/src/api/Elastic.Documentation.Mcp.Remote/Tools/DocumentTools.cs index 56b10f5fde..596c482f64 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Tools/DocumentTools.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Tools/DocumentTools.cs @@ -70,7 +70,7 @@ public Task GetDocumentByUrl( : null, Body = includeBody ? result.Body : null, BodyLength = result.Body?.Length ?? 0, - BodyNote = ResponseBody.Note(result.Body, includeBody) + BodyNote = ResponseBody.Note(result.Body?.Length ?? 0, includeBody) }; return ToolSucceeded.Serialize(response, McpJsonContext.Default.DocumentResponse); }); diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs similarity index 99% rename from src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiGateway.cs rename to src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs index b9be653819..2432459f94 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiGateway.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs @@ -12,7 +12,7 @@ using Microsoft.Extensions.Logging; using EsSearchResponse = Elastic.Clients.Elasticsearch.SearchResponse; -namespace Elastic.Documentation.Mcp.Remote.Gateways; +namespace Elastic.Documentation.Search.ApiReference; /// Queries the api.* fields API Explorer pages carry in the docs search index. public class ApiGateway(ElasticsearchClientAccessor clientAccessor, ILogger logger) : IApiGateway diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs new file mode 100644 index 0000000000..b1eb326566 --- /dev/null +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -0,0 +1,224 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +namespace Elastic.Documentation.Search.ApiReference; + +/// What a call to answers: one response, or why the call was rejected. +public readonly union ApiReferenceReply( + ApiOperationSearchResponse, + ApiOperationResponse, + ApiListResponse, + ApiOperationListResponse, + ApiReferenceRejection +); + +/// A call the API reference cannot answer. ends in _not_found when nothing matched. +public sealed record ApiReferenceRejection(string ErrorType, string Message); + +/// Searches, reads and lists the operations of the REST API reference. The MCP tools and the docs API share it. +public class ApiReferenceService(IApiGateway apiGateway) +{ + /// Above this many operations, listing an API without a group returns the group names only. + public const int MaxListedOperations = 150; + public const int MaxPageSize = 50; + private const string UngroupedName = "Other"; + + private static readonly ApiReferenceRejection VersionNeedsApi = new( + "invalid_arguments", + "version needs api: pass the API key the version belongs to." + ); + + /// Finds operations by words, a typed route or a field path. + public async Task SearchAsync( + string query, + string? api, + string? version, + bool includeDeprecated, + int pageNumber, + int pageSize, + CancellationToken ct + ) + { + if (VersionWithoutApi(api, version)) + return VersionNeedsApi; + var search = new ApiOperationSearch( + query, + ToScope(api, version), + includeDeprecated, + Math.Max(1, pageNumber), + Math.Clamp(pageSize, 1, MaxPageSize) + ); + var page = await apiGateway.SearchOperationsAsync(search, ct); + return new ApiOperationSearchResponse { Query = query, TotalHits = page.Total, Results = page.Hits }; + } + + /// Reads one operation by exactly one of or . + public async Task GetAsync( + string? api, + string? operationId, + string? endpoint, + string? version, + bool includeBody, + CancellationToken ct + ) + { + if (VersionWithoutApi(api, version)) + return VersionNeedsApi; + if (ToOperationKey(operationId, endpoint) is not { } key) + return new ApiReferenceRejection("invalid_arguments", "Pass exactly one of operationId or endpoint."); + + var detail = await apiGateway.GetOperationAsync(new ApiOperationLookup(ToScope(api, version), key), ct); + if (detail is null) + return new ApiReferenceRejection( + "operation_not_found", + $"No API operation matches {operationId ?? endpoint}{(api is null ? "" : $" in {api}")}." + ); + return new ApiOperationResponse + { + Operation = detail.Operation, + Versions = detail.Versions, + Fields = detail.Fields, + AiShortSummary = detail.AiShortSummary, + Body = includeBody ? detail.Body : null, + BodyLength = detail.Body?.Length ?? 0, + OtherMatches = detail.OtherMatches + }; + } + + /// Lists every API without , or the operations of one API by group. + public async Task ListAsync(string? api, string? version, string? group, CancellationToken ct) + { + if (VersionWithoutApi(api, version)) + return VersionNeedsApi; + if (ToScope(api, version) is not { } scope) + return new ApiListResponse { Apis = await apiGateway.ListApisAsync(ct) }; + + var operations = await apiGateway.ListOperationsAsync(scope, ct); + return operations.Count == 0 + ? new ApiReferenceRejection( + "api_not_found", + $"No operations found for API '{api}'{(version is null ? "" : $" version '{version}'")}." + ) + : GroupOperations(scope, operations, group); + } + + internal static ApiReferenceReply GroupOperations(ApiScope scope, IReadOnlyList operations, string? group) + { + var groups = operations + .GroupBy(o => o.Group ?? UngroupedName, StringComparer.OrdinalIgnoreCase) + .OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase) + .ToList(); + if (group is not null) + { + groups = [.. groups.Where(g => string.Equals(g.Key, group.Trim(), StringComparison.OrdinalIgnoreCase))]; + if (groups.Count == 0) + return new ApiReferenceRejection( + "group_not_found", + $"API '{scope.Key}' has no group '{group}'. List the API without group to see its groups." + ); + } + + var listOperations = group is not null || operations.Count <= MaxListedOperations; + return new ApiOperationListResponse + { + Api = scope.Key, + Version = scope.Version, + TotalOperations = groups.Sum(g => g.Count()), + Groups = [.. groups.Select(g => ToGroup(g, listOperations))], + Note = listOperations ? null : $"This API has {operations.Count} operations. Pass group to list the operations of one group." + }; + } + + private static ApiOperationGroupDto ToGroup(IGrouping group, bool listOperations) => + new() + { + Name = group.Key, + Count = group.Count(), + Operations = listOperations + ? [.. group.OrderBy(o => o.Path, StringComparer.Ordinal).ThenBy(o => o.Method, StringComparer.Ordinal).Select(ToListItem)] + : null + }; + + private static ApiOperationListItemDto ToListItem(ApiOperationSummary operation) => + new() + { + Title = operation.Title, + Url = operation.Url, + Method = operation.Method, + Path = operation.Path, + OperationId = operation.OperationId, + Deprecated = operation.Deprecated + }; + + private static bool VersionWithoutApi(string? api, string? version) => + string.IsNullOrWhiteSpace(api) && !string.IsNullOrWhiteSpace(version); + + private static ApiScope? ToScope(string? api, string? version) => + string.IsNullOrWhiteSpace(api) + ? null + : new ApiScope(api.Trim().ToLowerInvariant(), string.IsNullOrWhiteSpace(version) ? null : version.Trim().ToLowerInvariant()); + + private static ApiOperationKey? ToOperationKey(string? operationId, string? endpoint) + { + var hasId = !string.IsNullOrWhiteSpace(operationId); + if (hasId == !string.IsNullOrWhiteSpace(endpoint)) + return null; + return hasId ? new ApiOperationIdKey(operationId!.Trim()) : new ApiEndpointKey(endpoint!.Trim()); + } +} + +/// Operations that match a search. +public sealed record ApiOperationSearchResponse +{ + public required string Query { get; init; } + public required long TotalHits { get; init; } + public required IReadOnlyList Results { get; init; } +} + +/// One operation with its routes, versions and documented fields. +public sealed record ApiOperationResponse +{ + public required ApiOperationSummary Operation { get; init; } + public required string[] Versions { get; init; } + public required IReadOnlyList Fields { get; init; } + public string? AiShortSummary { get; init; } + public string? Body { get; init; } + public int BodyLength { get; init; } + /// Set by callers that can tell the reader how to ask for an omitted body. + public string? BodyNote { get; init; } + public required IReadOnlyList OtherMatches { get; init; } +} + +/// Every API with its key and versions. +public sealed record ApiListResponse +{ + public required IReadOnlyList Apis { get; init; } +} + +/// The operations of one API, by group. +public sealed record ApiOperationListResponse +{ + public required string Api { get; init; } + public string? Version { get; init; } + public required int TotalOperations { get; init; } + public required IReadOnlyList Groups { get; init; } + public string? Note { get; init; } +} + +public sealed record ApiOperationGroupDto +{ + public required string Name { get; init; } + public required int Count { get; init; } + public IReadOnlyList? Operations { get; init; } +} + +public sealed record ApiOperationListItemDto +{ + public required string Title { get; init; } + public required string Url { get; init; } + public required string Method { get; init; } + public required string Path { get; init; } + public required string OperationId { get; init; } + public bool Deprecated { get; init; } +} diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiRouteMatch.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiRouteMatch.cs similarity index 98% rename from src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiRouteMatch.cs rename to src/services/search/Elastic.Documentation.Search/ApiReference/ApiRouteMatch.cs index 2782679e9d..274d5b5393 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiRouteMatch.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiRouteMatch.cs @@ -4,7 +4,7 @@ using Elastic.Documentation.Search.Contract; -namespace Elastic.Documentation.Mcp.Remote.Gateways; +namespace Elastic.Documentation.Search.ApiReference; /// A route as typed: its method, if any, and the path through . public sealed record TypedEndpoint(string? Method, string Path) diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/IApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs similarity index 98% rename from src/api/Elastic.Documentation.Mcp.Remote/Gateways/IApiGateway.cs rename to src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs index 47615ef841..3bd3bf9308 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Gateways/IApiGateway.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs @@ -2,7 +2,7 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -namespace Elastic.Documentation.Mcp.Remote.Gateways; +namespace Elastic.Documentation.Search.ApiReference; /// Reads API Explorer operations and landing pages from the docs search index. public interface IApiGateway diff --git a/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj b/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj index d538e632ba..6c9733821f 100644 --- a/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj +++ b/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj @@ -23,5 +23,8 @@ <_Parameter1>Elastic.Documentation.Api.Tests + + <_Parameter1>Mcp.Remote.Tests + diff --git a/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs b/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs index 63676e03b6..ce27d1d195 100644 --- a/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs +++ b/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information using Elastic.Documentation.Configuration.Products; +using Elastic.Documentation.Search.ApiReference; using Elastic.Documentation.Search.Common; using Elastic.Documentation.Search.Contract; using Microsoft.Extensions.DependencyInjection; @@ -66,6 +67,17 @@ public static IServiceCollection AddSearchServices(this IServiceCollection servi return services; } + /// + /// Registers over the api.* fields of the docs index. + /// Needs the that registers. + /// + public static IServiceCollection AddApiReferenceServices(this IServiceCollection services) + { + _ = services.AddScoped(); + _ = services.AddScoped(); + return services; + } + private static ILogger? GetLogger(IServiceCollection services) { using var serviceProvider = services.BuildServiceProvider(); diff --git a/tests-integration/Mcp.Remote.IntegrationTests/ApiToolsIntegrationTests.cs b/tests-integration/Mcp.Remote.IntegrationTests/ApiToolsIntegrationTests.cs index 9572d71b3f..9ca11ad1e6 100644 --- a/tests-integration/Mcp.Remote.IntegrationTests/ApiToolsIntegrationTests.cs +++ b/tests-integration/Mcp.Remote.IntegrationTests/ApiToolsIntegrationTests.cs @@ -7,6 +7,7 @@ using AwesomeAssertions; using Elastic.Documentation.Mcp.Remote.Responses; using Elastic.Documentation.Mcp.Remote.Tools; +using Elastic.Documentation.Search.ApiReference; namespace Mcp.Remote.IntegrationTests; @@ -74,7 +75,7 @@ public async Task ListApiOperations_Elasticsearch_ReturnsGroups() var json = await tools.ListApiOperations("elasticsearch", cancellationToken: Ct); var response = Reply(json, McpJsonContext.Default.ApiOperationListResponse); - response.TotalOperations.Should().BeGreaterThan(ApiTools.MaxListedOperations); + response.TotalOperations.Should().BeGreaterThan(ApiReferenceService.MaxListedOperations); response.Groups.Should().NotBeEmpty(); } } diff --git a/tests-integration/Mcp.Remote.IntegrationTests/McpToolsIntegrationTestsBase.cs b/tests-integration/Mcp.Remote.IntegrationTests/McpToolsIntegrationTestsBase.cs index a463b77a85..c1d988a2b6 100644 --- a/tests-integration/Mcp.Remote.IntegrationTests/McpToolsIntegrationTestsBase.cs +++ b/tests-integration/Mcp.Remote.IntegrationTests/McpToolsIntegrationTestsBase.cs @@ -8,6 +8,7 @@ using Elastic.Documentation.Mcp.Remote.Gateways; using Elastic.Documentation.Mcp.Remote.Tools; using Elastic.Documentation.Search; +using Elastic.Documentation.Search.ApiReference; using Elastic.Documentation.Search.Common; using Elastic.Documentation.Search.Contract; using Elastic.Documentation.ServiceDefaults; @@ -70,7 +71,7 @@ protected async Task LogIndexCount(ElasticsearchClientAccessor clientAccessor, C { var clientAccessor = CreateElasticsearchClientAccessor(); var apiGateway = new ApiGateway(clientAccessor, NullLogger.Instance); - return (new ApiTools(apiGateway, NullLogger.Instance), clientAccessor); + return (new ApiTools(new ApiReferenceService(apiGateway), NullLogger.Instance), clientAccessor); } /// diff --git a/tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs new file mode 100644 index 0000000000..99eb17084d --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs @@ -0,0 +1,173 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Net; +using System.Text.Json; +using AwesomeAssertions; +using Elastic.Documentation.Api.Tests.Fixtures; +using Elastic.Documentation.Search.ApiReference; +using FakeItEasy; + +namespace Elastic.Documentation.Api.Tests; + +// The tests share one host and swap the gateway it resolves, so they run one after another. +[NotInParallel(nameof(ApiReferenceEndpointTests))] +public class ApiReferenceEndpointTests +{ + private static readonly SwappableService Gateway = new(); + + private static readonly Lazy SharedFactory = new( + () => ApiWebApplicationFactory.WithMockedServices(replacements => replacements.Replace(_ => Gateway.Current)) + ); + + [After(Class)] + public static void DisposeSharedFactory() + { + if (SharedFactory.IsValueCreated) + SharedFactory.Value.Dispose(); + } + + private static readonly ApiOperationSummary Operation = new() + { + Api = "elasticsearch", + Title = "Get cluster health", + Url = "/docs/api/doc/elasticsearch/operation/operation-cluster-health", + Method = "GET", + Path = "/_cluster/health", + OperationId = "cluster-health", + Group = "cluster", + Endpoints = ["GET /_cluster/health"] + }; + + private static async Task<(HttpStatusCode Status, JsonElement Body)> Get(IApiGateway gateway, string pathAndQuery) + { + Gateway.Current = gateway; + using var client = SharedFactory.Value.CreateClient(); + using var response = await client.GetAsync( + $"/docs/_api/v1/api-reference{pathAndQuery}", + TestContext.Current!.Execution.CancellationToken + ); + var json = await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken); + return (response.StatusCode, JsonElement.Parse(json)); + } + + [Test] + public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() + { + ApiOperationSearch? received = null; + var gateway = A.Fake(); + _ = A + .CallTo(() => gateway.SearchOperationsAsync(A._, A._)) + .Invokes((ApiOperationSearch search, CancellationToken _) => received = search) + .Returns(new ApiOperationPage(1, [new ApiOperationHit(Operation, 1, [])])); + + var (status, body) = await Get(gateway, "/search?q=health&api=%20Elasticsearch%20&version=9&include_deprecated=true&size=500"); + + status.Should().Be(HttpStatusCode.OK); + received.Should().Be( + new ApiOperationSearch("health", new ApiScope("elasticsearch", "9"), true, 1, ApiReferenceService.MaxPageSize) + ); + body.GetProperty("totalHits").GetInt64().Should().Be(1); + body.GetProperty("results")[0].GetProperty("operation").GetProperty("operationId").GetString().Should().Be("cluster-health"); + } + + [Test] + public async Task Search_VersionWithoutApi_IsABadRequest() + { + var gateway = A.Fake(); + + var (status, body) = await Get(gateway, "/search?q=health&version=9"); + + status.Should().Be(HttpStatusCode.BadRequest); + body.GetProperty("errorType").GetString().Should().Be("invalid_arguments"); + A.CallTo(gateway).MustNotHaveHappened(); + } + + [Test] + public async Task Operation_ByOperationId_ReturnsTheBodyOnlyWhenAsked() + { + List received = []; + var gateway = A.Fake(); + _ = A + .CallTo(() => gateway.GetOperationAsync(A._, A._)) + .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) + .Returns(new ApiOperationDetail { Operation = Operation, Versions = ["9"], Fields = [], Body = "Full body" }); + + var (withoutBody, withoutJson) = await Get(gateway, "/operation?operation_id=cluster-health"); + var (withBody, withJson) = await Get(gateway, "/operation?operation_id=cluster-health&include_body=true"); + + withoutBody.Should().Be(HttpStatusCode.OK); + withoutJson.TryGetProperty("body", out var omitted).Should().BeTrue(); + omitted.ValueKind.Should().Be(JsonValueKind.Null); + withoutJson.GetProperty("bodyLength").GetInt32().Should().Be(9); + withBody.Should().Be(HttpStatusCode.OK); + withJson.GetProperty("body").GetString().Should().Be("Full body"); + ApiOperationKey key = new ApiOperationIdKey("cluster-health"); + received.Should().Equal(new ApiOperationLookup(null, key), new ApiOperationLookup(null, key)); + } + + [Test] + public async Task Operation_NoMatch_IsNotFound() + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); + + var (status, body) = await Get(gateway, "/operation?api=elasticsearch&endpoint=GET%20/nope"); + + status.Should().Be(HttpStatusCode.NotFound); + body.GetProperty("errorType").GetString().Should().Be("operation_not_found"); + body.GetProperty("message").GetString().Should().Be("No API operation matches GET /nope in elasticsearch."); + } + + [Test] + [Arguments("")] + [Arguments("?operation_id=cluster-health&endpoint=GET%20/_cluster/health")] + public async Task Operation_WithoutExactlyOneKey_IsABadRequest(string query) + { + var gateway = A.Fake(); + + var (status, _) = await Get(gateway, $"/operation{query}"); + + status.Should().Be(HttpStatusCode.BadRequest); + A.CallTo(gateway).MustNotHaveHappened(); + } + + [Test] + public async Task List_WithoutApi_ListsTheApis() + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.ListApisAsync(A._)).Returns([ + new ApiSummary { Key = "elasticsearch", Title = "Elasticsearch API", Url = "/docs/api/doc/elasticsearch", Versions = ["9"] } + ]); + + var (status, body) = await Get(gateway, "/"); + + status.Should().Be(HttpStatusCode.OK); + body.GetProperty("apis")[0].GetProperty("key").GetString().Should().Be("elasticsearch"); + } + + [Test] + public async Task List_WithApiAndGroup_ListsThatGroupsOperations() + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.ListOperationsAsync(new ApiScope("elasticsearch", null), A._)).Returns([Operation]); + + var (status, body) = await Get(gateway, "/?api=elasticsearch&group=Cluster"); + + status.Should().Be(HttpStatusCode.OK); + body.GetProperty("groups")[0].GetProperty("operations")[0].GetProperty("path").GetString().Should().Be("/_cluster/health"); + } + + [Test] + public async Task List_UnknownApi_IsNotFound() + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.ListOperationsAsync(A._, A._)).Returns([]); + + var (status, body) = await Get(gateway, "/?api=nope"); + + status.Should().Be(HttpStatusCode.NotFound); + body.GetProperty("errorType").GetString().Should().Be("api_not_found"); + } +} diff --git a/tests/Mcp.Remote.Tests/ApiGatewayTests.cs b/tests/Mcp.Remote.Tests/ApiGatewayTests.cs index dfa5abeb97..0fc4eb4f59 100644 --- a/tests/Mcp.Remote.Tests/ApiGatewayTests.cs +++ b/tests/Mcp.Remote.Tests/ApiGatewayTests.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information using AwesomeAssertions; -using Elastic.Documentation.Mcp.Remote.Gateways; using Elastic.Documentation.Search; +using Elastic.Documentation.Search.ApiReference; using Microsoft.Extensions.Logging.Abstractions; using Nullean.Snapshots; using Nullean.Snapshots.Json; diff --git a/tests/Mcp.Remote.Tests/ApiRouteMatchTests.cs b/tests/Mcp.Remote.Tests/ApiRouteMatchTests.cs index 1a7e95a9bf..746a810cb9 100644 --- a/tests/Mcp.Remote.Tests/ApiRouteMatchTests.cs +++ b/tests/Mcp.Remote.Tests/ApiRouteMatchTests.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information using AwesomeAssertions; -using Elastic.Documentation.Mcp.Remote.Gateways; +using Elastic.Documentation.Search.ApiReference; using Elastic.Documentation.Search.Contract; namespace Mcp.Remote.Tests; diff --git a/tests/Mcp.Remote.Tests/ApiToolsTests.cs b/tests/Mcp.Remote.Tests/ApiToolsTests.cs index 987adc214f..f41ac4ab53 100644 --- a/tests/Mcp.Remote.Tests/ApiToolsTests.cs +++ b/tests/Mcp.Remote.Tests/ApiToolsTests.cs @@ -4,10 +4,10 @@ using System.Text.Json; using AwesomeAssertions; -using Elastic.Documentation.Mcp.Remote.Gateways; using Elastic.Documentation.Mcp.Remote.Responses; using Elastic.Documentation.Mcp.Remote.Tools; using Elastic.Documentation.Search; +using Elastic.Documentation.Search.ApiReference; using FakeItEasy; using Microsoft.Extensions.Logging.Abstractions; using ModelContextProtocol; @@ -39,7 +39,7 @@ private static ApiOperationSummary Operation(string operationId, string? group, public async Task SearchApiOperations_VersionWithoutApi_RejectsTheCall() { var gateway = A.Fake(); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); var json = await tools.SearchApiOperations("health", version: "9", cancellationToken: Ct); @@ -55,7 +55,7 @@ public async Task SearchApiOperations_PassesTheNormalizedScopeToTheGateway() 0, [] )); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); _ = await tools.SearchApiOperations("health", api: " Elasticsearch ", version: "9", pageSize: 500, cancellationToken: Ct); @@ -73,7 +73,7 @@ public async Task SearchApiOperations_PassesTheNormalizedScopeToTheGateway() public async Task GetApiOperation_NeedsExactlyOneOfOperationIdAndEndpoint(string? operationId, string? endpoint) { var gateway = A.Fake(); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); var json = await tools.GetApiOperation("elasticsearch", operationId, endpoint, cancellationToken: Ct); @@ -86,7 +86,7 @@ public async Task GetApiOperation_NoMatch_ReportsWhatWasLookedUp() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); var json = await tools.GetApiOperation("elasticsearch", endpoint: "GET /_nope", cancellationToken: Ct); @@ -104,7 +104,7 @@ public async Task GetApiOperation_OmitsTheBodyByDefault() Fields = [], Body = "Get search hits that match the query." }); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); var json = await tools.GetApiOperation("elasticsearch", operationId: "search", cancellationToken: Ct); @@ -124,7 +124,7 @@ public async Task ListApiOperations_SmallApi_ListsOperationsByGroup() Operation("cluster-health", "Cluster", "/_cluster/health"), Operation("ping", null, "/") ]); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); var json = await tools.ListApiOperations("elasticsearch", cancellationToken: Ct); @@ -188,15 +188,13 @@ public async Task ListApiOperations_SmallApi_ListsOperationsByGroup() public void GroupOperations_LargeApiWithoutGroup_ReturnsGroupNamesOnly() { var operations = Enumerable - .Range(0, ApiTools.MaxListedOperations + 1) + .Range(0, ApiReferenceService.MaxListedOperations + 1) .Select(i => Operation($"op-{i}", i % 2 == 0 ? "Search" : "Cluster")) .ToList(); - var reply = ApiTools.GroupOperations(new ApiScope("elasticsearch", null), operations, group: null); + var reply = ApiReferenceService.GroupOperations(new ApiScope("elasticsearch", null), operations, group: null); - var json = reply is ToolSucceeded succeeded ? succeeded.Json : null; - json.Should().NotBeNull(); - var response = JsonSerializer.Deserialize(json, McpJsonContext.Default.ApiOperationListResponse); + var response = reply is ApiOperationListResponse list ? list : null; response.Should().NotBeNull(); response.Groups.Select(g => (g.Name, g.Count)).Should().Equal(("Cluster", 75), ("Search", 76)); response.Groups.Should().AllSatisfy(g => g.Operations.Should().BeNull()); @@ -206,9 +204,13 @@ public void GroupOperations_LargeApiWithoutGroup_ReturnsGroupNamesOnly() [Test] public void GroupOperations_UnknownGroup_RejectsTheCall() { - var reply = ApiTools.GroupOperations(new ApiScope("elasticsearch", null), [Operation("search", "Search")], group: "nope"); + var reply = ApiReferenceService.GroupOperations( + new ApiScope("elasticsearch", null), + [Operation("search", "Search")], + group: "nope" + ); - (reply is ToolRejected rejected ? rejected.ErrorType : null).Should().Be("group_not_found"); + (reply is ApiReferenceRejection rejected ? rejected.ErrorType : null).Should().Be("group_not_found"); } [Test] @@ -218,7 +220,7 @@ public async Task SearchApiOperations_BackendUnavailable_ThrowsMcpExceptionSoThe _ = A.CallTo(() => gateway.SearchOperationsAsync(A._, A._)).Throws( SearchUnavailableException.Transient("MaxTimeoutReached") ); - var tools = new ApiTools(gateway, NullLogger.Instance); + var tools = new ApiTools(new ApiReferenceService(gateway), NullLogger.Instance); var search = () => tools.SearchApiOperations("health", cancellationToken: Ct); From cbe5c12eafa37867658c3169121b120787ae6093 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 12:34:22 +0100 Subject: [PATCH 2/7] Document the API reference endpoints and name no MCP parameter The operation lookup told HTTP callers to pass operationId, which the endpoint does not take. The REST API page now lists the three lookups with their parameters, defaults, responses and status codes. Co-Authored-By: Claude Opus 5.5 --- docs/data/api.md | 15 +++++++++++++++ .../ApiReference/ApiReferenceService.cs | 2 +- tests/Mcp.Remote.Tests/ApiToolsTests.cs | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/data/api.md b/docs/data/api.md index 3d72859a75..af5d7cb53f 100644 --- a/docs/data/api.md +++ b/docs/data/api.md @@ -14,6 +14,21 @@ navigation_title: REST API | Navigation search | Search scoped to navigation structure and page titles | | Ask AI | Streaming endpoint for AI-powered question answering over documentation | | Changes feed | Content change feed for tracking documentation updates | +| API reference | Search, read, and list the REST API operations that API Explorer publishes | + +## API reference lookups + +The API reference endpoints answer the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md). They serve HTTP clients such as the Elastic CLI's `elastic docs api` commands. All three are `GET` requests under `/docs/_api/v1/api-reference`. Their responses are camelCase JSON, the same shapes the MCP tools return. + +`api` is an API key such as `elasticsearch` or `kibana`. `version` is `main` or a major such as `9`, and needs `api`. Without `version`, a lookup reads the API's current version. + +| Request | Query parameters | Returns | +|---------|------------------|---------| +| `/search` | `q` (required): words, a route such as `GET /_cluster/health`, or a field path. A trailing dot, as in `retriever.`, lists child fields.
`api`, `version`
`include_deprecated` (default `false`)
`page` (default `1`)
`size` (default `10`, at most `50`) | `query`, `totalHits`, and `results`. Each result has its `operation`, a `score`, and the `matchedFields`. | +| `/operation` | Exactly one of `operation_id` or `endpoint`, such as `GET /my-index/_search`.
`api`, `version`
`include_body` (default `false`) | The `operation`, its `versions`, every documented field in `fields`, `bodyLength`, `otherMatches`, and `body` only when `include_body=true` | +| `/` | `api`, `version`
`group`: one group of operations | Without `api`: `apis`, with each API's key, landing page, and versions.
With `api`: its `groups` of operations. An API with more than 150 operations lists only group names and counts, with a `note`, until you pass `group`. | + +A request the lookups can't answer returns `{ "errorType": "...", "message": "..." }`. The status is `404` when `errorType` ends in `_not_found`: `operation_not_found`, `api_not_found`, or `group_not_found`. Invalid arguments return `400` with `invalid_arguments`. ## Ask AI provider diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index b1eb326566..d8f5ff5e92 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -66,7 +66,7 @@ CancellationToken ct if (VersionWithoutApi(api, version)) return VersionNeedsApi; if (ToOperationKey(operationId, endpoint) is not { } key) - return new ApiReferenceRejection("invalid_arguments", "Pass exactly one of operationId or endpoint."); + return new ApiReferenceRejection("invalid_arguments", "Pass exactly one of an operation id or an endpoint."); var detail = await apiGateway.GetOperationAsync(new ApiOperationLookup(ToScope(api, version), key), ct); if (detail is null) diff --git a/tests/Mcp.Remote.Tests/ApiToolsTests.cs b/tests/Mcp.Remote.Tests/ApiToolsTests.cs index f41ac4ab53..bb534e9f18 100644 --- a/tests/Mcp.Remote.Tests/ApiToolsTests.cs +++ b/tests/Mcp.Remote.Tests/ApiToolsTests.cs @@ -77,7 +77,7 @@ public async Task GetApiOperation_NeedsExactlyOneOfOperationIdAndEndpoint(string var json = await tools.GetApiOperation("elasticsearch", operationId, endpoint, cancellationToken: Ct); - Error(json).Should().MatchInlineSnapshot("""Pass exactly one of operationId or endpoint."""); + Error(json).Should().MatchInlineSnapshot("""Pass exactly one of an operation id or an endpoint."""); A.CallTo(gateway).MustNotHaveHappened(); } From 181b79005d48e636f626cae8b8c67d5e2dfa18b4 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 13:48:45 +0100 Subject: [PATCH 3/7] Serve API operations as one resource collection The lookups move from /api-reference/{,search,operation} to /api-operations: the collection filters by q or by endpoint, one operation reads by id, and groups and apis are their own routes, so each route returns one shape. An endpoint lookup now lists every operation that serves the request, best first, instead of reading the top match. Co-Authored-By: Claude Opus 5.5 --- docs/data/api.md | 16 ++- .../MappingsExtensions.cs | 64 ++++++--- .../SerializationContext.cs | 1 + .../Responses/McpResponses.cs | 1 + .../Tools/ApiTools.cs | 1 + .../ApiReference/ApiReferenceService.cs | 34 +++++ ...Tests.cs => ApiOperationsEndpointTests.cs} | 121 +++++++++++++----- 7 files changed, 178 insertions(+), 60 deletions(-) rename tests/Elastic.Documentation.Api.Tests/{ApiReferenceEndpointTests.cs => ApiOperationsEndpointTests.cs} (58%) diff --git a/docs/data/api.md b/docs/data/api.md index af5d7cb53f..24801c1191 100644 --- a/docs/data/api.md +++ b/docs/data/api.md @@ -14,19 +14,23 @@ navigation_title: REST API | Navigation search | Search scoped to navigation structure and page titles | | Ask AI | Streaming endpoint for AI-powered question answering over documentation | | Changes feed | Content change feed for tracking documentation updates | -| API reference | Search, read, and list the REST API operations that API Explorer publishes | +| API operations | Search, read, and list the REST API operations that API Explorer publishes | -## API reference lookups +## API operations -The API reference endpoints answer the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md). They serve HTTP clients such as the Elastic CLI's `elastic docs api` commands. All three are `GET` requests under `/docs/_api/v1/api-reference`. Their responses are camelCase JSON, the same shapes the MCP tools return. +The API operations endpoints answer the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md). They serve HTTP clients such as the Elastic CLI's `elastic docs api` commands. All of them are `GET` requests under `/docs/_api/v1/api-operations`. Their responses are camelCase JSON, the same shapes the MCP tools return. `api` is an API key such as `elasticsearch` or `kibana`. `version` is `main` or a major such as `9`, and needs `api`. Without `version`, a lookup reads the API's current version. | Request | Query parameters | Returns | |---------|------------------|---------| -| `/search` | `q` (required): words, a route such as `GET /_cluster/health`, or a field path. A trailing dot, as in `retriever.`, lists child fields.
`api`, `version`
`include_deprecated` (default `false`)
`page` (default `1`)
`size` (default `10`, at most `50`) | `query`, `totalHits`, and `results`. Each result has its `operation`, a `score`, and the `matchedFields`. | -| `/operation` | Exactly one of `operation_id` or `endpoint`, such as `GET /my-index/_search`.
`api`, `version`
`include_body` (default `false`) | The `operation`, its `versions`, every documented field in `fields`, `bodyLength`, `otherMatches`, and `body` only when `include_body=true` | -| `/` | `api`, `version`
`group`: one group of operations | Without `api`: `apis`, with each API's key, landing page, and versions.
With `api`: its `groups` of operations. An API with more than 150 operations lists only group names and counts, with a `note`, until you pass `group`. | +| `/api-operations?q=` | `q`: words, a route such as `GET /_cluster/health`, or a field path. A trailing dot, as in `retriever.`, lists child fields.
`api`, `version`
`include_deprecated` (default `false`)
`page` (default `1`)
`size` (default `10`, at most `50`) | `query`, `totalHits`, and `results`. Each result has its `operation`, a `score`, and the `matchedFields`. | +| `/api-operations?endpoint=` | `endpoint`: a request such as `GET /my-index/_search`, with or without the method.
`api`, `version` | `endpoint` and `results`: the operations that serve the request, best match first. No match is an empty list. | +| `/api-operations/{operationId}` | `api`, `version`
`include_body` (default `false`) | The `operation`, its `versions`, every documented field in `fields`, `bodyLength`, `otherMatches` (the same id in other APIs), and `body` only when `include_body=true` | +| `/api-operations/groups` | `api` (required), `version`
`group`: one group of operations | The API's `groups` of operations. An API with more than 150 operations lists only group names and counts, with a `note`, until you pass `group`. | +| `/api-operations/apis` | None | `apis`, with each API's key, landing page, and versions | + +`/api-operations` needs exactly one of `q` or `endpoint`. The literal routes `groups` and `apis` take precedence over `{operationId}`. A request the lookups can't answer returns `{ "errorType": "...", "message": "..." }`. The status is `404` when `errorType` ends in `_not_found`: `operation_not_found`, `api_not_found`, or `group_not_found`. Invalid arguments return `400` with `invalid_arguments`. diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index 06d690f611..b1f6fcfbf9 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -27,7 +27,7 @@ public static void MapElasticDocsApiEndpoints(this IEndpointRouteBuilder group) MapFullSearch(group); MapChanges(group); MapPageFeedback(group); - MapApiReference(group); + MapApiOperations(group); } private static void MapAskAiEndpoint(IEndpointRouteBuilder group) @@ -188,53 +188,77 @@ Cancel ctx }); // The same lookups as the search_api_operations, get_api_operation and list_api_operations MCP tools. - private static void MapApiReference(IEndpointRouteBuilder group) + // The literal routes take precedence over {operationId}, so they reserve those ids. + private static void MapApiOperations(IEndpointRouteBuilder group) { - var apiGroup = group.MapGroup("/api-reference"); - _ = apiGroup.MapGet( + var operations = group.MapGroup("/api-operations"); + + // One collection, filtered by words (q) or by the request an operation serves (endpoint). + _ = operations.MapGet( "/", async ( + [FromQuery(Name = "q")] string? query, + [FromQuery(Name = "endpoint")] string? endpoint, [FromQuery(Name = "api")] string? api, [FromQuery(Name = "version")] string? version, - [FromQuery(Name = "group")] string? apiGroupName, + [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, + [FromQuery(Name = "page")] int? pageNumber, + [FromQuery(Name = "size")] int? pageSize, ApiReferenceService apiReference, Cancel ctx - ) => ToResult(await apiReference.ListAsync(api, version, apiGroupName, ctx)) + ) => + (string.IsNullOrWhiteSpace(query), string.IsNullOrWhiteSpace(endpoint)) switch + { + (false, true) => + ToResult( + await apiReference.SearchAsync( + query!, + api, + version, + includeDeprecated ?? false, + pageNumber ?? 1, + pageSize ?? 10, + ctx + ) + ), + (true, false) => ToResult(await apiReference.ResolveAsync(endpoint!, api, version, ctx)), + _ => Results.BadRequest(new ApiReferenceRejection("invalid_arguments", "Pass exactly one of q or endpoint.")) + } ); - _ = apiGroup.MapGet( - "/search", + _ = operations.MapGet( + "/apis", + async (ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.ListAsync(null, null, null, ctx)) + ); + + _ = operations.MapGet( + "/groups", async ( - [FromQuery(Name = "q")] string query, [FromQuery(Name = "api")] string? api, [FromQuery(Name = "version")] string? version, - [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, - [FromQuery(Name = "page")] int? pageNumber, - [FromQuery(Name = "size")] int? pageSize, + [FromQuery(Name = "group")] string? apiGroupName, ApiReferenceService apiReference, Cancel ctx - ) => ToResult( - await apiReference.SearchAsync(query, api, version, includeDeprecated ?? false, pageNumber ?? 1, pageSize ?? 10, ctx) - ) + ) => ToResult(await apiReference.ListGroupsAsync(api, version, apiGroupName, ctx)) ); - _ = apiGroup.MapGet( - "/operation", + _ = operations.MapGet( + "/{operationId}", async ( + string operationId, [FromQuery(Name = "api")] string? api, - [FromQuery(Name = "operation_id")] string? operationId, - [FromQuery(Name = "endpoint")] string? endpoint, [FromQuery(Name = "version")] string? version, [FromQuery(Name = "include_body")] bool? includeBody, ApiReferenceService apiReference, Cancel ctx - ) => ToResult(await apiReference.GetAsync(api, operationId, endpoint, version, includeBody ?? false, ctx)) + ) => ToResult(await apiReference.GetAsync(api, operationId, null, version, includeBody ?? false, ctx)) ); } private static IResult ToResult(ApiReferenceReply reply) => reply switch { ApiOperationSearchResponse r => Results.Ok(r), + ApiEndpointMatchResponse r => Results.Ok(r), ApiOperationResponse r => Results.Ok(r), ApiListResponse r => Results.Ok(r), ApiOperationListResponse r => Results.Ok(r), diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index dcff84e6d4..f11fb46d2e 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -43,6 +43,7 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(Search.ApiReference.ApiOperationSearchResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiOperationResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiListResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiEndpointMatchResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiOperationListResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiReferenceRejection))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs b/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs index 482c3d8da0..ef38f57f52 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs @@ -192,6 +192,7 @@ public sealed record AiEnrichmentStatusDto [JsonSerializable(typeof(ApiOperationSearchResponse))] [JsonSerializable(typeof(ApiOperationResponse))] [JsonSerializable(typeof(ApiListResponse))] +[JsonSerializable(typeof(ApiEndpointMatchResponse))] [JsonSerializable(typeof(ApiOperationListResponse))] [JsonSerializable(typeof(ApiOperationGroupDto))] [JsonSerializable(typeof(ApiOperationListItemDto))] diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs b/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs index 0833d24ed8..3c58286e29 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs @@ -108,6 +108,7 @@ public Task ListApiOperations( McpJsonContext.Default.ApiOperationResponse ), ApiListResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiListResponse), + ApiEndpointMatchResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiEndpointMatchResponse), ApiOperationListResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiOperationListResponse), ApiReferenceRejection r => new ToolRejected(r.ErrorType, r.Message) }; diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index d8f5ff5e92..71f49f3192 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -7,6 +7,7 @@ namespace Elastic.Documentation.Search.ApiReference; /// What a call to answers: one response, or why the call was rejected. public readonly union ApiReferenceReply( ApiOperationSearchResponse, + ApiEndpointMatchResponse, ApiOperationResponse, ApiListResponse, ApiOperationListResponse, @@ -86,6 +87,32 @@ CancellationToken ct }; } + /// + /// Finds the operations that serve a request such as GET /my-index/_search, best match first. + /// No match is an empty result, not a rejection: this filters the operations rather than reading one. + /// + public async Task ResolveAsync(string endpoint, string? api, string? version, CancellationToken ct) + { + if (VersionWithoutApi(api, version)) + return VersionNeedsApi; + if (string.IsNullOrWhiteSpace(endpoint)) + return new ApiReferenceRejection("invalid_arguments", "Pass an endpoint, such as 'GET /_cluster/health'."); + + var lookup = new ApiOperationLookup(ToScope(api, version), new ApiEndpointKey(endpoint.Trim())); + var detail = await apiGateway.GetOperationAsync(lookup, ct); + return new ApiEndpointMatchResponse + { + Endpoint = endpoint.Trim(), + Results = detail is null ? [] : [detail.Operation, .. detail.OtherMatches] + }; + } + + /// Lists the operations of one API by group; is required. + public Task ListGroupsAsync(string? api, string? version, string? group, CancellationToken ct) => + string.IsNullOrWhiteSpace(api) + ? Task.FromResult(new ApiReferenceRejection("invalid_arguments", "Pass api, such as 'elasticsearch'.")) + : ListAsync(api, version, group, ct); + /// Lists every API without , or the operations of one API by group. public async Task ListAsync(string? api, string? version, string? group, CancellationToken ct) { @@ -176,6 +203,13 @@ public sealed record ApiOperationSearchResponse public required IReadOnlyList Results { get; init; } } +/// The operations that serve one request, best match first. +public sealed record ApiEndpointMatchResponse +{ + public required string Endpoint { get; init; } + public required IReadOnlyList Results { get; init; } +} + /// One operation with its routes, versions and documented fields. public sealed record ApiOperationResponse { diff --git a/tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs similarity index 58% rename from tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs rename to tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs index 99eb17084d..27686b72cb 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiReferenceEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs @@ -12,8 +12,8 @@ namespace Elastic.Documentation.Api.Tests; // The tests share one host and swap the gateway it resolves, so they run one after another. -[NotInParallel(nameof(ApiReferenceEndpointTests))] -public class ApiReferenceEndpointTests +[NotInParallel(nameof(ApiOperationsEndpointTests))] +public class ApiOperationsEndpointTests { private static readonly SwappableService Gateway = new(); @@ -45,13 +45,16 @@ public static void DisposeSharedFactory() Gateway.Current = gateway; using var client = SharedFactory.Value.CreateClient(); using var response = await client.GetAsync( - $"/docs/_api/v1/api-reference{pathAndQuery}", + $"/docs/_api/v1/api-operations{pathAndQuery}", TestContext.Current!.Execution.CancellationToken ); var json = await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken); return (response.StatusCode, JsonElement.Parse(json)); } + private static ApiOperationDetail Detail(string? body = null, params ApiOperationSummary[] otherMatches) => + new() { Operation = Operation, Versions = ["9"], Fields = [], Body = body, OtherMatches = otherMatches }; + [Test] public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() { @@ -62,7 +65,7 @@ public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() .Invokes((ApiOperationSearch search, CancellationToken _) => received = search) .Returns(new ApiOperationPage(1, [new ApiOperationHit(Operation, 1, [])])); - var (status, body) = await Get(gateway, "/search?q=health&api=%20Elasticsearch%20&version=9&include_deprecated=true&size=500"); + var (status, body) = await Get(gateway, "?q=health&api=%20Elasticsearch%20&version=9&include_deprecated=true&size=500"); status.Should().Be(HttpStatusCode.OK); received.Should().Be( @@ -77,7 +80,7 @@ public async Task Search_VersionWithoutApi_IsABadRequest() { var gateway = A.Fake(); - var (status, body) = await Get(gateway, "/search?q=health&version=9"); + var (status, body) = await Get(gateway, "?q=health&version=9"); status.Should().Be(HttpStatusCode.BadRequest); body.GetProperty("errorType").GetString().Should().Be("invalid_arguments"); @@ -85,87 +88,137 @@ public async Task Search_VersionWithoutApi_IsABadRequest() } [Test] - public async Task Operation_ByOperationId_ReturnsTheBodyOnlyWhenAsked() + [Arguments("")] + [Arguments("?q=%20")] + [Arguments("?q=health&endpoint=GET%20/_cluster/health")] + public async Task Collection_WithoutExactlyOneOfQOrEndpoint_IsABadRequest(string query) + { + var gateway = A.Fake(); + + var (status, body) = await Get(gateway, query); + + status.Should().Be(HttpStatusCode.BadRequest); + body.GetProperty("message").GetString().Should().Be("Pass exactly one of q or endpoint."); + A.CallTo(gateway).MustNotHaveHappened(); + } + + [Test] + public async Task Endpoint_ListsTheBestMatchFirst() { List received = []; var gateway = A.Fake(); _ = A .CallTo(() => gateway.GetOperationAsync(A._, A._)) .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) - .Returns(new ApiOperationDetail { Operation = Operation, Versions = ["9"], Fields = [], Body = "Full body" }); + .Returns(Detail(otherMatches: Operation with { Api = "kibana", OperationId = "kibana-health" })); - var (withoutBody, withoutJson) = await Get(gateway, "/operation?operation_id=cluster-health"); - var (withBody, withJson) = await Get(gateway, "/operation?operation_id=cluster-health&include_body=true"); + var (status, body) = await Get(gateway, "?endpoint=GET%20/my-index/_search&api=elasticsearch"); - withoutBody.Should().Be(HttpStatusCode.OK); - withoutJson.TryGetProperty("body", out var omitted).Should().BeTrue(); - omitted.ValueKind.Should().Be(JsonValueKind.Null); - withoutJson.GetProperty("bodyLength").GetInt32().Should().Be(9); - withBody.Should().Be(HttpStatusCode.OK); - withJson.GetProperty("body").GetString().Should().Be("Full body"); - ApiOperationKey key = new ApiOperationIdKey("cluster-health"); - received.Should().Equal(new ApiOperationLookup(null, key), new ApiOperationLookup(null, key)); + status.Should().Be(HttpStatusCode.OK); + ApiOperationKey key = new ApiEndpointKey("GET /my-index/_search"); + received.Should().Equal(new ApiOperationLookup(new ApiScope("elasticsearch", null), key)); + body.GetProperty("endpoint").GetString().Should().Be("GET /my-index/_search"); + body + .GetProperty("results") + .EnumerateArray() + .Select(r => r.GetProperty("operationId").GetString()) + .Should() + .Equal("cluster-health", "kibana-health"); } [Test] - public async Task Operation_NoMatch_IsNotFound() + public async Task Endpoint_NoMatch_IsAnEmptyResult() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); - var (status, body) = await Get(gateway, "/operation?api=elasticsearch&endpoint=GET%20/nope"); + var (status, body) = await Get(gateway, "?endpoint=GET%20/nope"); - status.Should().Be(HttpStatusCode.NotFound); - body.GetProperty("errorType").GetString().Should().Be("operation_not_found"); - body.GetProperty("message").GetString().Should().Be("No API operation matches GET /nope in elasticsearch."); + status.Should().Be(HttpStatusCode.OK); + body.GetProperty("results").GetArrayLength().Should().Be(0); } [Test] - [Arguments("")] - [Arguments("?operation_id=cluster-health&endpoint=GET%20/_cluster/health")] - public async Task Operation_WithoutExactlyOneKey_IsABadRequest(string query) + public async Task Operation_ById_ReturnsTheBodyOnlyWhenAsked() { + List received = []; var gateway = A.Fake(); + _ = A + .CallTo(() => gateway.GetOperationAsync(A._, A._)) + .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) + .Returns(Detail("Full body")); - var (status, _) = await Get(gateway, $"/operation{query}"); + var (withoutBody, withoutJson) = await Get(gateway, "/cluster-health"); + var (withBody, withJson) = await Get(gateway, "/cluster-health?api=elasticsearch&include_body=true"); - status.Should().Be(HttpStatusCode.BadRequest); - A.CallTo(gateway).MustNotHaveHappened(); + withoutBody.Should().Be(HttpStatusCode.OK); + withoutJson.GetProperty("body").ValueKind.Should().Be(JsonValueKind.Null); + withoutJson.GetProperty("bodyLength").GetInt32().Should().Be(9); + withBody.Should().Be(HttpStatusCode.OK); + withJson.GetProperty("body").GetString().Should().Be("Full body"); + ApiOperationKey key = new ApiOperationIdKey("cluster-health"); + received.Should().Equal(new ApiOperationLookup(null, key), new ApiOperationLookup(new ApiScope("elasticsearch", null), key)); + } + + [Test] + public async Task Operation_UnknownId_IsNotFound() + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); + + var (status, body) = await Get(gateway, "/nope?api=elasticsearch"); + + status.Should().Be(HttpStatusCode.NotFound); + body.GetProperty("errorType").GetString().Should().Be("operation_not_found"); + body.GetProperty("message").GetString().Should().Be("No API operation matches nope in elasticsearch."); } [Test] - public async Task List_WithoutApi_ListsTheApis() + public async Task Apis_ListsEveryApi() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.ListApisAsync(A._)).Returns([ new ApiSummary { Key = "elasticsearch", Title = "Elasticsearch API", Url = "/docs/api/doc/elasticsearch", Versions = ["9"] } ]); - var (status, body) = await Get(gateway, "/"); + var (status, body) = await Get(gateway, "/apis"); status.Should().Be(HttpStatusCode.OK); body.GetProperty("apis")[0].GetProperty("key").GetString().Should().Be("elasticsearch"); + A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustNotHaveHappened(); } [Test] - public async Task List_WithApiAndGroup_ListsThatGroupsOperations() + public async Task Groups_ListsTheOperationsOfOneGroup() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.ListOperationsAsync(new ApiScope("elasticsearch", null), A._)).Returns([Operation]); - var (status, body) = await Get(gateway, "/?api=elasticsearch&group=Cluster"); + var (status, body) = await Get(gateway, "/groups?api=elasticsearch&group=Cluster"); status.Should().Be(HttpStatusCode.OK); body.GetProperty("groups")[0].GetProperty("operations")[0].GetProperty("path").GetString().Should().Be("/_cluster/health"); } [Test] - public async Task List_UnknownApi_IsNotFound() + public async Task Groups_WithoutApi_IsABadRequest() + { + var gateway = A.Fake(); + + var (status, body) = await Get(gateway, "/groups"); + + status.Should().Be(HttpStatusCode.BadRequest); + body.GetProperty("errorType").GetString().Should().Be("invalid_arguments"); + A.CallTo(gateway).MustNotHaveHappened(); + } + + [Test] + public async Task Groups_UnknownApi_IsNotFound() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.ListOperationsAsync(A._, A._)).Returns([]); - var (status, body) = await Get(gateway, "/?api=nope"); + var (status, body) = await Get(gateway, "/groups?api=nope"); status.Should().Be(HttpStatusCode.NotFound); body.GetProperty("errorType").GetString().Should().Be("api_not_found"); From f3acb866e0e9e21fa79e20d24e9ecd9c5222fabe Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 14:06:16 +0100 Subject: [PATCH 4/7] Address API operations by id and filter one collection Operations are one collection at /api-operations, filtered by q, endpoint, operation_id, api, version and group, and read at /api-operations/{id}, where id is {api}:{operationId}. APIs and their groups move to /apis, so no literal route shadows an id. view=full adds fields to each result, so an endpoint or id lookup without an API key takes one request. Co-Authored-By: Claude Opus 5.5 --- docs/data/api.md | 44 +++- .../MappingsExtensions.cs | 96 ++++---- .../SerializationContext.cs | 3 +- .../Responses/McpResponses.cs | 2 +- .../Tools/ApiTools.cs | 3 +- .../ApiReference/ApiReferenceService.cs | 186 ++++++++++++--- .../ApiReference/IApiGateway.cs | 4 + .../ApiOperationsEndpointTests.cs | 225 ++++++++++++------ 8 files changed, 394 insertions(+), 169 deletions(-) diff --git a/docs/data/api.md b/docs/data/api.md index 24801c1191..43d5b9be32 100644 --- a/docs/data/api.md +++ b/docs/data/api.md @@ -14,25 +14,47 @@ navigation_title: REST API | Navigation search | Search scoped to navigation structure and page titles | | Ask AI | Streaming endpoint for AI-powered question answering over documentation | | Changes feed | Content change feed for tracking documentation updates | -| API operations | Search, read, and list the REST API operations that API Explorer publishes | +| APIs and API operations | Search, read, and list the REST API operations that API Explorer publishes | -## API operations +## APIs and API operations -The API operations endpoints answer the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md). They serve HTTP clients such as the Elastic CLI's `elastic docs api` commands. All of them are `GET` requests under `/docs/_api/v1/api-operations`. Their responses are camelCase JSON, the same shapes the MCP tools return. +Two resources describe the REST APIs that API Explorer publishes: `apis` and `api-operations`. They answer the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md), and serve HTTP clients such as the Elastic CLI's `elastic docs api` commands. All requests are `GET` under `/docs/_api/v1`, and responses are camelCase JSON. -`api` is an API key such as `elasticsearch` or `kibana`. `version` is `main` or a major such as `9`, and needs `api`. Without `version`, a lookup reads the API's current version. +An operation's id is `{api}:{operationId}`, such as `elasticsearch:cluster-health`. Every operation in a response carries it as `id`. API keys never contain `:`, so an operation id after the first `:` may. + +`api` is an API key such as `elasticsearch` or `kibana`. `version` is `main` or a major such as `9`, and needs `api`. Without `version`, a request reads the API's current version. + +### APIs | Request | Query parameters | Returns | |---------|------------------|---------| -| `/api-operations?q=` | `q`: words, a route such as `GET /_cluster/health`, or a field path. A trailing dot, as in `retriever.`, lists child fields.
`api`, `version`
`include_deprecated` (default `false`)
`page` (default `1`)
`size` (default `10`, at most `50`) | `query`, `totalHits`, and `results`. Each result has its `operation`, a `score`, and the `matchedFields`. | -| `/api-operations?endpoint=` | `endpoint`: a request such as `GET /my-index/_search`, with or without the method.
`api`, `version` | `endpoint` and `results`: the operations that serve the request, best match first. No match is an empty list. | -| `/api-operations/{operationId}` | `api`, `version`
`include_body` (default `false`) | The `operation`, its `versions`, every documented field in `fields`, `bodyLength`, `otherMatches` (the same id in other APIs), and `body` only when `include_body=true` | -| `/api-operations/groups` | `api` (required), `version`
`group`: one group of operations | The API's `groups` of operations. An API with more than 150 operations lists only group names and counts, with a `note`, until you pass `group`. | -| `/api-operations/apis` | None | `apis`, with each API's key, landing page, and versions | +| `/apis` | None | `apis`, with each API's key, title, landing page, and versions | +| `/apis/{api}` | None | That API's key, title, landing page, and versions | +| `/apis/{api}/groups` | `version` | The API's `groups`, each with its name and operation count | + +### API operations + +`/api-operations` is one collection. It takes at most one of `q`, `endpoint`, or `operation_id`. Without any of them, it lists one API's operations and needs `api`. + +| Query parameter | Meaning | +|-----------------|---------| +| `q` | Words, a route such as `GET /_cluster/health`, or a field path. A trailing dot, as in `retriever.`, lists child fields. Results come in relevance order with a `score` and the `matchedFields`. | +| `endpoint` | A request such as `GET /my-index/_search`, with or without the method. Results are the operations that serve it, best match first. | +| `operation_id` | An operation id without its API, such as `cluster-health`. Results are that id in every API, or in `api` only. | +| `api`, `version` | Scope to one API and version | +| `group` | Lists one group of the API. It doesn't combine with `q`, `endpoint`, or `operation_id`. | +| `include_deprecated` | Include deprecated operations in a search or listing. The default is `false`. | +| `view` | `basic` (the default) or `full`. `full` adds each result's `versions` and `fields`, and needs `endpoint` or `operation_id`. | +| `include_body` | Adds each result's `body`. It needs `view=full`. | +| `page`, `size` | Page through a search or listing. `size` defaults to `10` and is at most `50`. | + +The collection returns `totalHits` and `results`. Each result has its `operation`, plus the fields its filters add. A lookup that matches nothing returns an empty page, not `404`. + +`/api-operations/{id}` reads one operation by its id. It takes `version` and `include_body` (default `false`). It returns the `operation`, its `versions`, every documented field in `fields`, `bodyLength`, `otherMatches`, and `body` only when `include_body=true`. -`/api-operations` needs exactly one of `q` or `endpoint`. The literal routes `groups` and `apis` take precedence over `{operationId}`. +### Errors -A request the lookups can't answer returns `{ "errorType": "...", "message": "..." }`. The status is `404` when `errorType` ends in `_not_found`: `operation_not_found`, `api_not_found`, or `group_not_found`. Invalid arguments return `400` with `invalid_arguments`. +A request these resources can't answer returns `{ "errorType": "...", "message": "..." }`. The status is `404` when `errorType` ends in `_not_found`: `operation_not_found`, `api_not_found`, or `group_not_found`. Invalid arguments return `400` with `invalid_arguments`. ## Ask AI provider diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index b1f6fcfbf9..f49a6460ef 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -187,78 +187,82 @@ Cancel ctx return Results.Ok(response); }); - // The same lookups as the search_api_operations, get_api_operation and list_api_operations MCP tools. - // The literal routes take precedence over {operationId}, so they reserve those ids. + // Two resources: the APIs API Explorer publishes, and their operations, addressed as {api}:{operationId}. + // They answer the same lookups as the search_api_operations, get_api_operation and list_api_operations MCP tools. private static void MapApiOperations(IEndpointRouteBuilder group) { - var operations = group.MapGroup("/api-operations"); - - // One collection, filtered by words (q) or by the request an operation serves (endpoint). - _ = operations.MapGet( + var apis = group.MapGroup("/apis"); + _ = apis.MapGet( "/", - async ( - [FromQuery(Name = "q")] string? query, - [FromQuery(Name = "endpoint")] string? endpoint, - [FromQuery(Name = "api")] string? api, - [FromQuery(Name = "version")] string? version, - [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, - [FromQuery(Name = "page")] int? pageNumber, - [FromQuery(Name = "size")] int? pageSize, - ApiReferenceService apiReference, - Cancel ctx - ) => - (string.IsNullOrWhiteSpace(query), string.IsNullOrWhiteSpace(endpoint)) switch - { - (false, true) => - ToResult( - await apiReference.SearchAsync( - query!, - api, - version, - includeDeprecated ?? false, - pageNumber ?? 1, - pageSize ?? 10, - ctx - ) - ), - (true, false) => ToResult(await apiReference.ResolveAsync(endpoint!, api, version, ctx)), - _ => Results.BadRequest(new ApiReferenceRejection("invalid_arguments", "Pass exactly one of q or endpoint.")) - } - ); - - _ = operations.MapGet( - "/apis", async (ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.ListAsync(null, null, null, ctx)) ); + _ = apis.MapGet( + "/{api}", + async (string api, ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.GetApiAsync(api, ctx)) + ); + _ = apis.MapGet( + "/{api}/groups", + async (string api, [FromQuery(Name = "version")] string? version, ApiReferenceService apiReference, Cancel ctx) => ToResult( + await apiReference.ListGroupsAsync(api, version, ctx) + ) + ); + var operations = group.MapGroup("/api-operations"); _ = operations.MapGet( - "/groups", + "/", async ( [FromQuery(Name = "api")] string? api, [FromQuery(Name = "version")] string? version, [FromQuery(Name = "group")] string? apiGroupName, + [FromQuery(Name = "q")] string? query, + [FromQuery(Name = "endpoint")] string? endpoint, + [FromQuery(Name = "operation_id")] string? operationId, + [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, + [FromQuery(Name = "view")] string? view, + [FromQuery(Name = "include_body")] bool? includeBody, + [FromQuery(Name = "page")] int? pageNumber, + [FromQuery(Name = "size")] int? pageSize, ApiReferenceService apiReference, Cancel ctx - ) => ToResult(await apiReference.ListGroupsAsync(api, version, apiGroupName, ctx)) + ) => view is not (null or "basic" or "full") + ? Results.BadRequest(new ApiReferenceRejection("invalid_arguments", "view is 'basic' or 'full'.")) + : ToResult( + await apiReference.QueryAsync( + new ApiOperationQuery + { + Api = api, + Version = version, + Group = apiGroupName, + Q = query, + Endpoint = endpoint, + OperationId = operationId, + IncludeDeprecated = includeDeprecated ?? false, + Full = view == "full", + IncludeBody = includeBody ?? false, + Page = pageNumber ?? 1, + Size = pageSize ?? 10 + }, + ctx + ) + ) ); - _ = operations.MapGet( - "/{operationId}", + "/{id}", async ( - string operationId, - [FromQuery(Name = "api")] string? api, + string id, [FromQuery(Name = "version")] string? version, [FromQuery(Name = "include_body")] bool? includeBody, ApiReferenceService apiReference, Cancel ctx - ) => ToResult(await apiReference.GetAsync(api, operationId, null, version, includeBody ?? false, ctx)) + ) => ToResult(await apiReference.GetByIdAsync(id, version, includeBody ?? false, ctx)) ); } private static IResult ToResult(ApiReferenceReply reply) => reply switch { ApiOperationSearchResponse r => Results.Ok(r), - ApiEndpointMatchResponse r => Results.Ok(r), + ApiOperationCollectionResponse r => Results.Ok(r), + ApiSummary r => Results.Ok(r), ApiOperationResponse r => Results.Ok(r), ApiListResponse r => Results.Ok(r), ApiOperationListResponse r => Results.Ok(r), diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index f11fb46d2e..6e51fafd17 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -43,7 +43,8 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(Search.ApiReference.ApiOperationSearchResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiOperationResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiListResponse))] -[JsonSerializable(typeof(Search.ApiReference.ApiEndpointMatchResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiOperationCollectionResponse))] +[JsonSerializable(typeof(Search.ApiReference.ApiSummary))] [JsonSerializable(typeof(Search.ApiReference.ApiOperationListResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiReferenceRejection))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs b/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs index ef38f57f52..ebed0fef3d 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Responses/McpResponses.cs @@ -192,7 +192,7 @@ public sealed record AiEnrichmentStatusDto [JsonSerializable(typeof(ApiOperationSearchResponse))] [JsonSerializable(typeof(ApiOperationResponse))] [JsonSerializable(typeof(ApiListResponse))] -[JsonSerializable(typeof(ApiEndpointMatchResponse))] +[JsonSerializable(typeof(ApiOperationCollectionResponse))] [JsonSerializable(typeof(ApiOperationListResponse))] [JsonSerializable(typeof(ApiOperationGroupDto))] [JsonSerializable(typeof(ApiOperationListItemDto))] diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs b/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs index 3c58286e29..65375408cf 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Tools/ApiTools.cs @@ -108,7 +108,8 @@ public Task ListApiOperations( McpJsonContext.Default.ApiOperationResponse ), ApiListResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiListResponse), - ApiEndpointMatchResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiEndpointMatchResponse), + ApiOperationCollectionResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiOperationCollectionResponse), + ApiSummary r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiSummary), ApiOperationListResponse r => ToolSucceeded.Serialize(r, McpJsonContext.Default.ApiOperationListResponse), ApiReferenceRejection r => new ToolRejected(r.ErrorType, r.Message) }; diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index 71f49f3192..91b053f0bb 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -7,8 +7,9 @@ namespace Elastic.Documentation.Search.ApiReference; /// What a call to answers: one response, or why the call was rejected. public readonly union ApiReferenceReply( ApiOperationSearchResponse, - ApiEndpointMatchResponse, + ApiOperationCollectionResponse, ApiOperationResponse, + ApiSummary, ApiListResponse, ApiOperationListResponse, ApiReferenceRejection @@ -88,30 +89,118 @@ CancellationToken ct } /// - /// Finds the operations that serve a request such as GET /my-index/_search, best match first. - /// No match is an empty result, not a rejection: this filters the operations rather than reading one. + /// Reads the operations collection: a search with , the operations behind an + /// or an (best match first), + /// or one API's operations by path when none of the three is set. /// - public async Task ResolveAsync(string endpoint, string? api, string? version, CancellationToken ct) + public async Task QueryAsync(ApiOperationQuery query, CancellationToken ct) { - if (VersionWithoutApi(api, version)) + if (VersionWithoutApi(query.Api, query.Version)) return VersionNeedsApi; - if (string.IsNullOrWhiteSpace(endpoint)) - return new ApiReferenceRejection("invalid_arguments", "Pass an endpoint, such as 'GET /_cluster/health'."); + var lookups = new[] { query.Q, query.Endpoint, query.OperationId }.Count(v => !string.IsNullOrWhiteSpace(v)); + if (lookups > 1) + return new ApiReferenceRejection("invalid_arguments", "Pass at most one of q, endpoint or operation_id."); + var exact = !string.IsNullOrWhiteSpace(query.Endpoint) || !string.IsNullOrWhiteSpace(query.OperationId); + if (query.Full && !exact) + return new ApiReferenceRejection("invalid_arguments", "view=full needs endpoint or operation_id."); + if (query.IncludeBody && !query.Full) + return new ApiReferenceRejection("invalid_arguments", "include_body needs view=full."); + if (!string.IsNullOrWhiteSpace(query.Group) && lookups > 0) + return new ApiReferenceRejection("invalid_arguments", "group filters a listing; pass it without q, endpoint or operation_id."); + + var scope = ToScope(query.Api, query.Version); + var page = Math.Max(1, query.Page); + var size = Math.Clamp(query.Size, 1, MaxPageSize); + + if (!string.IsNullOrWhiteSpace(query.Q)) + { + var hits = await apiGateway.SearchOperationsAsync( + new ApiOperationSearch(query.Q, scope, query.IncludeDeprecated, page, size), + ct + ); + return new ApiOperationCollectionResponse + { + TotalHits = hits.Total, + Results = + [ + .. hits.Hits.Select( + h => new ApiOperationItem { Operation = h.Operation, Score = h.Score, MatchedFields = h.MatchedFields } + ) + ] + }; + } - var lookup = new ApiOperationLookup(ToScope(api, version), new ApiEndpointKey(endpoint.Trim())); - var detail = await apiGateway.GetOperationAsync(lookup, ct); - return new ApiEndpointMatchResponse + if (exact) + { + ApiOperationKey key = string.IsNullOrWhiteSpace(query.Endpoint) + ? new ApiOperationIdKey(query.OperationId!.Trim()) + : new ApiEndpointKey(query.Endpoint.Trim()); + var detail = await apiGateway.GetOperationAsync(new ApiOperationLookup(scope, key), ct); + if (detail is null) + return new ApiOperationCollectionResponse { TotalHits = 0, Results = [] }; + List items = [ToItem(detail.Operation, query.Full ? detail : null, query.IncludeBody)]; + foreach (var other in detail.OtherMatches) + { + // Other matches come back as summaries; a full view reads each one in its own API. + var otherDetail = query.Full + ? await apiGateway.GetOperationAsync( + new ApiOperationLookup(new ApiScope(other.Api, scope?.Version), new ApiOperationIdKey(other.OperationId)), + ct + ) + : null; + items.Add(ToItem(other, otherDetail, query.IncludeBody)); + } + return new ApiOperationCollectionResponse { TotalHits = items.Count, Results = items }; + } + + if (scope is null) + return new ApiReferenceRejection("invalid_arguments", "Pass api to list operations, or one of q, endpoint or operation_id."); + var operations = await apiGateway.ListOperationsAsync(scope, ct); + if (operations.Count == 0) + return ApiNotFound(scope); + var listed = operations.Where(o => query.IncludeDeprecated || !o.Deprecated); + if (!string.IsNullOrWhiteSpace(query.Group)) { - Endpoint = endpoint.Trim(), - Results = detail is null ? [] : [detail.Operation, .. detail.OtherMatches] + var group = query.Group.Trim(); + listed = listed.Where(o => string.Equals(o.Group ?? UngroupedName, group, StringComparison.OrdinalIgnoreCase)).ToList(); + if (!listed.Any()) + return new ApiReferenceRejection("group_not_found", $"API '{scope.Key}' has no group '{group}'."); + } + var sorted = listed.OrderBy(o => o.Path, StringComparer.Ordinal).ThenBy(o => o.Method, StringComparer.Ordinal).ToList(); + return new ApiOperationCollectionResponse + { + TotalHits = sorted.Count, + Results = [.. sorted.Skip((page - 1) * size).Take(size).Select(o => new ApiOperationItem { Operation = o })] }; } - /// Lists the operations of one API by group; is required. - public Task ListGroupsAsync(string? api, string? version, string? group, CancellationToken ct) => - string.IsNullOrWhiteSpace(api) - ? Task.FromResult(new ApiReferenceRejection("invalid_arguments", "Pass api, such as 'elasticsearch'.")) - : ListAsync(api, version, group, ct); + /// Reads one operation by its , {api}:{operationId}. + public Task GetByIdAsync(string id, string? version, bool includeBody, CancellationToken ct) + { + // API keys never contain ':', so the first one ends the key and the operation id may contain more. + var separator = id.IndexOf(':'); + return separator <= 0 || separator == id.Length - 1 + ? Task.FromResult( + new ApiReferenceRejection("invalid_arguments", "An operation id looks like 'elasticsearch:cluster-health'.") + ) + : GetAsync(id[..separator], id[(separator + 1)..], null, version, includeBody, ct); + } + + /// Reads one API by its key. + public async Task GetApiAsync(string api, CancellationToken ct) + { + var apis = await apiGateway.ListApisAsync(ct); + var key = api.Trim().ToLowerInvariant(); + return apis.FirstOrDefault(a => a.Key == key) is { } found ? found : new ApiReferenceRejection("api_not_found", $"No API '{api}'."); + } + + /// Counts one API's operations by group, without listing them. + public async Task ListGroupsAsync(string api, string? version, CancellationToken ct) + { + var scope = ToScope(api, version)!; + var operations = await apiGateway.ListOperationsAsync(scope, ct); + return operations.Count == 0 ? ApiNotFound(scope) : GroupOperations(scope, operations, group: null, groupsOnly: true); + } /// Lists every API without , or the operations of one API by group. public async Task ListAsync(string? api, string? version, string? group, CancellationToken ct) @@ -122,15 +211,21 @@ public async Task ListAsync(string? api, string? version, str return new ApiListResponse { Apis = await apiGateway.ListApisAsync(ct) }; var operations = await apiGateway.ListOperationsAsync(scope, ct); - return operations.Count == 0 - ? new ApiReferenceRejection( - "api_not_found", - $"No operations found for API '{api}'{(version is null ? "" : $" version '{version}'")}." - ) - : GroupOperations(scope, operations, group); + return operations.Count == 0 ? ApiNotFound(scope) : GroupOperations(scope, operations, group); } - internal static ApiReferenceReply GroupOperations(ApiScope scope, IReadOnlyList operations, string? group) + private static ApiReferenceRejection ApiNotFound(ApiScope scope) => + new("api_not_found", $"No operations found for API '{scope.Key}'{(scope.Version is null ? "" : $" version '{scope.Version}'")}."); + + private static ApiOperationItem ToItem(ApiOperationSummary operation, ApiOperationDetail? detail, bool includeBody) => + new() { Operation = operation, Versions = detail?.Versions, Fields = detail?.Fields, Body = includeBody ? detail?.Body : null }; + + internal static ApiReferenceReply GroupOperations( + ApiScope scope, + IReadOnlyList operations, + string? group, + bool groupsOnly = false + ) { var groups = operations .GroupBy(o => o.Group ?? UngroupedName, StringComparer.OrdinalIgnoreCase) @@ -146,14 +241,16 @@ internal static ApiReferenceReply GroupOperations(ApiScope scope, IReadOnlyList< ); } - var listOperations = group is not null || operations.Count <= MaxListedOperations; + var listOperations = !groupsOnly && (group is not null || operations.Count <= MaxListedOperations); return new ApiOperationListResponse { Api = scope.Key, Version = scope.Version, TotalOperations = groups.Sum(g => g.Count()), Groups = [.. groups.Select(g => ToGroup(g, listOperations))], - Note = listOperations ? null : $"This API has {operations.Count} operations. Pass group to list the operations of one group." + Note = listOperations || groupsOnly + ? null + : $"This API has {operations.Count} operations. Pass group to list the operations of one group." }; } @@ -203,11 +300,40 @@ public sealed record ApiOperationSearchResponse public required IReadOnlyList Results { get; init; } } -/// The operations that serve one request, best match first. -public sealed record ApiEndpointMatchResponse +/// The filters of the operations collection. At most one of , or . +public sealed record ApiOperationQuery +{ + public string? Api { get; init; } + public string? Version { get; init; } + public string? Group { get; init; } + public string? Q { get; init; } + public string? Endpoint { get; init; } + public string? OperationId { get; init; } + public bool IncludeDeprecated { get; init; } + /// Adds each result's versions and fields; needs or . + public bool Full { get; init; } + /// Adds each result's body; needs . + public bool IncludeBody { get; init; } + public int Page { get; init; } = 1; + public int Size { get; init; } = 10; +} + +/// A page of the operations collection. +public sealed record ApiOperationCollectionResponse { - public required string Endpoint { get; init; } - public required IReadOnlyList Results { get; init; } + public required long TotalHits { get; init; } + public required IReadOnlyList Results { get; init; } +} + +/// One operation in the collection. Search adds a score and the matched fields; the full view adds versions, fields and the body. +public sealed record ApiOperationItem +{ + public required ApiOperationSummary Operation { get; init; } + public float? Score { get; init; } + public IReadOnlyList? MatchedFields { get; init; } + public string[]? Versions { get; init; } + public IReadOnlyList? Fields { get; init; } + public string? Body { get; init; } } /// One operation with its routes, versions and documented fields. diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs index 3bd3bf9308..8800a6a368 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs @@ -50,6 +50,10 @@ public sealed record ApiOperationSummary public required string Method { get; init; } public required string Path { get; init; } public required string OperationId { get; init; } + + /// The operation's id across APIs, {api}:{operationId}, as the docs API addresses it. + public string Id => $"{Api}:{OperationId}"; + public string? Group { get; init; } public bool Deprecated { get; init; } diff --git a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs index 27686b72cb..5d963e6b06 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs @@ -44,16 +44,27 @@ public static void DisposeSharedFactory() { Gateway.Current = gateway; using var client = SharedFactory.Value.CreateClient(); - using var response = await client.GetAsync( - $"/docs/_api/v1/api-operations{pathAndQuery}", - TestContext.Current!.Execution.CancellationToken - ); + using var response = await client.GetAsync($"/docs/_api/v1{pathAndQuery}", TestContext.Current!.Execution.CancellationToken); var json = await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken); return (response.StatusCode, JsonElement.Parse(json)); } private static ApiOperationDetail Detail(string? body = null, params ApiOperationSummary[] otherMatches) => - new() { Operation = Operation, Versions = ["9"], Fields = [], Body = body, OtherMatches = otherMatches }; + new() { Operation = Operation, Versions = ["9"], Fields = [Field], Body = body, OtherMatches = otherMatches }; + + private static readonly ApiField Field = new() + { + Name = "level", + Path = "level", + Type = "string", + Location = "query", + Description = "Detail level" + }; + + private static readonly ApiOperationSummary KibanaOperation = Operation with { Api = "kibana", OperationId = "kibana-health" }; + + private static IEnumerable Ids(JsonElement body) => + body.GetProperty("results").EnumerateArray().Select(r => r.GetProperty("operation").GetProperty("id").GetString()); [Test] public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() @@ -63,83 +74,136 @@ public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() _ = A .CallTo(() => gateway.SearchOperationsAsync(A._, A._)) .Invokes((ApiOperationSearch search, CancellationToken _) => received = search) - .Returns(new ApiOperationPage(1, [new ApiOperationHit(Operation, 1, [])])); + .Returns(new ApiOperationPage(1, [new ApiOperationHit(Operation, 2, [Field])])); - var (status, body) = await Get(gateway, "?q=health&api=%20Elasticsearch%20&version=9&include_deprecated=true&size=500"); + var (status, body) = await Get( + gateway, + "/api-operations?q=health&api=%20Elasticsearch%20&version=9&include_deprecated=true&size=500" + ); status.Should().Be(HttpStatusCode.OK); received.Should().Be( new ApiOperationSearch("health", new ApiScope("elasticsearch", "9"), true, 1, ApiReferenceService.MaxPageSize) ); body.GetProperty("totalHits").GetInt64().Should().Be(1); - body.GetProperty("results")[0].GetProperty("operation").GetProperty("operationId").GetString().Should().Be("cluster-health"); + var hit = body.GetProperty("results")[0]; + hit.GetProperty("operation").GetProperty("id").GetString().Should().Be("elasticsearch:cluster-health"); + hit.GetProperty("score").GetSingle().Should().Be(2); + hit.GetProperty("matchedFields")[0].GetProperty("path").GetString().Should().Be("level"); } [Test] - public async Task Search_VersionWithoutApi_IsABadRequest() + [Arguments("/api-operations?q=health&version=9", "version needs api: pass the API key the version belongs to.")] + [Arguments("/api-operations?q=health&endpoint=GET%20/x", "Pass at most one of q, endpoint or operation_id.")] + [Arguments("/api-operations?q=health&view=full", "view=full needs endpoint or operation_id.")] + [Arguments("/api-operations?operation_id=x&include_body=true", "include_body needs view=full.")] + [Arguments("/api-operations?api=elasticsearch&group=cluster&q=health", "group filters a listing; pass it without q, endpoint or operation_id.")] + [Arguments("/api-operations", "Pass api to list operations, or one of q, endpoint or operation_id.")] + [Arguments("/api-operations?operation_id=x&view=everything", "view is 'basic' or 'full'.")] + [Arguments("/api-operations/cluster-health", "An operation id looks like 'elasticsearch:cluster-health'.")] + [Arguments("/api-operations/elasticsearch:", "An operation id looks like 'elasticsearch:cluster-health'.")] + public async Task InvalidArguments_AreABadRequestWithoutQueryingTheIndex(string pathAndQuery, string message) { var gateway = A.Fake(); - var (status, body) = await Get(gateway, "?q=health&version=9"); + var (status, body) = await Get(gateway, pathAndQuery); status.Should().Be(HttpStatusCode.BadRequest); body.GetProperty("errorType").GetString().Should().Be("invalid_arguments"); + body.GetProperty("message").GetString().Should().Be(message); A.CallTo(gateway).MustNotHaveHappened(); } [Test] - [Arguments("")] - [Arguments("?q=%20")] - [Arguments("?q=health&endpoint=GET%20/_cluster/health")] - public async Task Collection_WithoutExactlyOneOfQOrEndpoint_IsABadRequest(string query) + public async Task Endpoint_FullView_ReturnsEveryMatchWithItsFieldsInOneRequest() { + List received = []; var gateway = A.Fake(); + A + .CallTo(() => gateway.GetOperationAsync(A._, A._)) + .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) + .ReturnsNextFromSequence(Detail("Body", KibanaOperation), Detail() with { Operation = KibanaOperation }); - var (status, body) = await Get(gateway, query); + var (status, body) = await Get(gateway, "/api-operations?endpoint=GET%20/my-index/_search&view=full&include_body=true"); - status.Should().Be(HttpStatusCode.BadRequest); - body.GetProperty("message").GetString().Should().Be("Pass exactly one of q or endpoint."); - A.CallTo(gateway).MustNotHaveHappened(); + status.Should().Be(HttpStatusCode.OK); + Ids(body).Should().Equal("elasticsearch:cluster-health", "kibana:kibana-health"); + var best = body.GetProperty("results")[0]; + best.GetProperty("fields")[0].GetProperty("path").GetString().Should().Be("level"); + best.GetProperty("body").GetString().Should().Be("Body"); + body.GetProperty("results")[1].GetProperty("fields").GetArrayLength().Should().Be(1); + ApiOperationKey endpointKey = new ApiEndpointKey("GET /my-index/_search"); + ApiOperationKey kibanaKey = new ApiOperationIdKey("kibana-health"); + received.Should().Equal(new ApiOperationLookup(null, endpointKey), new ApiOperationLookup(new ApiScope("kibana", null), kibanaKey)); } [Test] - public async Task Endpoint_ListsTheBestMatchFirst() + public async Task OperationId_BasicView_ListsTheSameIdInEveryApiWithoutFields() { - List received = []; var gateway = A.Fake(); - _ = A - .CallTo(() => gateway.GetOperationAsync(A._, A._)) - .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) - .Returns(Detail(otherMatches: Operation with { Api = "kibana", OperationId = "kibana-health" })); + _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns( + Detail(otherMatches: KibanaOperation) + ); - var (status, body) = await Get(gateway, "?endpoint=GET%20/my-index/_search&api=elasticsearch"); + var (status, body) = await Get(gateway, "/api-operations?operation_id=cluster-health"); status.Should().Be(HttpStatusCode.OK); - ApiOperationKey key = new ApiEndpointKey("GET /my-index/_search"); - received.Should().Equal(new ApiOperationLookup(new ApiScope("elasticsearch", null), key)); - body.GetProperty("endpoint").GetString().Should().Be("GET /my-index/_search"); - body - .GetProperty("results") - .EnumerateArray() - .Select(r => r.GetProperty("operationId").GetString()) - .Should() - .Equal("cluster-health", "kibana-health"); + Ids(body).Should().Equal("elasticsearch:cluster-health", "kibana:kibana-health"); + body.GetProperty("results")[0].GetProperty("fields").ValueKind.Should().Be(JsonValueKind.Null); + A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustHaveHappenedOnceExactly(); } [Test] - public async Task Endpoint_NoMatch_IsAnEmptyResult() + public async Task Endpoint_NoMatch_IsAnEmptyPage() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); - var (status, body) = await Get(gateway, "?endpoint=GET%20/nope"); + var (status, body) = await Get(gateway, "/api-operations?endpoint=GET%20/nope"); status.Should().Be(HttpStatusCode.OK); + body.GetProperty("totalHits").GetInt64().Should().Be(0); body.GetProperty("results").GetArrayLength().Should().Be(0); } [Test] - public async Task Operation_ById_ReturnsTheBodyOnlyWhenAsked() + public async Task Listing_FiltersByGroupHidesDeprecatedSortsByPathAndPages() + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.ListOperationsAsync(new ApiScope("elasticsearch", null), A._)).Returns([ + Operation with { OperationId = "c", Path = "/_cluster/state" }, + Operation with { OperationId = "a", Path = "/_cluster/allocation" }, + Operation with { OperationId = "b", Path = "/_cluster/health", Method = "POST" }, + Operation with { OperationId = "old", Path = "/_cluster/old", Deprecated = true }, + Operation with { OperationId = "s", Path = "/_search", Group = "search" } + ]); + + var (status, body) = await Get(gateway, "/api-operations?api=elasticsearch&group=CLUSTER&size=2&page=2"); + + status.Should().Be(HttpStatusCode.OK); + body.GetProperty("totalHits").GetInt64().Should().Be(3); + Ids(body).Should().Equal("elasticsearch:c"); + } + + [Test] + [Arguments("/api-operations?api=nope", "api_not_found")] + [Arguments("/api-operations?api=elasticsearch&group=nope", "group_not_found")] + [Arguments("/apis/nope/groups", "api_not_found")] + public async Task Listing_UnknownApiOrGroup_IsNotFound(string pathAndQuery, string errorType) + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.ListOperationsAsync(A._, A._)).ReturnsLazily( + (ApiScope scope, CancellationToken _) => scope.Key == "elasticsearch" ? [Operation] : [] + ); + + var (status, body) = await Get(gateway, pathAndQuery); + + status.Should().Be(HttpStatusCode.NotFound); + body.GetProperty("errorType").GetString().Should().Be(errorType); + } + + [Test] + public async Task Operation_ById_SplitsAtTheFirstColonAndReturnsTheBodyOnlyWhenAsked() { List received = []; var gateway = A.Fake(); @@ -148,16 +212,21 @@ public async Task Operation_ById_ReturnsTheBodyOnlyWhenAsked() .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) .Returns(Detail("Full body")); - var (withoutBody, withoutJson) = await Get(gateway, "/cluster-health"); - var (withBody, withJson) = await Get(gateway, "/cluster-health?api=elasticsearch&include_body=true"); + var (withoutBody, withoutJson) = await Get(gateway, "/api-operations/elasticsearch:cluster-health"); + var (withBody, withJson) = await Get(gateway, "/api-operations/kibana%3Aa%3Ab?version=9&include_body=true"); withoutBody.Should().Be(HttpStatusCode.OK); + withoutJson.GetProperty("operation").GetProperty("id").GetString().Should().Be("elasticsearch:cluster-health"); withoutJson.GetProperty("body").ValueKind.Should().Be(JsonValueKind.Null); withoutJson.GetProperty("bodyLength").GetInt32().Should().Be(9); withBody.Should().Be(HttpStatusCode.OK); withJson.GetProperty("body").GetString().Should().Be("Full body"); - ApiOperationKey key = new ApiOperationIdKey("cluster-health"); - received.Should().Equal(new ApiOperationLookup(null, key), new ApiOperationLookup(new ApiScope("elasticsearch", null), key)); + ApiOperationKey first = new ApiOperationIdKey("cluster-health"); + ApiOperationKey second = new ApiOperationIdKey("a:b"); + received.Should().Equal( + new ApiOperationLookup(new ApiScope("elasticsearch", null), first), + new ApiOperationLookup(new ApiScope("kibana", "9"), second) + ); } [Test] @@ -166,61 +235,59 @@ public async Task Operation_UnknownId_IsNotFound() var gateway = A.Fake(); _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); - var (status, body) = await Get(gateway, "/nope?api=elasticsearch"); + var (status, body) = await Get(gateway, "/api-operations/elasticsearch:nope"); status.Should().Be(HttpStatusCode.NotFound); body.GetProperty("errorType").GetString().Should().Be("operation_not_found"); body.GetProperty("message").GetString().Should().Be("No API operation matches nope in elasticsearch."); } - [Test] - public async Task Apis_ListsEveryApi() + private static readonly ApiSummary Elasticsearch = new() { - var gateway = A.Fake(); - _ = A.CallTo(() => gateway.ListApisAsync(A._)).Returns([ - new ApiSummary { Key = "elasticsearch", Title = "Elasticsearch API", Url = "/docs/api/doc/elasticsearch", Versions = ["9"] } - ]); - - var (status, body) = await Get(gateway, "/apis"); - - status.Should().Be(HttpStatusCode.OK); - body.GetProperty("apis")[0].GetProperty("key").GetString().Should().Be("elasticsearch"); - A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustNotHaveHappened(); - } - - [Test] - public async Task Groups_ListsTheOperationsOfOneGroup() - { - var gateway = A.Fake(); - _ = A.CallTo(() => gateway.ListOperationsAsync(new ApiScope("elasticsearch", null), A._)).Returns([Operation]); - - var (status, body) = await Get(gateway, "/groups?api=elasticsearch&group=Cluster"); - - status.Should().Be(HttpStatusCode.OK); - body.GetProperty("groups")[0].GetProperty("operations")[0].GetProperty("path").GetString().Should().Be("/_cluster/health"); - } + Key = "elasticsearch", + Title = "Elasticsearch API", + Url = "/docs/api/doc/elasticsearch", + Versions = ["9"] + }; [Test] - public async Task Groups_WithoutApi_IsABadRequest() + public async Task Apis_ListsEveryApiAndReadsOneByKey() { var gateway = A.Fake(); - - var (status, body) = await Get(gateway, "/groups"); - - status.Should().Be(HttpStatusCode.BadRequest); - body.GetProperty("errorType").GetString().Should().Be("invalid_arguments"); - A.CallTo(gateway).MustNotHaveHappened(); + _ = A.CallTo(() => gateway.ListApisAsync(A._)).Returns([Elasticsearch]); + + var (listStatus, list) = await Get(gateway, "/apis"); + var (oneStatus, one) = await Get(gateway, "/apis/Elasticsearch"); + var (missingStatus, missing) = await Get(gateway, "/apis/nope"); + + listStatus.Should().Be(HttpStatusCode.OK); + list.GetProperty("apis")[0].GetProperty("key").GetString().Should().Be("elasticsearch"); + oneStatus.Should().Be(HttpStatusCode.OK); + one.GetProperty("title").GetString().Should().Be("Elasticsearch API"); + missingStatus.Should().Be(HttpStatusCode.NotFound); + missing.GetProperty("errorType").GetString().Should().Be("api_not_found"); } [Test] - public async Task Groups_UnknownApi_IsNotFound() + public async Task Groups_CountOperationsWithoutListingThem() { var gateway = A.Fake(); - _ = A.CallTo(() => gateway.ListOperationsAsync(A._, A._)).Returns([]); + _ = A.CallTo(() => gateway.ListOperationsAsync(new ApiScope("elasticsearch", "9"), A._)).Returns([ + Operation, + Operation with { OperationId = "x" }, + Operation with { OperationId = "s", Group = "search" } + ]); - var (status, body) = await Get(gateway, "/groups?api=nope"); + var (status, body) = await Get(gateway, "/apis/elasticsearch/groups?version=9"); - status.Should().Be(HttpStatusCode.NotFound); - body.GetProperty("errorType").GetString().Should().Be("api_not_found"); + status.Should().Be(HttpStatusCode.OK); + body + .GetProperty("groups") + .EnumerateArray() + .Select(g => (g.GetProperty("name").GetString(), g.GetProperty("count").GetInt32())) + .Should() + .Equal(("cluster", 2), ("search", 1)); + body.GetProperty("groups")[0].GetProperty("operations").ValueKind.Should().Be(JsonValueKind.Null); + body.GetProperty("note").ValueKind.Should().Be(JsonValueKind.Null); } } From 323b85b5fc16adac4149ba663542f8a33193df44 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 14:30:29 +0100 Subject: [PATCH 5/7] Read every lookup match in one query and align group counts The gateway's lookups already load each match's trees, properties and body, so FindOperationsAsync returns them all and the full view no longer reads each other match again. Group counts drop deprecated operations unless include_deprecated is set, like the group listing, and a blank API key is a 400 instead of a NullReferenceException. Co-Authored-By: Claude Opus 5.5 --- docs/data/api.md | 2 +- .../MappingsExtensions.cs | 10 ++-- .../ApiReference/ApiGateway.cs | 34 ++++++++----- .../ApiReference/ApiReferenceService.cs | 34 ++++++------- .../ApiReference/IApiGateway.cs | 3 ++ .../ApiOperationsEndpointTests.cs | 51 +++++++++++++++---- tests/Mcp.Remote.Tests/ApiGatewayTests.cs | 17 +++++++ tests/Mcp.Remote.Tests/ElasticsearchStub.cs | 4 ++ 8 files changed, 107 insertions(+), 48 deletions(-) diff --git a/docs/data/api.md b/docs/data/api.md index 43d5b9be32..4e0006f28e 100644 --- a/docs/data/api.md +++ b/docs/data/api.md @@ -30,7 +30,7 @@ An operation's id is `{api}:{operationId}`, such as `elasticsearch:cluster-healt |---------|------------------|---------| | `/apis` | None | `apis`, with each API's key, title, landing page, and versions | | `/apis/{api}` | None | That API's key, title, landing page, and versions | -| `/apis/{api}/groups` | `version` | The API's `groups`, each with its name and operation count | +| `/apis/{api}/groups` | `version`
`include_deprecated` (default `false`) | The API's `groups`, each with its name and operation count. Counts follow the same deprecated filter as a group listing. | ### API operations diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index f49a6460ef..128ccc5e21 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -202,9 +202,13 @@ private static void MapApiOperations(IEndpointRouteBuilder group) ); _ = apis.MapGet( "/{api}/groups", - async (string api, [FromQuery(Name = "version")] string? version, ApiReferenceService apiReference, Cancel ctx) => ToResult( - await apiReference.ListGroupsAsync(api, version, ctx) - ) + async ( + string api, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult(await apiReference.ListGroupsAsync(api, version, includeDeprecated ?? false, ctx)) ); var operations = group.MapGroup("/api-operations"); diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs index 2432459f94..4dd040eb84 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs @@ -84,6 +84,13 @@ public async Task SearchOperationsAsync(ApiOperationSearch sea /// public async Task GetOperationAsync(ApiOperationLookup lookup, CancellationToken ct = default) + { + var matches = await FindOperationsAsync(lookup, ct); + return matches.Count == 0 ? null : matches[0] with { OtherMatches = [.. matches.Skip(1).Select(m => m.Operation)] }; + } + + /// + public async Task> FindOperationsAsync(ApiOperationLookup lookup, CancellationToken ct = default) { var ranked = lookup.Key switch { @@ -91,22 +98,21 @@ public async Task SearchOperationsAsync(ApiOperationSearch sea ApiEndpointKey endpoint => await FindByEndpoint(lookup.Scope, ApiRouteMatch.Parse(endpoint.Endpoint), ct) }; if (ranked.Count == 0) - { logger.LogDebug("No API operation matches {Lookup}", lookup); - return null; - } - var best = ranked[0]; - var api = best.Api!; - return new ApiOperationDetail - { - Operation = ToSummary(best, lookup.Scope), - Versions = [.. api.Trees.Select(t => t.Tree)], - Fields = [.. api.Properties.Select(ToField)], - AiShortSummary = best.AiShortSummary, - Body = best.Body, - OtherMatches = [.. ranked.Skip(1).Select(d => ToSummary(d, lookup.Scope))] - }; + // Both lookups read DetailSource, so every match already carries its trees, properties and body. + return [ + .. ranked.Select( + d => new ApiOperationDetail + { + Operation = ToSummary(d, lookup.Scope), + Versions = [.. d.Api!.Trees.Select(t => t.Tree)], + Fields = [.. d.Api.Properties.Select(ToField)], + AiShortSummary = d.AiShortSummary, + Body = d.Body + } + ) + ]; } /// diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index 91b053f0bb..925cab5058 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -135,22 +135,12 @@ .. hits.Hits.Select( ApiOperationKey key = string.IsNullOrWhiteSpace(query.Endpoint) ? new ApiOperationIdKey(query.OperationId!.Trim()) : new ApiEndpointKey(query.Endpoint.Trim()); - var detail = await apiGateway.GetOperationAsync(new ApiOperationLookup(scope, key), ct); - if (detail is null) - return new ApiOperationCollectionResponse { TotalHits = 0, Results = [] }; - List items = [ToItem(detail.Operation, query.Full ? detail : null, query.IncludeBody)]; - foreach (var other in detail.OtherMatches) + var matches = await apiGateway.FindOperationsAsync(new ApiOperationLookup(scope, key), ct); + return new ApiOperationCollectionResponse { - // Other matches come back as summaries; a full view reads each one in its own API. - var otherDetail = query.Full - ? await apiGateway.GetOperationAsync( - new ApiOperationLookup(new ApiScope(other.Api, scope?.Version), new ApiOperationIdKey(other.OperationId)), - ct - ) - : null; - items.Add(ToItem(other, otherDetail, query.IncludeBody)); - } - return new ApiOperationCollectionResponse { TotalHits = items.Count, Results = items }; + TotalHits = matches.Count, + Results = [.. matches.Select(m => ToItem(m.Operation, query.Full ? m : null, query.IncludeBody))] + }; } if (scope is null) @@ -194,12 +184,18 @@ public async Task GetApiAsync(string api, CancellationToken c return apis.FirstOrDefault(a => a.Key == key) is { } found ? found : new ApiReferenceRejection("api_not_found", $"No API '{api}'."); } - /// Counts one API's operations by group, without listing them. - public async Task ListGroupsAsync(string api, string? version, CancellationToken ct) + /// + /// Counts one API's operations by group, without listing them. Deprecated operations count only with + /// , as in the listing, so a count matches the group's listing. + /// + public async Task ListGroupsAsync(string api, string? version, bool includeDeprecated, CancellationToken ct) { - var scope = ToScope(api, version)!; + if (ToScope(api, version) is not { } scope) + return new ApiReferenceRejection("invalid_arguments", "Pass an API key, such as 'elasticsearch'."); var operations = await apiGateway.ListOperationsAsync(scope, ct); - return operations.Count == 0 ? ApiNotFound(scope) : GroupOperations(scope, operations, group: null, groupsOnly: true); + return operations.Count == 0 + ? ApiNotFound(scope) + : GroupOperations(scope, [.. operations.Where(o => includeDeprecated || !o.Deprecated)], group: null, groupsOnly: true); } /// Lists every API without , or the operations of one API by group. diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs index 8800a6a368..0c1a4da8aa 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs @@ -12,6 +12,9 @@ public interface IApiGateway /// The best match for , or null when no operation matches. Task GetOperationAsync(ApiOperationLookup lookup, CancellationToken ct = default); + /// Every match for , best first, each with its versions, fields and body, from one index query. + Task> FindOperationsAsync(ApiOperationLookup lookup, CancellationToken ct = default); + Task> ListApisAsync(CancellationToken ct = default); Task> ListOperationsAsync(ApiScope scope, CancellationToken ct = default); diff --git a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs index 5d963e6b06..235513df1c 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs @@ -102,6 +102,7 @@ public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() [Arguments("/api-operations?operation_id=x&view=everything", "view is 'basic' or 'full'.")] [Arguments("/api-operations/cluster-health", "An operation id looks like 'elasticsearch:cluster-health'.")] [Arguments("/api-operations/elasticsearch:", "An operation id looks like 'elasticsearch:cluster-health'.")] + [Arguments("/apis/%20/groups", "Pass an API key, such as 'elasticsearch'.")] public async Task InvalidArguments_AreABadRequestWithoutQueryingTheIndex(string pathAndQuery, string message) { var gateway = A.Fake(); @@ -115,14 +116,14 @@ public async Task InvalidArguments_AreABadRequestWithoutQueryingTheIndex(string } [Test] - public async Task Endpoint_FullView_ReturnsEveryMatchWithItsFieldsInOneRequest() + public async Task Endpoint_FullView_ReturnsEveryMatchWithItsFieldsFromOneLookup() { List received = []; var gateway = A.Fake(); - A - .CallTo(() => gateway.GetOperationAsync(A._, A._)) + _ = A + .CallTo(() => gateway.FindOperationsAsync(A._, A._)) .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) - .ReturnsNextFromSequence(Detail("Body", KibanaOperation), Detail() with { Operation = KibanaOperation }); + .Returns([Detail("Body"), Detail() with { Operation = KibanaOperation }]); var (status, body) = await Get(gateway, "/api-operations?endpoint=GET%20/my-index/_search&view=full&include_body=true"); @@ -133,31 +134,31 @@ public async Task Endpoint_FullView_ReturnsEveryMatchWithItsFieldsInOneRequest() best.GetProperty("body").GetString().Should().Be("Body"); body.GetProperty("results")[1].GetProperty("fields").GetArrayLength().Should().Be(1); ApiOperationKey endpointKey = new ApiEndpointKey("GET /my-index/_search"); - ApiOperationKey kibanaKey = new ApiOperationIdKey("kibana-health"); - received.Should().Equal(new ApiOperationLookup(null, endpointKey), new ApiOperationLookup(new ApiScope("kibana", null), kibanaKey)); + received.Should().Equal(new ApiOperationLookup(null, endpointKey)); + A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustNotHaveHappened(); } [Test] public async Task OperationId_BasicView_ListsTheSameIdInEveryApiWithoutFields() { var gateway = A.Fake(); - _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns( - Detail(otherMatches: KibanaOperation) - ); + _ = A.CallTo(() => gateway.FindOperationsAsync(A._, A._)).Returns([ + Detail(), + Detail() with { Operation = KibanaOperation } + ]); var (status, body) = await Get(gateway, "/api-operations?operation_id=cluster-health"); status.Should().Be(HttpStatusCode.OK); Ids(body).Should().Equal("elasticsearch:cluster-health", "kibana:kibana-health"); body.GetProperty("results")[0].GetProperty("fields").ValueKind.Should().Be(JsonValueKind.Null); - A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustHaveHappenedOnceExactly(); } [Test] public async Task Endpoint_NoMatch_IsAnEmptyPage() { var gateway = A.Fake(); - _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); + _ = A.CallTo(() => gateway.FindOperationsAsync(A._, A._)).Returns([]); var (status, body) = await Get(gateway, "/api-operations?endpoint=GET%20/nope"); @@ -290,4 +291,32 @@ public async Task Groups_CountOperationsWithoutListingThem() body.GetProperty("groups")[0].GetProperty("operations").ValueKind.Should().Be(JsonValueKind.Null); body.GetProperty("note").ValueKind.Should().Be(JsonValueKind.Null); } + + [Test] + [Arguments("", 1)] + [Arguments("&include_deprecated=true", 2)] + public async Task Groups_CountDeprecatedOperationsOnlyWhenTheListingWould(string includeDeprecated, int clusterCount) + { + var gateway = A.Fake(); + _ = A.CallTo(() => gateway.ListOperationsAsync(A._, A._)).Returns([ + Operation, + Operation with { OperationId = "old", Deprecated = true }, + Operation with { OperationId = "gone", Group = "legacy", Deprecated = true } + ]); + + var (groupsStatus, groups) = await Get(gateway, $"/apis/elasticsearch/groups?version=9{includeDeprecated}"); + var (listStatus, list) = await Get(gateway, $"/api-operations?api=elasticsearch&group=cluster{includeDeprecated}"); + + groupsStatus.Should().Be(HttpStatusCode.OK); + listStatus.Should().Be(HttpStatusCode.OK); + var cluster = groups.GetProperty("groups").EnumerateArray().Single(g => g.GetProperty("name").GetString() == "cluster"); + cluster.GetProperty("count").GetInt32().Should().Be(clusterCount); + list.GetProperty("totalHits").GetInt64().Should().Be(clusterCount); + groups + .GetProperty("groups") + .EnumerateArray() + .Any(g => g.GetProperty("name").GetString() == "legacy") + .Should() + .Be(includeDeprecated != ""); + } } diff --git a/tests/Mcp.Remote.Tests/ApiGatewayTests.cs b/tests/Mcp.Remote.Tests/ApiGatewayTests.cs index 0fc4eb4f59..7eebd24a00 100644 --- a/tests/Mcp.Remote.Tests/ApiGatewayTests.cs +++ b/tests/Mcp.Remote.Tests/ApiGatewayTests.cs @@ -225,6 +225,23 @@ public async Task GetOperationAsync_OperationId_ListsLaterHitsAsOtherMatches() detail.OtherMatches.Select(o => o.OperationId).Should().Equal("search"); } + [Test] + public async Task FindOperationsAsync_OperationId_ReturnsEveryMatchWithItsDetailsFromOneQuery() + { + using var stub = ElasticsearchStub.Start(SearchCandidates); + var gateway = new ApiGateway(stub.Accessor, NullLogger.Instance); + + var matches = await gateway.FindOperationsAsync( + new ApiOperationLookup(null, new ApiOperationIdKey("get")), + TestContext.Current!.Execution.CancellationToken + ); + + matches.Select(m => m.Operation.OperationId).Should().Equal("get", "search"); + matches.Should().AllSatisfy(m => m.Versions.Should().NotBeNull()); + matches.Should().AllSatisfy(m => m.OtherMatches.Should().BeEmpty()); + stub.RequestCount.Should().Be(1); + } + [Test] public async Task GetOperationAsync_OperationIdInVersion_FiltersByApiTreeAndOperationId() { diff --git a/tests/Mcp.Remote.Tests/ElasticsearchStub.cs b/tests/Mcp.Remote.Tests/ElasticsearchStub.cs index a39cf3deb1..cb5775baad 100644 --- a/tests/Mcp.Remote.Tests/ElasticsearchStub.cs +++ b/tests/Mcp.Remote.Tests/ElasticsearchStub.cs @@ -29,6 +29,9 @@ private ElasticsearchStub(string response, int port, int statusCode) public Uri Uri { get; } public string LastRequestBody { get; private set; } = string.Empty; + /// How many requests the stub has answered. + public int RequestCount { get; private set; } + /// A client pointed at this stub, disposed with it. public ElasticsearchClientAccessor Accessor => _accessor ??= new( @@ -86,6 +89,7 @@ private async Task ServeAsync() : context.Request.InputStream; using (var reader = new StreamReader(body, Encoding.UTF8)) LastRequestBody = await reader.ReadToEndAsync(); + RequestCount++; var bytes = Encoding.UTF8.GetBytes(_response); context.Response.StatusCode = _statusCode; From eed1aa9d57a33ed3ffd2cae10f95270395ddc0a5 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 15:29:36 +0100 Subject: [PATCH 6/7] Check the view of an operations query in the service Every other rule of the operations collection lives in ApiReferenceService.QueryAsync; the view check was the only one in the HTTP handler, so it now sits with them and has a unit test. Co-Authored-By: Claude Opus 5.5 --- .../MappingsExtensions.cs | 38 +++++++++---------- .../ApiReference/ApiReferenceService.cs | 8 +++- .../ApiReferenceServiceTests.cs | 35 +++++++++++++++++ 3 files changed, 59 insertions(+), 22 deletions(-) create mode 100644 tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index 128ccc5e21..5d24e02eca 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -228,27 +228,25 @@ Cancel ctx [FromQuery(Name = "size")] int? pageSize, ApiReferenceService apiReference, Cancel ctx - ) => view is not (null or "basic" or "full") - ? Results.BadRequest(new ApiReferenceRejection("invalid_arguments", "view is 'basic' or 'full'.")) - : ToResult( - await apiReference.QueryAsync( - new ApiOperationQuery - { - Api = api, - Version = version, - Group = apiGroupName, - Q = query, - Endpoint = endpoint, - OperationId = operationId, - IncludeDeprecated = includeDeprecated ?? false, - Full = view == "full", - IncludeBody = includeBody ?? false, - Page = pageNumber ?? 1, - Size = pageSize ?? 10 - }, - ctx - ) + ) => ToResult( + await apiReference.QueryAsync( + new ApiOperationQuery + { + Api = api, + Version = version, + Group = apiGroupName, + Q = query, + Endpoint = endpoint, + OperationId = operationId, + IncludeDeprecated = includeDeprecated ?? false, + View = view, + IncludeBody = includeBody ?? false, + Page = pageNumber ?? 1, + Size = pageSize ?? 10 + }, + ctx ) + ) ); _ = operations.MapGet( "/{id}", diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index 925cab5058..59cc37e1d3 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -100,6 +100,8 @@ public async Task QueryAsync(ApiOperationQuery query, Cancell var lookups = new[] { query.Q, query.Endpoint, query.OperationId }.Count(v => !string.IsNullOrWhiteSpace(v)); if (lookups > 1) return new ApiReferenceRejection("invalid_arguments", "Pass at most one of q, endpoint or operation_id."); + if (query.View is not (null or "basic" or "full")) + return new ApiReferenceRejection("invalid_arguments", "view is 'basic' or 'full'."); var exact = !string.IsNullOrWhiteSpace(query.Endpoint) || !string.IsNullOrWhiteSpace(query.OperationId); if (query.Full && !exact) return new ApiReferenceRejection("invalid_arguments", "view=full needs endpoint or operation_id."); @@ -306,8 +308,10 @@ public sealed record ApiOperationQuery public string? Endpoint { get; init; } public string? OperationId { get; init; } public bool IncludeDeprecated { get; init; } - /// Adds each result's versions and fields; needs or . - public bool Full { get; init; } + /// basic (the default) or full; any other value is rejected. + public string? View { get; init; } + /// The full view adds each result's versions and fields; needs or . + public bool Full => View == "full"; /// Adds each result's body; needs . public bool IncludeBody { get; init; } public int Page { get; init; } = 1; diff --git a/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs new file mode 100644 index 0000000000..57477db676 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs @@ -0,0 +1,35 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using AwesomeAssertions; +using Elastic.Documentation.Search.ApiReference; +using FakeItEasy; + +namespace Elastic.Documentation.Api.Tests; + +public class ApiReferenceServiceTests +{ + [Test] + [Arguments("everything")] + [Arguments("FULL")] + [Arguments("")] + public async Task QueryAsync_UnknownView_RejectsTheQueryWithoutReadingTheIndex(string view) + { + var gateway = A.Fake(); + + var reply = await new ApiReferenceService(gateway).QueryAsync( + new ApiOperationQuery { OperationId = "cluster-health", View = view }, + TestContext.Current!.Execution.CancellationToken + ); + + (reply is ApiReferenceRejection rejected ? rejected.Message : null).Should().Be("view is 'basic' or 'full'."); + A.CallTo(gateway).MustNotHaveHappened(); + } + + [Test] + [Arguments(null, false)] + [Arguments("basic", false)] + [Arguments("full", true)] + public void Full_IsSetOnlyByTheFullView(string? view, bool full) => new ApiOperationQuery { View = view }.Full.Should().Be(full); +} From 846a2814e1811e59a5ebb0b9494846b708d0a1c7 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 17:19:53 +0100 Subject: [PATCH 7/7] Address every API operation inside its API Most operation ids and many routes exist in several APIs: elasticsearch and elasticsearch-serverless share 325 ids, kibana and kibana-serverless 724. A lookup across APIs had to pick one, in no defined order. Operations now live under /apis/{api}/operations, searched, looked up by endpoint or listed there, and read at /apis/{api}/operations/{operationId}. /api-operations, the {api}:{operationId} ids and the operation_id filter are gone. The MCP tools keep their optional api. Co-Authored-By: Claude Opus 5.5 --- docs/data/api.md | 23 +++-- .../MappingsExtensions.cs | 24 +++-- .../ApiReference/ApiReferenceService.cs | 73 +++++++------- .../ApiReference/IApiGateway.cs | 3 - .../ApiOperationsEndpointTests.cs | 95 +++++++++---------- .../ApiReferenceServiceTests.cs | 2 +- 6 files changed, 103 insertions(+), 117 deletions(-) diff --git a/docs/data/api.md b/docs/data/api.md index 4e0006f28e..ecdcafd8e8 100644 --- a/docs/data/api.md +++ b/docs/data/api.md @@ -18,11 +18,11 @@ navigation_title: REST API ## APIs and API operations -Two resources describe the REST APIs that API Explorer publishes: `apis` and `api-operations`. They answer the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md), and serve HTTP clients such as the Elastic CLI's `elastic docs api` commands. All requests are `GET` under `/docs/_api/v1`, and responses are camelCase JSON. +The `apis` resource describes the REST APIs that API Explorer publishes and, under each API, its operations. It answers the same lookups as the `search_api_operations`, `get_api_operation`, and `list_api_operations` tools of the [MCP server](mcp/index.md), and serves HTTP clients such as the Elastic CLI's `elastic docs api` commands. All requests are `GET` under `/docs/_api/v1`, and responses are camelCase JSON. -An operation's id is `{api}:{operationId}`, such as `elasticsearch:cluster-health`. Every operation in a response carries it as `id`. API keys never contain `:`, so an operation id after the first `:` may. +Every operation request names its API, such as `elasticsearch` or `kibana`. Many operation ids and routes exist in several APIs: `elasticsearch` and `elasticsearch-serverless` share most of theirs. A lookup across APIs would have to pick one, so there is none. The MCP tools still search across APIs when no API is given. -`api` is an API key such as `elasticsearch` or `kibana`. `version` is `main` or a major such as `9`, and needs `api`. Without `version`, a request reads the API's current version. +`version` is `main` or a major such as `9`. Without it, a request reads the API's current version. ### APIs @@ -32,25 +32,24 @@ An operation's id is `{api}:{operationId}`, such as `elasticsearch:cluster-healt | `/apis/{api}` | None | That API's key, title, landing page, and versions | | `/apis/{api}/groups` | `version`
`include_deprecated` (default `false`) | The API's `groups`, each with its name and operation count. Counts follow the same deprecated filter as a group listing. | -### API operations +### Operations of an API -`/api-operations` is one collection. It takes at most one of `q`, `endpoint`, or `operation_id`. Without any of them, it lists one API's operations and needs `api`. +`/apis/{api}/operations` takes at most one of `q` or `endpoint`. Without either, it lists the API's operations by path. | Query parameter | Meaning | |-----------------|---------| | `q` | Words, a route such as `GET /_cluster/health`, or a field path. A trailing dot, as in `retriever.`, lists child fields. Results come in relevance order with a `score` and the `matchedFields`. | -| `endpoint` | A request such as `GET /my-index/_search`, with or without the method. Results are the operations that serve it, best match first. | -| `operation_id` | An operation id without its API, such as `cluster-health`. Results are that id in every API, or in `api` only. | -| `api`, `version` | Scope to one API and version | -| `group` | Lists one group of the API. It doesn't combine with `q`, `endpoint`, or `operation_id`. | +| `endpoint` | A request such as `GET /my-index/_search`, with or without the method. Results are the operations that serve it, best route first. A route made only of parameters, such as `/{index}`, can serve several. | +| `version` | The API version | +| `group` | Lists one group. It doesn't combine with `q` or `endpoint`. | | `include_deprecated` | Include deprecated operations in a search or listing. The default is `false`. | -| `view` | `basic` (the default) or `full`. `full` adds each result's `versions` and `fields`, and needs `endpoint` or `operation_id`. | +| `view` | `basic` (the default) or `full`. `full` adds each result's `versions` and `fields`, and needs `endpoint`. | | `include_body` | Adds each result's `body`. It needs `view=full`. | | `page`, `size` | Page through a search or listing. `size` defaults to `10` and is at most `50`. | -The collection returns `totalHits` and `results`. Each result has its `operation`, plus the fields its filters add. A lookup that matches nothing returns an empty page, not `404`. +The response has `totalHits` and `results`. Each result has its `operation`, plus the fields its filters add. A lookup that matches nothing returns an empty page, not `404`. -`/api-operations/{id}` reads one operation by its id. It takes `version` and `include_body` (default `false`). It returns the `operation`, its `versions`, every documented field in `fields`, `bodyLength`, `otherMatches`, and `body` only when `include_body=true`. +`/apis/{api}/operations/{operationId}` reads one operation, such as `/apis/elasticsearch/operations/cluster-health`. It takes `version` and `include_body` (default `false`). It returns the `operation`, its `versions`, every documented field in `fields`, `bodyLength`, and `body` only when `include_body=true`. ### Errors diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index 5d24e02eca..2669804557 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -187,8 +187,9 @@ Cancel ctx return Results.Ok(response); }); - // Two resources: the APIs API Explorer publishes, and their operations, addressed as {api}:{operationId}. - // They answer the same lookups as the search_api_operations, get_api_operation and list_api_operations MCP tools. + // The APIs API Explorer publishes and, under each, its operations. An operation is always addressed inside its + // API: many operation ids and routes exist in several APIs (elasticsearch and elasticsearch-serverless share + // most), so a lookup across APIs could only guess. The MCP tools answer the same lookups. private static void MapApiOperations(IEndpointRouteBuilder group) { var apis = group.MapGroup("/apis"); @@ -210,17 +211,14 @@ private static void MapApiOperations(IEndpointRouteBuilder group) Cancel ctx ) => ToResult(await apiReference.ListGroupsAsync(api, version, includeDeprecated ?? false, ctx)) ); - - var operations = group.MapGroup("/api-operations"); - _ = operations.MapGet( - "/", + _ = apis.MapGet( + "/{api}/operations", async ( - [FromQuery(Name = "api")] string? api, + string api, [FromQuery(Name = "version")] string? version, [FromQuery(Name = "group")] string? apiGroupName, [FromQuery(Name = "q")] string? query, [FromQuery(Name = "endpoint")] string? endpoint, - [FromQuery(Name = "operation_id")] string? operationId, [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, [FromQuery(Name = "view")] string? view, [FromQuery(Name = "include_body")] bool? includeBody, @@ -237,7 +235,6 @@ await apiReference.QueryAsync( Group = apiGroupName, Q = query, Endpoint = endpoint, - OperationId = operationId, IncludeDeprecated = includeDeprecated ?? false, View = view, IncludeBody = includeBody ?? false, @@ -248,15 +245,16 @@ await apiReference.QueryAsync( ) ) ); - _ = operations.MapGet( - "/{id}", + _ = apis.MapGet( + "/{api}/operations/{operationId}", async ( - string id, + string api, + string operationId, [FromQuery(Name = "version")] string? version, [FromQuery(Name = "include_body")] bool? includeBody, ApiReferenceService apiReference, Cancel ctx - ) => ToResult(await apiReference.GetByIdAsync(id, version, includeBody ?? false, ctx)) + ) => ToResult(await apiReference.GetOperationAsync(api, operationId, version, includeBody ?? false, ctx)) ); } diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index 59cc37e1d3..15bcb005c1 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -89,35 +89,34 @@ CancellationToken ct } /// - /// Reads the operations collection: a search with , the operations behind an - /// or an (best match first), - /// or one API's operations by path when none of the three is set. + /// Reads one API's operations: a search with , the operations that serve an + /// (best route first), or a listing by path when neither is set. /// public async Task QueryAsync(ApiOperationQuery query, CancellationToken ct) { - if (VersionWithoutApi(query.Api, query.Version)) - return VersionNeedsApi; - var lookups = new[] { query.Q, query.Endpoint, query.OperationId }.Count(v => !string.IsNullOrWhiteSpace(v)); - if (lookups > 1) - return new ApiReferenceRejection("invalid_arguments", "Pass at most one of q, endpoint or operation_id."); + // Every lookup is inside one API, so an operation id or a route can never match in two of them. + if (ToScope(query.Api, query.Version) is not { } scope) + return new ApiReferenceRejection("invalid_arguments", "Pass an API key, such as 'elasticsearch'."); + var hasQuery = !string.IsNullOrWhiteSpace(query.Q); + var hasEndpoint = !string.IsNullOrWhiteSpace(query.Endpoint); + if (hasQuery && hasEndpoint) + return new ApiReferenceRejection("invalid_arguments", "Pass q or endpoint, not both."); if (query.View is not (null or "basic" or "full")) return new ApiReferenceRejection("invalid_arguments", "view is 'basic' or 'full'."); - var exact = !string.IsNullOrWhiteSpace(query.Endpoint) || !string.IsNullOrWhiteSpace(query.OperationId); - if (query.Full && !exact) - return new ApiReferenceRejection("invalid_arguments", "view=full needs endpoint or operation_id."); + if (query.Full && !hasEndpoint) + return new ApiReferenceRejection("invalid_arguments", "view=full needs endpoint."); if (query.IncludeBody && !query.Full) return new ApiReferenceRejection("invalid_arguments", "include_body needs view=full."); - if (!string.IsNullOrWhiteSpace(query.Group) && lookups > 0) - return new ApiReferenceRejection("invalid_arguments", "group filters a listing; pass it without q, endpoint or operation_id."); + if (!string.IsNullOrWhiteSpace(query.Group) && (hasQuery || hasEndpoint)) + return new ApiReferenceRejection("invalid_arguments", "group filters a listing; pass it without q or endpoint."); - var scope = ToScope(query.Api, query.Version); var page = Math.Max(1, query.Page); var size = Math.Clamp(query.Size, 1, MaxPageSize); - if (!string.IsNullOrWhiteSpace(query.Q)) + if (hasQuery) { var hits = await apiGateway.SearchOperationsAsync( - new ApiOperationSearch(query.Q, scope, query.IncludeDeprecated, page, size), + new ApiOperationSearch(query.Q!, scope, query.IncludeDeprecated, page, size), ct ); return new ApiOperationCollectionResponse @@ -132,12 +131,13 @@ .. hits.Hits.Select( }; } - if (exact) + if (hasEndpoint) { - ApiOperationKey key = string.IsNullOrWhiteSpace(query.Endpoint) - ? new ApiOperationIdKey(query.OperationId!.Trim()) - : new ApiEndpointKey(query.Endpoint.Trim()); - var matches = await apiGateway.FindOperationsAsync(new ApiOperationLookup(scope, key), ct); + // Within one API, a route made only of parameters, such as /{index}, can still serve several operations. + var matches = await apiGateway.FindOperationsAsync( + new ApiOperationLookup(scope, new ApiEndpointKey(query.Endpoint!.Trim())), + ct + ); return new ApiOperationCollectionResponse { TotalHits = matches.Count, @@ -145,8 +145,6 @@ .. hits.Hits.Select( }; } - if (scope is null) - return new ApiReferenceRejection("invalid_arguments", "Pass api to list operations, or one of q, endpoint or operation_id."); var operations = await apiGateway.ListOperationsAsync(scope, ct); if (operations.Count == 0) return ApiNotFound(scope); @@ -166,17 +164,19 @@ .. hits.Hits.Select( }; } - /// Reads one operation by its , {api}:{operationId}. - public Task GetByIdAsync(string id, string? version, bool includeBody, CancellationToken ct) - { - // API keys never contain ':', so the first one ends the key and the operation id may contain more. - var separator = id.IndexOf(':'); - return separator <= 0 || separator == id.Length - 1 + /// Reads one operation of one API by its operation id. + public Task GetOperationAsync( + string api, + string operationId, + string? version, + bool includeBody, + CancellationToken ct + ) => + string.IsNullOrWhiteSpace(api) ? Task.FromResult( - new ApiReferenceRejection("invalid_arguments", "An operation id looks like 'elasticsearch:cluster-health'.") + new ApiReferenceRejection("invalid_arguments", "Pass an API key, such as 'elasticsearch'.") ) - : GetAsync(id[..separator], id[(separator + 1)..], null, version, includeBody, ct); - } + : GetAsync(api, operationId, null, version, includeBody, ct); /// Reads one API by its key. public async Task GetApiAsync(string api, CancellationToken ct) @@ -298,7 +298,7 @@ public sealed record ApiOperationSearchResponse public required IReadOnlyList Results { get; init; } } -/// The filters of the operations collection. At most one of , or . +/// The filters of one API's operations. At most one of or . public sealed record ApiOperationQuery { public string? Api { get; init; } @@ -306,11 +306,10 @@ public sealed record ApiOperationQuery public string? Group { get; init; } public string? Q { get; init; } public string? Endpoint { get; init; } - public string? OperationId { get; init; } public bool IncludeDeprecated { get; init; } /// basic (the default) or full; any other value is rejected. public string? View { get; init; } - /// The full view adds each result's versions and fields; needs or . + /// The full view adds each result's versions and fields; needs . public bool Full => View == "full"; /// Adds each result's body; needs . public bool IncludeBody { get; init; } @@ -318,14 +317,14 @@ public sealed record ApiOperationQuery public int Size { get; init; } = 10; } -/// A page of the operations collection. +/// A page of one API's operations. public sealed record ApiOperationCollectionResponse { public required long TotalHits { get; init; } public required IReadOnlyList Results { get; init; } } -/// One operation in the collection. Search adds a score and the matched fields; the full view adds versions, fields and the body. +/// One operation in a page. Search adds a score and the matched fields; the full view adds versions, fields and the body. public sealed record ApiOperationItem { public required ApiOperationSummary Operation { get; init; } diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs index 0c1a4da8aa..2f0007b97e 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs @@ -54,9 +54,6 @@ public sealed record ApiOperationSummary public required string Path { get; init; } public required string OperationId { get; init; } - /// The operation's id across APIs, {api}:{operationId}, as the docs API addresses it. - public string Id => $"{Api}:{OperationId}"; - public string? Group { get; init; } public bool Deprecated { get; init; } diff --git a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs index 235513df1c..1e4dc73794 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs @@ -46,7 +46,7 @@ public static void DisposeSharedFactory() using var client = SharedFactory.Value.CreateClient(); using var response = await client.GetAsync($"/docs/_api/v1{pathAndQuery}", TestContext.Current!.Execution.CancellationToken); var json = await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken); - return (response.StatusCode, JsonElement.Parse(json)); + return (response.StatusCode, json.Length == 0 ? default : JsonElement.Parse(json)); } private static ApiOperationDetail Detail(string? body = null, params ApiOperationSummary[] otherMatches) => @@ -61,10 +61,11 @@ private static ApiOperationDetail Detail(string? body = null, params ApiOperatio Description = "Detail level" }; - private static readonly ApiOperationSummary KibanaOperation = Operation with { Api = "kibana", OperationId = "kibana-health" }; + // Another path to the same operation, so an endpoint lookup has more than one match inside one API. + private static readonly ApiOperationSummary IndexOperation = Operation with { OperationId = "indices-get", Path = "/{index}" }; - private static IEnumerable Ids(JsonElement body) => - body.GetProperty("results").EnumerateArray().Select(r => r.GetProperty("operation").GetProperty("id").GetString()); + private static IEnumerable OperationIds(JsonElement body) => + body.GetProperty("results").EnumerateArray().Select(r => r.GetProperty("operation").GetProperty("operationId").GetString()); [Test] public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() @@ -76,10 +77,7 @@ public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() .Invokes((ApiOperationSearch search, CancellationToken _) => received = search) .Returns(new ApiOperationPage(1, [new ApiOperationHit(Operation, 2, [Field])])); - var (status, body) = await Get( - gateway, - "/api-operations?q=health&api=%20Elasticsearch%20&version=9&include_deprecated=true&size=500" - ); + var (status, body) = await Get(gateway, "/apis/Elasticsearch/operations?q=health&version=9&include_deprecated=true&size=500"); status.Should().Be(HttpStatusCode.OK); received.Should().Be( @@ -87,21 +85,19 @@ public async Task Search_PassesTheNormalizedScopeAndClampedPageSize() ); body.GetProperty("totalHits").GetInt64().Should().Be(1); var hit = body.GetProperty("results")[0]; - hit.GetProperty("operation").GetProperty("id").GetString().Should().Be("elasticsearch:cluster-health"); + hit.GetProperty("operation").GetProperty("operationId").GetString().Should().Be("cluster-health"); hit.GetProperty("score").GetSingle().Should().Be(2); hit.GetProperty("matchedFields")[0].GetProperty("path").GetString().Should().Be("level"); } [Test] - [Arguments("/api-operations?q=health&version=9", "version needs api: pass the API key the version belongs to.")] - [Arguments("/api-operations?q=health&endpoint=GET%20/x", "Pass at most one of q, endpoint or operation_id.")] - [Arguments("/api-operations?q=health&view=full", "view=full needs endpoint or operation_id.")] - [Arguments("/api-operations?operation_id=x&include_body=true", "include_body needs view=full.")] - [Arguments("/api-operations?api=elasticsearch&group=cluster&q=health", "group filters a listing; pass it without q, endpoint or operation_id.")] - [Arguments("/api-operations", "Pass api to list operations, or one of q, endpoint or operation_id.")] - [Arguments("/api-operations?operation_id=x&view=everything", "view is 'basic' or 'full'.")] - [Arguments("/api-operations/cluster-health", "An operation id looks like 'elasticsearch:cluster-health'.")] - [Arguments("/api-operations/elasticsearch:", "An operation id looks like 'elasticsearch:cluster-health'.")] + [Arguments("/apis/elasticsearch/operations?q=health&endpoint=GET%20/x", "Pass q or endpoint, not both.")] + [Arguments("/apis/elasticsearch/operations?q=health&view=full", "view=full needs endpoint.")] + [Arguments("/apis/elasticsearch/operations?endpoint=GET%20/x&include_body=true", "include_body needs view=full.")] + [Arguments("/apis/elasticsearch/operations?group=cluster&q=health", "group filters a listing; pass it without q or endpoint.")] + [Arguments("/apis/elasticsearch/operations?endpoint=GET%20/x&view=everything", "view is 'basic' or 'full'.")] + [Arguments("/apis/%20/operations?q=health", "Pass an API key, such as 'elasticsearch'.")] + [Arguments("/apis/%20/operations/cluster-health", "Pass an API key, such as 'elasticsearch'.")] [Arguments("/apis/%20/groups", "Pass an API key, such as 'elasticsearch'.")] public async Task InvalidArguments_AreABadRequestWithoutQueryingTheIndex(string pathAndQuery, string message) { @@ -116,51 +112,48 @@ public async Task InvalidArguments_AreABadRequestWithoutQueryingTheIndex(string } [Test] - public async Task Endpoint_FullView_ReturnsEveryMatchWithItsFieldsFromOneLookup() + [Arguments("/api-operations?q=health")] + [Arguments("/api-operations/elasticsearch:cluster-health")] + public async Task OperationsOutsideAnApi_AreNotAnEndpoint(string pathAndQuery) + { + var gateway = A.Fake(); + + var (status, _) = await Get(gateway, pathAndQuery); + + status.Should().Be(HttpStatusCode.NotFound); + A.CallTo(gateway).MustNotHaveHappened(); + } + + [Test] + public async Task Endpoint_FullView_ReturnsEveryMatchInTheApiWithItsFieldsFromOneLookup() { List received = []; var gateway = A.Fake(); _ = A .CallTo(() => gateway.FindOperationsAsync(A._, A._)) .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) - .Returns([Detail("Body"), Detail() with { Operation = KibanaOperation }]); + .Returns([Detail("Body"), Detail() with { Operation = IndexOperation }]); - var (status, body) = await Get(gateway, "/api-operations?endpoint=GET%20/my-index/_search&view=full&include_body=true"); + var (status, body) = await Get(gateway, "/apis/elasticsearch/operations?endpoint=GET%20/my-index&view=full&include_body=true"); status.Should().Be(HttpStatusCode.OK); - Ids(body).Should().Equal("elasticsearch:cluster-health", "kibana:kibana-health"); + OperationIds(body).Should().Equal("cluster-health", "indices-get"); var best = body.GetProperty("results")[0]; best.GetProperty("fields")[0].GetProperty("path").GetString().Should().Be("level"); best.GetProperty("body").GetString().Should().Be("Body"); body.GetProperty("results")[1].GetProperty("fields").GetArrayLength().Should().Be(1); - ApiOperationKey endpointKey = new ApiEndpointKey("GET /my-index/_search"); - received.Should().Equal(new ApiOperationLookup(null, endpointKey)); + ApiOperationKey endpointKey = new ApiEndpointKey("GET /my-index"); + received.Should().Equal(new ApiOperationLookup(new ApiScope("elasticsearch", null), endpointKey)); A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustNotHaveHappened(); } - [Test] - public async Task OperationId_BasicView_ListsTheSameIdInEveryApiWithoutFields() - { - var gateway = A.Fake(); - _ = A.CallTo(() => gateway.FindOperationsAsync(A._, A._)).Returns([ - Detail(), - Detail() with { Operation = KibanaOperation } - ]); - - var (status, body) = await Get(gateway, "/api-operations?operation_id=cluster-health"); - - status.Should().Be(HttpStatusCode.OK); - Ids(body).Should().Equal("elasticsearch:cluster-health", "kibana:kibana-health"); - body.GetProperty("results")[0].GetProperty("fields").ValueKind.Should().Be(JsonValueKind.Null); - } - [Test] public async Task Endpoint_NoMatch_IsAnEmptyPage() { var gateway = A.Fake(); _ = A.CallTo(() => gateway.FindOperationsAsync(A._, A._)).Returns([]); - var (status, body) = await Get(gateway, "/api-operations?endpoint=GET%20/nope"); + var (status, body) = await Get(gateway, "/apis/elasticsearch/operations?endpoint=GET%20/nope"); status.Should().Be(HttpStatusCode.OK); body.GetProperty("totalHits").GetInt64().Should().Be(0); @@ -179,16 +172,16 @@ public async Task Listing_FiltersByGroupHidesDeprecatedSortsByPathAndPages() Operation with { OperationId = "s", Path = "/_search", Group = "search" } ]); - var (status, body) = await Get(gateway, "/api-operations?api=elasticsearch&group=CLUSTER&size=2&page=2"); + var (status, body) = await Get(gateway, "/apis/elasticsearch/operations?group=CLUSTER&size=2&page=2"); status.Should().Be(HttpStatusCode.OK); body.GetProperty("totalHits").GetInt64().Should().Be(3); - Ids(body).Should().Equal("elasticsearch:c"); + OperationIds(body).Should().Equal("c"); } [Test] - [Arguments("/api-operations?api=nope", "api_not_found")] - [Arguments("/api-operations?api=elasticsearch&group=nope", "group_not_found")] + [Arguments("/apis/nope/operations", "api_not_found")] + [Arguments("/apis/elasticsearch/operations?group=nope", "group_not_found")] [Arguments("/apis/nope/groups", "api_not_found")] public async Task Listing_UnknownApiOrGroup_IsNotFound(string pathAndQuery, string errorType) { @@ -204,7 +197,7 @@ public async Task Listing_UnknownApiOrGroup_IsNotFound(string pathAndQuery, stri } [Test] - public async Task Operation_ById_SplitsAtTheFirstColonAndReturnsTheBodyOnlyWhenAsked() + public async Task Operation_ReadsItInsideItsApiAndReturnsTheBodyOnlyWhenAsked() { List received = []; var gateway = A.Fake(); @@ -213,11 +206,11 @@ public async Task Operation_ById_SplitsAtTheFirstColonAndReturnsTheBodyOnlyWhenA .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup)) .Returns(Detail("Full body")); - var (withoutBody, withoutJson) = await Get(gateway, "/api-operations/elasticsearch:cluster-health"); - var (withBody, withJson) = await Get(gateway, "/api-operations/kibana%3Aa%3Ab?version=9&include_body=true"); + var (withoutBody, withoutJson) = await Get(gateway, "/apis/elasticsearch/operations/cluster-health"); + var (withBody, withJson) = await Get(gateway, "/apis/Kibana/operations/a%3Ab?version=9&include_body=true"); withoutBody.Should().Be(HttpStatusCode.OK); - withoutJson.GetProperty("operation").GetProperty("id").GetString().Should().Be("elasticsearch:cluster-health"); + withoutJson.GetProperty("operation").GetProperty("operationId").GetString().Should().Be("cluster-health"); withoutJson.GetProperty("body").ValueKind.Should().Be(JsonValueKind.Null); withoutJson.GetProperty("bodyLength").GetInt32().Should().Be(9); withBody.Should().Be(HttpStatusCode.OK); @@ -236,7 +229,7 @@ public async Task Operation_UnknownId_IsNotFound() var gateway = A.Fake(); _ = A.CallTo(() => gateway.GetOperationAsync(A._, A._)).Returns((ApiOperationDetail?)null); - var (status, body) = await Get(gateway, "/api-operations/elasticsearch:nope"); + var (status, body) = await Get(gateway, "/apis/elasticsearch/operations/nope"); status.Should().Be(HttpStatusCode.NotFound); body.GetProperty("errorType").GetString().Should().Be("operation_not_found"); @@ -305,7 +298,7 @@ public async Task Groups_CountDeprecatedOperationsOnlyWhenTheListingWould(string ]); var (groupsStatus, groups) = await Get(gateway, $"/apis/elasticsearch/groups?version=9{includeDeprecated}"); - var (listStatus, list) = await Get(gateway, $"/api-operations?api=elasticsearch&group=cluster{includeDeprecated}"); + var (listStatus, list) = await Get(gateway, $"/apis/elasticsearch/operations?group=cluster{includeDeprecated}"); groupsStatus.Should().Be(HttpStatusCode.OK); listStatus.Should().Be(HttpStatusCode.OK); diff --git a/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs index 57477db676..61a1531628 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs @@ -19,7 +19,7 @@ public async Task QueryAsync_UnknownView_RejectsTheQueryWithoutReadingTheIndex(s var gateway = A.Fake(); var reply = await new ApiReferenceService(gateway).QueryAsync( - new ApiOperationQuery { OperationId = "cluster-health", View = view }, + new ApiOperationQuery { Api = "elasticsearch", Endpoint = "GET /_cluster/health", View = view }, TestContext.Current!.Execution.CancellationToken );