Coming soon ChenAIle — agentic microservices: agents, AI tool calls, machine learning and a metrics-driven rules engine Learn more →

Polymorphic contracts

An operation is polymorphic when what it takes depends on the request: a workflow’s processById takes a different payload for each event, a query a different search request for each query name, and a body with a "type" field can be any subclass of a base class. Since 2.1.37 Chenile describes such an operation once, as a list of variants, and everything else reads that list:

  • the chenile-highway types each request and records its variant;
  • the security interceptor enforces each variant’s authorities;
  • MCP publishes one tool per variant;
  • OpenAPI publishes one path per variant (or a oneOf body);
  • the service registry stores the variants with their JSON Schemas and serves an OpenAPI document for the whole system.

See it animated in How it works · Polymorphism. The design is ADR 0001 in chenile-core/docs/adr.

Every operation has a contract

Polymorphic or not, every operation has a contract name and a description, resolved at startup:

  Annotation JSON service definition Default
Contract name @ChenileOperation(contractName = "…") "contractName" <serviceId>_<operationName>
Description @ChenileOperation(description = "…") "description" the service’s description, then generated text
Service description @ChenileController(description = "…") top-level "description" —

@ChenileOperation may be put on an HTTP controller method for these two attributes; there it creates no extra operation. The contract name is the MCP tool name and the OpenAPI operationId; the description is the tool description and the OpenAPI summary. @ChenileMCP only marks a service or operation for MCP.

@PostMapping("/orders")
@ChenileMCP
@ChenileOperation(contractName = "orderCreate", description = "Create an order")
public ResponseEntity<GenericResponse<Order>> create(HttpServletRequest request, @RequestBody Order order) {
    return process(request, order);
}

Making an operation polymorphic

A ChenilePolymorphProvider (package org.chenile.core.polymorph) lists the variants:

public interface ChenilePolymorphProvider {
    List<ChenilePolymorphVariant> getVariants(ChenileServiceDefinition service, OperationDefinition operation);
    default String variantName(OperationDefinition operation, String suffix) { … }   // <contractName>_<suffix>
    default ChenilePolymorphVariant resolveVariant(ChenileExchange exchange, OperationDefinition operation) { return null; }
}

There are two ways to attach one.

1. Let the body type selector describe what it types (preferred)

If the operation already has a body type selector, implement ChenilePolymorphProvider on it. chenile-core finds it with no annotation, and the bean that types each request is the bean that describes the contract, so they cannot disagree.

public class ShippingBodyTypeSelector implements Command<ChenileExchange>, ChenilePolymorphProvider {
    private final Map<String, Class<?>> types = Map.of("air", AirShipment.class, "sea", SeaShipment.class);

    @Override
    public void execute(ChenileExchange exchange) {
        Class<?> type = types.get(exchange.getHeader("mode", String.class));
        if (type != null) exchange.setBodyType(TransformationClassSelector.convertClassToTypeReference(type));
    }

    @Override
    public List<ChenilePolymorphVariant> getVariants(ChenileServiceDefinition service, OperationDefinition op) {
        return types.entrySet().stream().map(e -> new ChenilePolymorphVariant(
                variantName(op, e.getKey()),                    // shipments_ship_air
                "Ship by " + e.getKey(),
                Map.<String, Type>of("shipment", e.getValue()), // the BODY parameter's type
                Map.of(), Map.of(),
                Map.of("mode", e.getKey()),                     // selected by the "mode" path variable
                null,
                List.of("shipping." + e.getKey())))             // authorities
            .toList();
    }
}

If an operation has several selectors, at most one of them may list variants (otherwise startup fails with E530).

2. Name an explicit provider

When the variants do not come from a selector (queries are the example: the request type is always the same, only the contract differs per query), name a provider bean:

@ChenilePolymorph("queryPolymorph")          // JSON: "polymorph": "queryPolymorph"

An explicit provider wins over a selector.

What a variant says

ChenilePolymorphVariant is a record:

