diff --git a/docs/data/api.md b/docs/data/api.md
index 3d72859a75..ecdcafd8e8 100644
--- a/docs/data/api.md
+++ b/docs/data/api.md
@@ -14,6 +14,46 @@ 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 |
+| APIs and API operations | Search, read, and list the REST API operations that API Explorer publishes |
+
+## APIs and API operations
+
+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.
+
+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.
+
+`version` is `main` or a major such as `9`. Without it, a request reads the API's current version.
+
+### APIs
+
+| Request | Query parameters | Returns |
+|---------|------------------|---------|
+| `/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`
`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. |
+
+### Operations of an 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 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`. |
+| `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 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`.
+
+`/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
+
+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 9d77f72296..2669804557 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);
+ MapApiOperations(group);
}
private static void MapAskAiEndpoint(IEndpointRouteBuilder group)
@@ -185,6 +187,89 @@ Cancel ctx
return Results.Ok(response);
});
+ // 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");
+ _ = apis.MapGet(
+ "/",
+ 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,
+ [FromQuery(Name = "include_deprecated")] bool? includeDeprecated,
+ ApiReferenceService apiReference,
+ Cancel ctx
+ ) => ToResult(await apiReference.ListGroupsAsync(api, version, includeDeprecated ?? false, ctx))
+ );
+ _ = apis.MapGet(
+ "/{api}/operations",
+ async (
+ string api,
+ [FromQuery(Name = "version")] string? version,
+ [FromQuery(Name = "group")] string? apiGroupName,
+ [FromQuery(Name = "q")] string? query,
+ [FromQuery(Name = "endpoint")] string? endpoint,
+ [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.QueryAsync(
+ new ApiOperationQuery
+ {
+ Api = api,
+ Version = version,
+ Group = apiGroupName,
+ Q = query,
+ Endpoint = endpoint,
+ IncludeDeprecated = includeDeprecated ?? false,
+ View = view,
+ IncludeBody = includeBody ?? false,
+ Page = pageNumber ?? 1,
+ Size = pageSize ?? 10
+ },
+ ctx
+ )
+ )
+ );
+ _ = apis.MapGet(
+ "/{api}/operations/{operationId}",
+ async (
+ string api,
+ string operationId,
+ [FromQuery(Name = "version")] string? version,
+ [FromQuery(Name = "include_body")] bool? includeBody,
+ ApiReferenceService apiReference,
+ Cancel ctx
+ ) => ToResult(await apiReference.GetOperationAsync(api, operationId, version, includeBody ?? false, ctx))
+ );
+ }
+
+ private static IResult ToResult(ApiReferenceReply reply) => reply switch
+ {
+ ApiOperationSearchResponse 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),
+ 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..6e51fafd17 100644
--- a/src/api/Elastic.Documentation.Api/SerializationContext.cs
+++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs
@@ -40,5 +40,12 @@ 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.ApiOperationCollectionResponse))]
+[JsonSerializable(typeof(Search.ApiReference.ApiSummary))]
+[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..ebed0fef3d 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))]
@@ -248,6 +192,7 @@ public sealed record ApiOperationListItemDto
[JsonSerializable(typeof(ApiOperationSearchResponse))]
[JsonSerializable(typeof(ApiOperationResponse))]
[JsonSerializable(typeof(ApiListResponse))]
+[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 95d9f43a63..65375408cf 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,25 @@ 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),
+ 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/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 93%
rename from src/api/Elastic.Documentation.Mcp.Remote/Gateways/ApiGateway.cs
rename to src/services/search/Elastic.Documentation.Search/ApiReference/ApiGateway.cs
index b9be653819..4dd040eb84 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
@@ -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
new file mode 100644
index 0000000000..15bcb005c1
--- /dev/null
+++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs
@@ -0,0 +1,383 @@
+// 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,
+ ApiOperationCollectionResponse,
+ ApiOperationResponse,
+ ApiSummary,
+ 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 an operation id or an 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
+ };
+ }
+
+ ///
+ /// 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)
+ {
+ // 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'.");
+ 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) && (hasQuery || hasEndpoint))
+ return new ApiReferenceRejection("invalid_arguments", "group filters a listing; pass it without q or endpoint.");
+
+ var page = Math.Max(1, query.Page);
+ var size = Math.Clamp(query.Size, 1, MaxPageSize);
+
+ if (hasQuery)
+ {
+ 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 }
+ )
+ ]
+ };
+ }
+
+ if (hasEndpoint)
+ {
+ // 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,
+ Results = [.. matches.Select(m => ToItem(m.Operation, query.Full ? m : null, query.IncludeBody))]
+ };
+ }
+
+ 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))
+ {
+ 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 })]
+ };
+ }
+
+ /// 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", "Pass an API key, such as 'elasticsearch'.")
+ )
+ : GetAsync(api, operationId, 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. 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)
+ {
+ 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.Where(o => includeDeprecated || !o.Deprecated)], 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)
+ {
+ 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 ? ApiNotFound(scope) : GroupOperations(scope, operations, 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)
+ .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 = !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 || groupsOnly
+ ? 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; }
+}
+
+/// The filters of one API's operations. 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 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 .
+ public bool Full => View == "full";
+ /// 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 one API's operations.
+public sealed record ApiOperationCollectionResponse
+{
+ public required long TotalHits { get; init; }
+ public required IReadOnlyList Results { get; init; }
+}
+
+/// 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; }
+ 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.
+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 92%
rename from src/api/Elastic.Documentation.Mcp.Remote/Gateways/IApiGateway.cs
rename to src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs
index 47615ef841..2f0007b97e 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
@@ -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);
@@ -50,6 +53,7 @@ public sealed record ApiOperationSummary
public required string Method { get; init; }
public required string Path { get; init; }
public required string OperationId { get; init; }
+
public string? Group { get; init; }
public bool Deprecated { get; init; }
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/ApiOperationsEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs
new file mode 100644
index 0000000000..1e4dc73794
--- /dev/null
+++ b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs
@@ -0,0 +1,315 @@
+// 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(ApiOperationsEndpointTests))]
+public class ApiOperationsEndpointTests
+{
+ 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{pathAndQuery}", TestContext.Current!.Execution.CancellationToken);
+ var json = await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken);
+ return (response.StatusCode, json.Length == 0 ? default : JsonElement.Parse(json));
+ }
+
+ private static ApiOperationDetail Detail(string? body = null, params ApiOperationSummary[] 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"
+ };
+
+ // 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 OperationIds(JsonElement body) =>
+ body.GetProperty("results").EnumerateArray().Select(r => r.GetProperty("operation").GetProperty("operationId").GetString());
+
+ [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, 2, [Field])]));
+
+ 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(
+ new ApiOperationSearch("health", new ApiScope("elasticsearch", "9"), true, 1, ApiReferenceService.MaxPageSize)
+ );
+ body.GetProperty("totalHits").GetInt64().Should().Be(1);
+ var hit = body.GetProperty("results")[0];
+ 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("/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)
+ {
+ var gateway = A.Fake();
+
+ 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("/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 = IndexOperation }]);
+
+ var (status, body) = await Get(gateway, "/apis/elasticsearch/operations?endpoint=GET%20/my-index&view=full&include_body=true");
+
+ status.Should().Be(HttpStatusCode.OK);
+ 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");
+ received.Should().Equal(new ApiOperationLookup(new ApiScope("elasticsearch", null), endpointKey));
+ A.CallTo(() => gateway.GetOperationAsync(A._, A._)).MustNotHaveHappened();
+ }
+
+ [Test]
+ public async Task Endpoint_NoMatch_IsAnEmptyPage()
+ {
+ var gateway = A.Fake();
+ _ = A.CallTo(() => gateway.FindOperationsAsync(A._, A._)).Returns([]);
+
+ 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);
+ body.GetProperty("results").GetArrayLength().Should().Be(0);
+ }
+
+ [Test]
+ 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, "/apis/elasticsearch/operations?group=CLUSTER&size=2&page=2");
+
+ status.Should().Be(HttpStatusCode.OK);
+ body.GetProperty("totalHits").GetInt64().Should().Be(3);
+ OperationIds(body).Should().Equal("c");
+ }
+
+ [Test]
+ [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)
+ {
+ 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_ReadsItInsideItsApiAndReturnsTheBodyOnlyWhenAsked()
+ {
+ List received = [];
+ var gateway = A.Fake();
+ _ = A
+ .CallTo(() => gateway.GetOperationAsync(A._, A._))
+ .Invokes((ApiOperationLookup lookup, CancellationToken _) => received.Add(lookup))
+ .Returns(Detail("Full body"));
+
+ 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("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);
+ withJson.GetProperty("body").GetString().Should().Be("Full body");
+ 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]
+ 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, "/apis/elasticsearch/operations/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.");
+ }
+
+ private static readonly ApiSummary Elasticsearch = new()
+ {
+ Key = "elasticsearch",
+ Title = "Elasticsearch API",
+ Url = "/docs/api/doc/elasticsearch",
+ Versions = ["9"]
+ };
+
+ [Test]
+ public async Task Apis_ListsEveryApiAndReadsOneByKey()
+ {
+ var gateway = A.Fake();
+ _ = 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_CountOperationsWithoutListingThem()
+ {
+ var gateway = A.Fake();
+ _ = 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, "/apis/elasticsearch/groups?version=9");
+
+ 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);
+ }
+
+ [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, $"/apis/elasticsearch/operations?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/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiReferenceServiceTests.cs
new file mode 100644
index 0000000000..61a1531628
--- /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 { Api = "elasticsearch", Endpoint = "GET /_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);
+}
diff --git a/tests/Mcp.Remote.Tests/ApiGatewayTests.cs b/tests/Mcp.Remote.Tests/ApiGatewayTests.cs
index dfa5abeb97..7eebd24a00 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;
@@ -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/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..bb534e9f18 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,11 +73,11 @@ 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);
- 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();
}
@@ -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);
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;