Component Meaning
name The complete name, used unchanged everywhere. Build it with variantName(op, suffix) or return your own.
description Defaults to the operation’s description when blank.
parameterTypes java.lang.reflect.Type per parameter, usually the BODY parameter’s payload type.
parameterSchemas A JSON schema per parameter, instead of a type (not both for one parameter).
parameterDescriptions Descriptions per parameter.
fixedParameterValues The values that select the variant: path variables or headers, for example eventID = submit.
bodyDiscriminator For subclass polymorphism: a top-level body field and value, for example type = car.
authorities What a caller needs for this variant. Empty means the operation’s own @SecurityConfig applies.

At startup, a variant without a name (E531), a duplicate name (E532) and two variants selected by the same values (E533) fail the application.

At runtime

The typing step (TransformationClassSelector) runs these, in order, for a polymorphic operation:

  1. Variant. The provider’s resolveVariant may answer; otherwise a variant matches when all its fixed values equal the request’s path variables and headers and its body discriminator (if any) equals the body’s top-level field. The body field is read with a streaming parser that stops at the field. The variant with the most matching values wins; a tie fails the request (E534); no match leaves it unset. The result is exchange.getPolymorphVariant().
  2. Body type. The body type selector sets the payload type. If it sets none, the operation’s default type is used, unless chenile.transform.selector-fallback=false.

Then the transformers convert the body, and the operation’s interceptors run. With @SecurityConfig on the operation, SecurityConfigServiceImpl guards the request with the variant’s authorities first, then @SecurityConfig(authorities), then its authoritiesSupplier. A deployable-wide pre-processor runs before the typing step and cannot see the variant.

Workflows

StmBodyTypeSelector lists one variant per event whose payload type it knows: named <contractName>_<eventId>, selected by eventID, described by the transition’s meta-description, and guarded by the event’s meta-acls:

<event-information eventId="submit" meta-acls="order.submit,order.admin"/>

Put a plain @SecurityConfig on processById. To require <service bean name>_<eventId> (lower case) for events without meta-acls, call setDefaultAclRequired(true) on the selector bean.

This replaces StmAuthoritiesBuilder, ProcessIdPolymorph and workflow-service’s ChenileOpenApiConfiguration, removed in 2.1.37.

Queries

QueryPolymorph (chenile-query-service) is the explicit provider of POST /q/{queryName} (contract querySearch) and of the MCP query controller (mcpQuerySearch). Each query becomes a variant with its filter, sort and paging schema and its acls as authorities. Query definitions can differ per tenant, so resolveVariant checks each request against the current tenant’s definition. It replaces the queryAuthorities bean.

Subclasses

SubclassBodyTypeSelector lists one variant per subclass registered in SubclassRegistry for the operation’s input type, selected by the body’s type field. Register subclasses before startup completes (in a @Bean method or @PostConstruct); later registrations are not published.

Where the contract appears

Consumer What it publishes
MCP (@ChenileMCP) One tool per variant, named by the variant. Every caller sees every tool; authorities are enforced on each call.
OpenAPI (chenile-http, automatic) operationId/summary from the contract; one path per variant selected by path variables; a oneOf body (with a discriminator for body fields) and allowed header values for the others; x-chenile-authorities. An expanded path that collides with an existing operation fails startup (E535).
Service registry contractName, request and response JSON Schemas, variants and shared schemas per service. GET /serviceregistry/openapi serves the whole system, GET /serviceregistry/{serviceId}/openapi one service.

All schemas come from ChenileJsonSchemaGenerator (JSON Schema Draft 2020-12, victools 5).

Upgrading from 2.1.36

  • Import ChenilePolymorph, ChenilePolymorphProvider and ChenilePolymorphVariant from org.chenile.core.polymorph instead of org.chenile.mcp.model.
  • nameSuffix is now name, the complete name: build it with variantName(operation, suffix). Parameter types are java.lang.reflect.Type (pass MyPayload.class or typeReference.getType()).
  • Replace @ChenileMCP(name = …, description = …) with @ChenileMCP plus @ChenileOperation(contractName = …, description = …).
  • Workflows: drop the <svc>EventAuthoritiesSupplier and <svc>ProcessIdPolymorph beans and @ChenilePolymorph("<svc>ProcessIdPolymorph"); use @SecurityConfig without a supplier.
  • Registry databases not managed by Hibernate need the new columns shared_schemas, contract_name, request_schema, response_schema and variant_definitions.