Skip to content

🧠 API Designer Agent Specification

🎯 Purpose

The API Designer Agent is responsible for generating explicit, versioned, and contract-driven APIs for every service in the ConnectSoft ecosystem.

It translates a service’s:

  • 🧩 Use cases
  • βš™οΈ Application service methods
  • 🧱 Domain inputs/outputs
  • πŸ§ͺ Validation rules
    into a well-documented API surface, available in both machine-readable specs (OpenAPI, gRPC, AsyncAPI) and developer-friendly formats.

🧠 Why This Agent Exists

At ConnectSoft scale, with thousands of microservices and autonomous agents, a uniform, observable, and contract-first API strategy is mandatory.

Without it:

  • Services become invisible and unreliable
  • Agents can't integrate safely or reuse capabilities
  • API drift and undocumented endpoints erode trust
  • Observability and monitoring are inconsistent
  • Clients, SDKs, gateways, and tests can't auto-generate correctly

With this agent:

  • Every service has a discoverable, validated, and versioned API surface
  • Downstream systems (SDK generators, gateways, adapters, security scanners, tests) can operate autonomously
  • Every endpoint is secure, traceable, and governed

πŸš€ What It Enables

Feature Enabled By
OpenAPI-first service generation βœ… REST interface design at contract level
gRPC/Protobuf-first microservices βœ… Strong typing for internal agent calls
AsyncAPI contract generation βœ… Event subscription interfaces
Developer portal auto-sync βœ… Markdown + JSON contracts
API Gateway mapping βœ… Route-to-service registration
CI/CD validation pipelines βœ… Schema diffing + breaking change detection
Observability by design βœ… Endpoint-level tracing and span hints
Auto-generated SDKs βœ… Contract artifacts for TypeScript, C#, Python, etc.

🧬 Types of APIs It Designs

Protocol Purpose
REST (OpenAPI) External service access (most common)
gRPC (proto) Internal service-to-service communication
AsyncAPI (JSON/YAML) Event-driven input/output declarations
HTTP RPC / Hybrid (optional) Lightweight query endpoints for UIs
GraphQL (future extension) Read-heavy, client-defined schemas (if needed)

πŸ“œ Example Service Scenario

For a service BillingService that supports:

  • CreateInvoice
  • ApplyDiscount
  • SendReminder

The API Designer Agent will generate:

  • openapi.yaml with:
    • POST /invoices
    • POST /invoices/{id}/apply-discount
    • POST /reminders/send
  • Schema for InvoiceDto, DiscountRequest, ReminderRequest
  • Version tags (v1), security scheme (OAuth2), trace metadata

🧭 Key Design Principles

Principle Enforced
Contract-First βœ… Generate API before implementation
Clean Separation βœ… Input/Output = DTOs, not entities
Observability-First βœ… Span injection + trace_id required
Secure by Default βœ… Auth, rate limits, CORS injected by policy
Versioned APIs βœ… v1, v2, etc. with changelogs
Self-Documenting βœ… Markdown + OpenAPI + diagrams emitted

🧠 Position in the Agent Ecosystem

flowchart TD
    ApplicationArchitect -->|use-cases.yaml| APIDesigner
    DomainModeler -->|DTO suggestions| APIDesigner
    EventDrivenArchitect -->|event input bindings| APIDesigner

    APIDesigner --> AdapterGenerator
    APIDesigner --> APIGatewayConfigurator
    APIDesigner --> DeveloperPortal
    APIDesigner --> TestGenerator
Hold "Alt" / "Option" to enable pan & zoom

πŸ›οΈ Scope of Influence

The API Designer Agent governs all aspects of a service’s external and internal API surface.
This includes:

  • Interface boundaries
  • Route structure
  • Request/response modeling
  • Validation metadata
  • Security annotations
  • Versioning
  • API documentation and lifecycle

It does not generate implementation logic β€” only designs the contract.


πŸ“š What It Owns

πŸ“˜ 1. API Surface Design

API Type Includes
REST (OpenAPI) Path, method, parameters, headers, request/response schemas
gRPC (Protobuf) Service/method signatures, message types
AsyncAPI (optional) Event topic specs, payload contracts
Metadata Tags, summaries, descriptions, usage notes

πŸ” 2. Contract Metadata and Non-Functional Aspects

Concern Owned?
Security Schemes βœ… OAuth2, API key, roles, scopes
Rate Limiting βœ… Optional per endpoint (via annotation)
CORS Configuration βœ… Policies for cross-origin access
Observability Hooks βœ… Requires span emission per endpoint
Validation Contracts βœ… Required fields, schema references, data types

πŸ“¦ 3. Schema Definitions

Type Included
Input DTOs Generated from use case commands
Output DTOs Aligned with aggregate return types
Reusable Components Money, DateRange, UserSummary, etc.
Error/Problem Schemas ProblemDetails (RFC 7807), validation errors, trace diagnostics

🧭 4. API Versioning Strategy

Feature Owned By Agent
Version Tags βœ… (v1, v2, …) per route
Deprecation Markers βœ… deprecated: true with replacement hints
Breaking Change Tracking βœ… Emits api-versioning-map.yaml
Compatibility Rules βœ… Includes changelog and semantic version bump triggers

🚫 What It Doesn’t Own

Not Owned Owned By
Adapter/controller implementation βœ… Adapter Generator Agent
Infrastructure routing (gateway config) βœ… API Gateway Configurator Agent
Auth service implementation βœ… Identity/Auth Microservice
CI enforcement pipelines βœ… CI/CD Governance Agent

🧠 System Layer Influence Map

flowchart TD
    subgraph Inputs
      A1[ApplicationArchitect Agent]
      A2[DomainModeler Agent]
      A3[EventDrivenArchitect Agent]
    end

    A1 --> B[API Designer Agent]
    A2 --> B
    A3 --> B

    subgraph Outputs
      B --> C[Adapter Generator]
      B --> D[API Gateway Configurator]
      B --> E[Developer Portal Generator]
      B --> F[Test Generator Agent]
    end
Hold "Alt" / "Option" to enable pan & zoom

βœ… Summary: Agent Boundary of Influence

Area Responsibility
REST/gRPC/AsyncAPI spec definition βœ… Full ownership
DTO schema generation (for API layer) βœ… Based on use cases
API documentation (Markdown, diagrams) βœ… Generated automatically
Observability field injection (e.g., trace_id) βœ… Enforced
OpenAPI + JSON Schema output βœ… Fully owned
API versioning and contract publishing βœ… Fully owned
Business logic or controller implementation ❌ Out of scope
Runtime routing setup ❌ Delegated

πŸ“‹ Core Responsibilities

The API Designer Agent transforms service use cases and application logic into a complete, contract-first API surface.

It is responsible for:

  • Designing clean, consistent, versioned API contracts
  • Enforcing validation, observability, and security metadata
  • Supporting REST, gRPC, and optionally AsyncAPI
  • Emitting artifacts usable by other agents (e.g., gateway, adapter, test, portal)

πŸ“˜ 1. REST API Surface Design (OpenAPI)

Task Description
Define Endpoints Generate paths: section in OpenAPI (e.g., POST /invoices, GET /clients/{id})
Operation Metadata Set operationId, summary, tags, version
Request Models Map use case input to requestBody with schema reference
Response Models Define status codes, success/error responses, ProblemDetails
Parameter Extraction Use path/query/header parameters where applicable
Versioning Apply /v1/ prefix or x-version header annotation
Security Apply global or per-route OAuth2 schemes, scopes, and roles

🧠 2. Schema Generation

Task Description
Generate DTOs From input/output ports, use case signatures, and value objects
Common Components Reuse types like Money, TimeRange, ContactInfo, ValidationError
Validation Rules Inject minLength, maxLength, format, required, enum
Observability Fields Enforce trace_id, correlation_id in request/response headers or payloads
ProblemDetails Extension Add diagnostic codes, help links, error types

πŸ›°οΈ 3. gRPC/Proto Contract Modeling (optional)

Task Description
Define Service and RPC Methods E.g., service BillingService { rpc CreateInvoice(CreateInvoiceRequest) returns (InvoiceResponse); }
Message Modeling Infer messages from DTOs and VOs
Streaming Rules Mark stream where applicable (event replay, logs)
Interop Notes Output .proto file and Markdown explanation

πŸ“¦ 4. Documentation and Contract Artifacts

Task Description
Emit OpenAPI Spec openapi.yaml or openapi.json (OpenAPI 3.1 preferred)
Generate Markdown Summary api-surface-summary.md with table of endpoints, inputs, outputs, versions
Emit DTO Schema Files InvoiceRequest.schema.json, etc.
Emit Observability Hints endpoint-observability.yaml for downstream tracing agents
Emit Event Binding Contracts In AsyncAPI if service emits/subscribes to events

πŸ” 5. Versioning & Lifecycle Control

Task Description
Detect Breaking Changes Compare openapi.yaml with prior versions (e.g., changed param type)
Emit Versioned Specs openapi-v1.yaml, openapi-v2.yaml, etc.
Publish Event Emit ApiContractPublished with trace_id, version, URL

βœ… Summary Table of Responsibilities

Responsibility Output
REST API Surface βœ… openapi.yaml
gRPC API (optional) βœ… *.proto
Schema generation βœ… *.schema.json
Observability & tracing injection βœ… endpoint-observability.yaml
Markdown summary βœ… api-surface-summary.md
API versioning & changelog βœ… api-versioning-map.yaml, ApiContractPublished

🚫 Not Responsibilities

Area Handled By
HTTP controller or gRPC method implementation ❌ Adapter Generator Agent
Gateway runtime routing config ❌ API Gateway Configurator Agent
Auth logic (token issuance, policy resolution) ❌ Auth Microservice
Testing ❌ Test Generator Agent
Load balancing, rate limiting at runtime ❌ Infra layer

πŸ“₯ Core Inputs

The API Designer Agent transforms structured architectural and semantic artifacts into versioned API contracts.

Its inputs define:

  • What capabilities the service exposes
  • Which inputs/outputs it handles
  • How to map responsibilities to HTTP/gRPC/AsyncAPI endpoints
  • How to enforce contracts, observability, and validation rules

πŸ“‹ Required Input Artifacts

Artifact Source Agent Description
use-cases.yaml Application Architect Agent Primary map of service commands and queries
input-ports.json, output-ports.json Application Architect Agent Defines DTO boundaries and I/O flow
domain-model.yaml Domain Modeler Agent Optional source for value objects, enums
validation-map.yaml Domain Modeler Agent Optional source of field constraints (min, max, required, enum, etc.)
event-catalog.yaml Event-Driven Architect Agent Optional β€” maps event-producing endpoints to AsyncAPI interface
application-architecture.md Application Architect Agent Tags endpoints with observability, security, and version info
trace_id, service_name, project_id System Orchestration Layer Required for traceability, artifact versioning, and CI hooks

🧩 Input Field Mapping (REST-focused)

πŸ”· use-cases.yaml

Field Purpose
name: CreateInvoice Operation β†’ POST /invoices
input_dto: CreateInvoiceRequest Request schema
output_dto: InvoiceResponse Response schema
category: Command Suggests HTTP verb: POST
emits_event: InvoiceCreated Tag for async binding (optional)

πŸ”· input-ports.json

Field Use
port: ICreateInvoiceHandler Suggests synchronous endpoint
parameters Inferred request body and query/path mappings
return_type Output schema or status code suggestion

πŸ”· validation-map.yaml

Field Use
Invoice.Amount β†’ must be > 0 Inject into schema as minimum: 0.01
DueDate β†’ must be after Today Add format hint and optional notes
Currency β†’ must be enum(USD, EUR) Translate to enum constraint

πŸ”· event-catalog.yaml (Optional)

Field Use
InvoiceCreated β†’ topic Suggest endpoint emits this event
requires_exactly_once_delivery May alter response semantics or status codes

πŸ” Example Input Prompt (Aggregated YAML)

project:
  service_name: BillingService
  bounded_context: Billing
  trace_id: trace-api-bill-8842

inputs:
  use_cases_url: https://.../use-cases.yaml
  input_ports_url: https://.../input-ports.json
  validation_rules_url: https://.../validation-map.yaml
  application_architecture_url: https://.../application-architecture.md

settings:
  api_type: rest
  output_format: [yaml, markdown]
  version_strategy: semver
  generate_observability_map: true

πŸ§ͺ Validation Rules for Input Phase

Rule Enforced
service_name, bounded_context, trace_id must be present βœ…
At least one of use-cases.yaml or input-ports.json required βœ…
If api_type: grpc, must include output_ports.json βœ…
All referenced DTOs must resolve to schema definitions βœ…
Validation constraints must be injectible or defaulted βœ…
Event tags must match event catalog (if used) βœ…

🧠 Semantic Memory (Optional Retrieval)

  • Match common patterns (CreateX β†’ POST /x, GetXById β†’ GET /x/{id})
  • Suggest known DTO shapes (e.g., Money, Address, Email)
  • Recommend security scopes (billing.write, invoice.read)
  • Reuse versioning metadata and deprecation notices

πŸ“€ Core Outputs

The API Designer Agent produces a complete, observable, and contract-driven API surface.
All outputs are versioned, CI/CD-ready, and structured for downstream agent consumption (e.g., Adapter Generator, Gateway Configurator, Developer Portal, Test Generator).


πŸ“‹ Primary Output Artifacts

Artifact Format Description
openapi.yaml YAML (OpenAPI 3.1) RESTful API contract
grpc-service.proto Protobuf Optional gRPC contract (internal S2S APIs)
api-surface-summary.md Markdown Table of endpoints, methods, DTOs, and status codes
api-dto-schemas/ JSON Schema DTOs with validation rules
api-versioning-map.yaml YAML Tracks breaking/non-breaking changes and version history
endpoint-observability.yaml YAML Trace mapping, span emission, and correlation field injection
ApiContractPublished JSON Event emitted to signal contract readiness

πŸ“˜ 1. openapi.yaml

| Format | OpenAPI 3.1 | | Sections | - paths: β€” all endpoints (/invoices, /invoices/{id})
- components.schemas: β€” reusable DTOs
- security: β€” OAuth2 flows, scopes
- tags: β€” for grouping and documentation
- x-connectsoft: β€” observability and trace metadata


πŸ›°οΈ 2. grpc-service.proto (Optional)

syntax = "proto3";

service BillingService {
  rpc CreateInvoice (CreateInvoiceRequest) returns (InvoiceResponse);
}

message CreateInvoiceRequest {
  string customerId = 1;
  double amount = 2;
}

message InvoiceResponse {
  string invoiceId = 1;
  string status = 2;
}

βœ… Used by services operating over gRPC or for internal AI agent-to-agent calls


πŸ“„ 3. api-surface-summary.md

| Format | Markdown | | Purpose | Human-readable API map for developer onboarding and documentation portals |

| Example Table | | Endpoint | Method | Input DTO | Output DTO | Auth | Version | |----------|--------|-----------|------------|------|---------| | /invoices | POST | CreateInvoiceRequest | InvoiceResponse | OAuth2 (write:billing) | v1 |


πŸ“¦ 4. api-dto-schemas/

| Format | JSON Schema Draft 7+ | | Purpose | Validatable DTO definitions with inline constraints |

| Example: CreateInvoiceRequest.schema.json |

{
  "type": "object",
  "properties": {
    "amount": { "type": "number", "minimum": 0.01 },
    "dueDate": { "type": "string", "format": "date" }
  },
  "required": ["amount", "dueDate"]
}


πŸ“‘ 5. api-versioning-map.yaml

| Format | YAML | | Fields |

versions:
  - version: v1
    endpoints:
      - path: /invoices
        method: POST
        breaking_change: false
  - version: v2
    deprecates: v1
    breaking_change: true
    changelog: Added required field `currency` to request

βœ… Used in CI/CD to validate backward compatibility


πŸ“ˆ 6. endpoint-observability.yaml

| Format | YAML | | Purpose | Span start/end metadata and required trace fields per operation |

POST /invoices:
  trace_fields_required:
    - trace_id
    - correlation_id
    - user_id
  span_template:
    name: "billing.create-invoice"
    type: server

βœ… Used by the Observability Agent and Test Generator for span injection


πŸ“’ 7. Emitted Event: ApiContractPublished

| Format | JSON | | Fields |

{
  "event": "ApiContractPublished",
  "service": "BillingService",
  "boundedContext": "Billing",
  "apiVersion": "v1.0.0",
  "openapiUrl": "https://contracts.connectsoft.dev/billing/openapi.yaml",
  "summaryUrl": "https://docs.connectsoft.dev/billing/api-surface-summary.md",
  "traceId": "api-trace-9221",
  "timestamp": "2025-05-01T22:03:00Z"
}

βœ… Notifies all pipeline participants and dependent agents


βœ… Output Validation Criteria

Output Rule
OpenAPI spec must pass schema validation βœ…
All endpoints must declare HTTP method, path, input, output, and status code βœ…
DTOs must pass JSON Schema validation βœ…
Versioning must be present and changelog generated βœ…
At least 1 observability field (trace_id, correlation_id) per operation βœ…
ApiContractPublished must be emitted on success βœ…

πŸ“š Knowledge Base Overview

The API Designer Agent uses a structured knowledge base to generate:

  • Consistent API path structures
  • Semantic operation names
  • Reusable DTOs and validation rules
  • Standardized observability, security, and versioning patterns
  • Language-independent, platform-governed API schemas

It includes both rule-based knowledge and semantic memory with examples from previously designed APIs.


🧱 1. Endpoint Naming Patterns

Use Case Inferred REST Endpoint
CreateInvoice POST /invoices
GetInvoiceById GET /invoices/{invoiceId}
ListInvoices GET /invoices
ApplyDiscount POST /invoices/{id}/apply-discount
CancelSubscription POST /subscriptions/{id}/cancel

πŸ“Œ Derived from use-cases.yaml β†’ enriched with CRUD heuristics


πŸ“¦ 2. Reusable Schema Components

Component Description
Money { amount: number, currency: string }
DateRange { startDate: string (date), endDate: string (date) }
ProblemDetails Error model (RFC 7807 + traceId, errorCode, diagnostics)
ValidationErrorDetails { field: string, message: string }[]
TraceableRequestHeaders Standard observability fields (trace_id, correlation_id, etc.)

πŸ“– 3. HTTP Verb Heuristics

Use Case Category Suggests
CreateX POST /x
GetX, GetXById GET /x, GET /x/{id}
UpdateX PUT /x/{id}
PatchX, ModifyX PATCH /x/{id}
DeleteX DELETE /x/{id}
SearchX, ListX GET /x with filters or pagination params

πŸ“š 4. Semantic Memory β€” Example API Contracts

Query Result
"CreateInvoice" Suggests OpenAPI path + DTOs + default HTTP status codes (201, 400, 422)
"SendReminder" Suggests POST + retry policy hint + trace injection
"UserDeactivatedEvent" Triggers AsyncAPI output mapping and event-binding headers

Each result includes: - confidence_score
- origin_service
- field naming conventions
- observability support


πŸ›‘οΈ 5. Security Rule Patterns

Feature Enforcement
All endpoints must have a security scheme βœ… OAuth2, bearer token, or API key
Roles and scopes are inferred from glossary or memory βœ… "billing.write", "client.view"
If sensitive DTO is involved β†’ force HTTPS-only flag βœ… Via OpenAPI schemes: override
If PII detected β†’ tag field with x-sensitive: true βœ… Used by security scanners and gateway

πŸ” 6. Versioning and Compatibility

Policy Enforced
Breaking change = new major version βœ… Detected from removed field or changed type
Optional field added = minor version bump βœ… Auto-injected v1.1.0
api-versioning-map.yaml tracks all route changes βœ… Includes breaking_change: true/false, suggested upgrade path
Deprecated routes are tagged with deprecated: true βœ… Markdown summary + warning in OpenAPI

πŸ“ˆ 7. Observability Injection Patterns

Pattern Applied
All POST/PUT/DELETE = emit span βœ… x-trace-span: true
GET endpoints = tag as read-only, optional tracing βœ… x-readonly: true
Header injection required: trace_id, user_id, correlation_id βœ… Documented per operation
Optional: span template emitted in endpoint-observability.yaml βœ… Used by Observability Agent

🧠 Knowledge Retrieval Example Flow

flowchart TD
    A[Receive Use Case: CreateInvoice]
    A --> B[Match Verb + Resource = POST /invoices]
    B --> C[Inject DTO: CreateInvoiceRequest]
    C --> D[Enrich with Security + Validation + Observability]
    D --> E[Emit OpenAPI Path + Schema Reference + Metadata]
Hold "Alt" / "Option" to enable pan & zoom

βœ… Knowledge Base Benefits

Outcome Benefit
Consistent APIs across services βœ… REST and gRPC look & feel unified
Reusable DTOs reduce duplication βœ… Developers reuse Money, Address, etc.
Governance-compliant schemas βœ… Security + traceability enforced by default
Developer onboarding is faster βœ… Markdown docs + diagrams are standardized
CI/CD can diff and validate versions βœ… api-versioning-map.yaml ensures safety

πŸ”„ End-to-End Process Overview

The API Designer Agent executes a modular, skill-driven, and observable flow from use case analysis to contract publication.

It transforms architecture inputs into:

  • OpenAPI / gRPC specs
  • JSON schemas for all DTOs
  • Markdown summaries
  • Observability metadata
  • CI/CD-compatible versioned artifacts

Each step is skill-composed, schema-driven, and memory-aware.


πŸ“‹ Step-by-Step Flow

Phase Description

1️⃣ Input Validation & Semantic Retrieval

  • Validate that trace_id, service_name, use-cases.yaml, and at least one input/output port file are available
  • Retrieve reusable endpoint names, DTOs, field structures, and versioning hints from semantic memory

2️⃣ Use Case β†’ Endpoint Mapping

  • Infer route, HTTP method, and version from use case names (e.g., CreateInvoice β†’ POST /invoices)
  • Extract:
    • Tags
    • Operation summaries
    • Use-case-to-endpoint relationship
    • Event emission hints (emits_event:)

3️⃣ DTO and Schema Generation

  • Generate request/response schemas:
    • Include validation rules (minLength, enum, required) from validation-map.yaml
    • Annotate sensitive fields (x-sensitive: true)
  • Convert domain value objects into OpenAPI-compatible components
  • Ensure camelCase naming and JSON Schema Draft 7+ compatibility

4️⃣ OpenAPI/Proto Contract Construction

  • Compose:

    • paths section with all endpoint methods
    • components.schemas from DTOs and VOs
    • security blocks per endpoint or globally
    • x-connectsoft metadata: trace_id, api_version, span_template
  • For gRPC:

    • Compose service blocks and message definitions from I/O DTOs

5️⃣ Observability & Security Enrichment

  • Inject:

    • Required trace headers: trace_id, correlation_id, user_id
    • x-trace-span: true (to enable observability agents to track lifecycle)
    • Default OAuth2 security schemes or per-endpoint overrides
  • Output span metadata into endpoint-observability.yaml


6️⃣ Versioning & Compatibility Check

  • Compare with previous API spec (if available)
  • Generate:
    • api-versioning-map.yaml
    • api-changelog.md (optional)
    • Emit changelog and version bump (major/minor) if breaking changes detected

7️⃣ Artifact Publishing

  • Output artifacts:
    • openapi.yaml, api-surface-summary.md, api-dto-schemas/*.json, endpoint-observability.yaml
  • Emit ApiContractPublished event with:
    • Artifact links
    • Version info
    • Traceability metadata

πŸ“ˆ Observability Spans (OpenTelemetry)

Span Description
dto_generation.duration Time per schema
openapi_assembly.duration Contract composition step
versioning_diff.duration Breaking change detection
observability_injection.status Whether span templates were added
api_contract_publish.status Contract output status

🧠 High-Level Flow

flowchart TD
    A[Validate Inputs] --> B[Analyze Use Cases]
    B --> C[Infer Endpoints]
    C --> D[Generate DTO Schemas]
    D --> E[Build OpenAPI + Proto Contracts]
    E --> F[Inject Observability + Security]
    F --> G[Check Version Compatibility]
    G --> H[Publish Artifacts + Emit ApiContractPublished]
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Retry/Catch Handling

Phase Issue Correction
DTO generation Invalid field format Use SchemaFixerSkill to auto-patch
Path conflict Route already declared Suggest alternate operationId or version suffix
Schema mismatch Enum missing values Retry with glossary-backed enum injection
Missing headers Add trace_id, user_id, fallback to default span map

πŸ› οΈ Skills and Kernel Functions Overview

The API Designer Agent is powered by a modular, skill-based architecture orchestrated by Semantic Kernel (.NET).
Each skill is responsible for a distinct aspect of API contract modeling β€” from use case analysis to endpoint generation, DTO schema synthesis, versioning, and artifact publishing.

All skills are retry-safe, observability-aware, and schema-constrained.


πŸ“‹ Core Skills

πŸ”· 1. Input & Inference Skills

Skill Responsibility
InputValidatorSkill Validates presence and integrity of use-cases.yaml, trace_id, ports
UseCaseToRouteMapperSkill Translates use case names into HTTP or RPC paths
VerbInferenceSkill Suggests HTTP verb (POST, GET, PATCH) from operation category
TagAndSummaryEnricherSkill Adds operation tags, summaries, groupings from glossary + patterns

πŸ“¦ 2. DTO & Schema Generation

Skill Responsibility
DtoSchemaBuilderSkill Generates JSON Schema for request/response DTOs
ValidationRuleInjectorSkill Injects field constraints (minLength, enum, required) from validation-map.yaml
EnumNormalizerSkill Ensures enums are in PascalCase, and fields are camelCase
SensitiveFieldTaggerSkill Adds x-sensitive: true to PII-related fields

πŸ“˜ 3. OpenAPI / Proto / AsyncAPI Composition

Skill Responsibility
OpenApiBuilderSkill Composes openapi.yaml (OpenAPI 3.1), including paths, components, security
GrpcProtoGeneratorSkill Builds *.proto files for gRPC-based APIs (if enabled)
AsyncApiContractBuilderSkill (Optional) Maps event-producing use cases into AsyncAPI spec (for pub/sub)
OperationMetadataGeneratorSkill Ensures every endpoint includes summaries, operationId, and tag grouping

πŸ” 4. Security & Observability

Skill Responsibility
SecuritySchemeGeneratorSkill Injects OAuth2, API key, or role-based security models
SpanInjectionPlannerSkill Adds x-trace-span metadata and span template hints per endpoint
TraceHeaderEnforcerSkill Requires trace_id, correlation_id, and optionally user_id headers
RateLimitPolicyAnnotatorSkill (Optional) Adds x-rate-limit tags if usage limits are defined

πŸ” 5. Versioning & Diff Management

Skill Responsibility
ApiVersionComparatorSkill Compares current spec to previous and detects breaking changes
VersionBumperSkill Suggests semver-compatible upgrade (v1.0.0 β†’ v1.1.0 or v2.0.0)
ChangelogEmitterSkill Emits api-changelog.md with structured diffs
ApiVersioningMapAssemblerSkill Outputs api-versioning-map.yaml with endpoint lifecycle annotations

πŸ“€ 6. Artifact Assembly & Publishing

Skill Responsibility
ApiContractAssemblerSkill Gathers YAML, JSON Schema, Markdown, and DTOs
OpenApiFileWriterSkill Writes OpenAPI spec to openapi.yaml
MarkdownDocWriterSkill Emits api-surface-summary.md
SchemaFileWriterSkill Exports each DTO to individual .schema.json files
EventEmitterSkill Emits ApiContractPublished JSON event with trace and version metadata

🧠 Skill Composition Flow

flowchart TD
    A[UseCaseToRouteMapperSkill] --> B[DtoSchemaBuilderSkill]
    B --> C[OpenApiBuilderSkill]
    C --> D[SpanInjectionPlannerSkill]
    D --> E[ApiVersionComparatorSkill]
    E --> F[ApiContractAssemblerSkill]
    F --> G[EventEmitterSkill]
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Retry Triggers per Skill

Skill Common Retry Case
DtoSchemaBuilderSkill Missing required/optional field info β†’ fallback to inferred defaults
OpenApiBuilderSkill Duplicate path or tag β†’ suggest suffixing or re-scoping
TraceHeaderEnforcerSkill Missing header injection β†’ add default trace_id and retry
ApiVersionComparatorSkill Unable to parse old spec β†’ downgrade to metadata-only diff

πŸ“ˆ Skill-Level Observability

  • Each skill emits:
    • execution_span, duration_ms, retry_count, status, trace_id, agent_version
  • Metrics collected by Observability Agent and shown in ConnectSoft CI dashboards

πŸ› οΈ Technology Stack Overview

The API Designer Agent is built on a modular, cloud-native, schema-first foundation using technologies that enable:

  • Open standard contract generation
  • Semantic modeling via skills and plugins
  • Format-agnostic output: REST (OpenAPI), gRPC (Proto), AsyncAPI
  • Seamless CI/CD and DevPortal integration
  • Observability and versioning-first output design

πŸ“‹ Core Technologies

🧠 1. Orchestration & Reasoning

Technology Role
Semantic Kernel (.NET) Manages skill composition, input orchestration, retry logic
Azure OpenAI (GPT-4) Natural language mapping of use cases β†’ routes, summaries, validation
ConnectSoft SkillPack: APIDesign Skill set for OpenAPI/gRPC/schema/markdown generation

πŸ“˜ 2. API Specification Standards

Format Use
OpenAPI 3.1.0 Primary output for REST APIs; supports JSON Schema, links, and polymorphism
Protobuf (*.proto) Used for gRPC and AI-to-AI internal service definitions
AsyncAPI (v3) Event producer/consumer contract specification (optional extension)
JSON Schema Draft 7+ Used for DTOs, request/response validation, reusable schemas
Markdown (.md) Human-readable API summaries and endpoint explanations

🧱 3. Output and Artifact Generation

Tool Output
YAML Parser/Emitter (.NET YAML Serializer) Generates openapi.yaml, api-versioning-map.yaml
JSON Schema Generator Generates DTOs, request/response payloads
Markdown Composer Produces api-surface-summary.md, docs for DevPortal
Mermaid Diagram Generator (optional) Flowchart visualizations (API summary, input/output)

πŸ” 4. Security Modeling

Technology Purpose
OAuth2 Flow Modeler Defines flows: password, client_credentials, PKCE
Security Annotations (security: in OpenAPI) Maps route to scopes and policies
x-sensitive Extensions Tag DTO fields with PII risk for redaction/logging/policy enforcement

πŸ“‘ 5. Observability Integration

Tool Function
OpenTelemetry SDK (.NET) Skill-level span tracing, endpoint observability injection
ConnectSoft endpoint-observability.yaml Output: span templates, trace_id/correlation_id mapping
Application Insights / Prometheus Runtime metrics emitted from downstream usage (optional)

πŸ“¦ 6. CI/CD & Registry Integration

Feature Role
Schema Compatibility Checker Validates current vs prior version for breaking changes
Changelog Generator Produces api-changelog.md on diff
Artifact Storage API Stores openapi.yaml, .proto, schemas, summaries
Contract Lifecycle Event Emitter Emits ApiContractPublished to notify CI pipeline and downstream agents
Version Resolver Assigns new semver tags (v1.1.0, v2.0.0) based on compatibility analysis

πŸ“’ Output Delivery Targets

Consumer Output
Adapter Generator Agent openapi.yaml, *.proto, JSON schemas
API Gateway Configurator openapi.yaml (for route -> service mapping)
Developer Portal Agent api-surface-summary.md, openapi.yaml, diagrams
Test Generator Agent DTO schemas, observability map
CI/CD Pipeline Contract validation, changelog diffing, impact assessment

βœ… Output Format Summary

Artifact Format
REST API Spec openapi.yaml
gRPC API grpc-service.proto
AsyncAPI (optional) asyncapi.yaml
DTO Schemas *.schema.json
Observability Map endpoint-observability.yaml
Markdown Docs api-surface-summary.md, api-changelog.md
Version Mapping api-versioning-map.yaml
Contract Lifecycle Event ApiContractPublished (JSON)

βš™οΈ Interoperability with Other Tools

Tool/Agent Integration
Swagger UI / Redoc Visualize and test openapi.yaml
Buf / Protobuf Tools Compile and test grpc-service.proto
AsyncAPI Studio Render event-based specs
VS Code Plugins Validate OpenAPI / JSON Schema output
Azure DevOps Pipelines Consume ApiContractPublished, enforce schema validations

πŸ“œ System Prompt (Bootstrapping Instruction)

The System Prompt defines the API Designer Agent’s goals, behaviors, constraints, and outputs.
It guides the generation of secure, observable, well-documented, and version-controlled API contracts.

This prompt is triggered during service generation and governs REST, gRPC, and optionally AsyncAPI design.


βœ… Full System Prompt (Plain Text)

You are the **API Designer Agent** within the ConnectSoft AI Software Factory.

Your role is to convert service use cases, domain models, and architectural inputs  
into clean, versioned, contract-first **API specifications** that are ready for publication, testing, and implementation.

You generate REST (OpenAPI), gRPC (Protobuf), and optional AsyncAPI (event) interfaces  
that conform to ConnectSoft’s principles of:

- Versioned contracts  
- Observability-first APIs  
- Clean separation of DTOs and domain logic  
- Reusability, validation, and CI/CD compatibility

---

## Responsibilities:

1. Parse inputs:
   - `use-cases.yaml`  
   - `input-ports.json`, `output-ports.json`  
   - `validation-map.yaml`  
   - `domain-model.yaml` (optional for enums/value objects)  
   - `application-architecture.md`

2. For each use case:
   - Infer appropriate HTTP method (POST, GET, PUT, etc.) or gRPC method
   - Generate input/output DTO schemas with validation constraints
   - Define path structure: `/resource`, `/resource/{id}`, or `/resource/action`
   - Add summaries, operationIds, and OpenAPI tags
   - Include span template and trace headers (`trace_id`, `correlation_id`, `user_id`)

3. Compose:
   - `openapi.yaml` (OpenAPI 3.1)  
   - `grpc-service.proto` (optional)  
   - `api-surface-summary.md`  
   - `api-dto-schemas/*.schema.json`  
   - `endpoint-observability.yaml`  
   - `api-versioning-map.yaml`

4. Enforce:
   - DTOs must be clean (no domain entity leakage)
   - API must be versioned
   - All endpoints must support observability (trace_id)
   - Security must be declared (OAuth2, API key, or none)
   - If a previous spec exists, perform version comparison

5. Publish artifacts and emit:
   - `ApiContractPublished` event (JSON)
   - Includes: version, schema URL, service name, trace_id, timestamp

---

## Output Formats:

- OpenAPI (YAML)
- Protobuf (`.proto`)
- Markdown summary
- JSON Schema for DTOs
- Contract metadata and observability hints
- Lifecycle event payload (JSON)

---

## Naming & Conventions:

- Paths: kebab-case, resource-oriented (`/invoices`, `/clients/{id}`)
- Methods: infer from use case semantics
- Field names: camelCase
- DTOs: PascalCase
- Versions: use semver (`v1`, `v1.1`, `v2`)
- PII fields: tag with `x-sensitive: true`

---

## Validation and Observability:

- Each endpoint must include `trace_id`, `correlation_id`
- Each response must define `200`, `4XX`, and `5XX` status codes
- ProblemDetails schema should follow RFC 7807 with trace metadata
- Output must pass OpenAPI/JSON Schema validators

---

## Versioning Policy:

- Breaking changes β†’ new major version (`v1 β†’ v2`)
- Optional fields or non-breaking β†’ minor version bump (`v1.0 β†’ v1.1`)
- Deprecated routes β†’ tagged and documented in changelog

---

## Publishing:

You must emit the `ApiContractPublished` event after output is complete.  
This enables the CI/CD pipeline to validate, approve, and generate downstream artifacts.

πŸ“¦ Purpose of System Prompt

This prompt ensures that the API Designer Agent:

  • Aligns with ConnectSoft’s clean API and observability standards
  • Produces outputs that are human-readable, machine-validated, and developer-consumable
  • Enables automation of downstream gateway, SDK, and test generation
  • Ensures that no code is written without a spec first

πŸ“₯ Input Prompt Template

The API Designer Agent receives its execution context as a structured YAML prompt.
This input defines:

  • The service identity
  • Source artifact URLs
  • Output and versioning preferences
  • Traceability metadata for observability and CI integration

It enables autonomous, reproducible API surface design.


βœ… Full Input Prompt (YAML)

assignment: "generate-api-spec"

project:
  project_id: "connectsoft-saas"
  trace_id: "api-trace-91129"
  bounded_context: "Billing"
  service_name: "BillingService"
  agent_version: "1.2.0"

inputs:
  use_cases_url: "https://artifacts.connectsoft.dev/billing/use-cases.yaml"
  input_ports_url: "https://artifacts.connectsoft.dev/billing/input-ports.json"
  output_ports_url: "https://artifacts.connectsoft.dev/billing/output-ports.json"
  validation_rules_url: "https://artifacts.connectsoft.dev/billing/validation-map.yaml"
  application_architecture_url: "https://artifacts.connectsoft.dev/billing/application-architecture.md"
  domain_model_url: "https://artifacts.connectsoft.dev/billing/domain-model.yaml"

settings:
  api_type: "rest"              # Options: rest, grpc, asyncapi
  output_format: [yaml, markdown, json]
  version_strategy: "semver"    # Options: semver, timestamped
  include_diagrams: true
  include_observability_map: true
  publish_contract: true

πŸ“‚ Prompt Field Breakdown

🧾 project

Field Description
trace_id Used in all logs, metrics, and lifecycle events
project_id ConnectSoft solution namespace
bounded_context Logical service grouping
service_name Current microservice/API owner
agent_version Version of the API Designer Agent used to generate this contract

πŸ“„ inputs

Artifact Required Description
use_cases_url βœ… Primary source of commands/queries and operation metadata
input_ports_url βœ… DTO definitions for inputs
output_ports_url βœ… DTO definitions for outputs
validation_rules_url ⚠️ Optional Constraint injection for DTOs
application_architecture_url ⚠️ Optional Trace injection, authentication requirements
domain_model_url ⚠️ Optional Enum/value object reuse in schemas

βš™οΈ settings

Setting Description
api_type Determines REST, gRPC, or AsyncAPI mode
output_format Defines which artifacts to generate (YAML/JSON/Markdown)
version_strategy Influences version tagging: v1, v1.1, v2, or timestamped
include_diagrams Enables Mermaid diagrams (e.g., resource interaction flow)
include_observability_map Emits endpoint-observability.yaml for tracing
publish_contract If true, emits ApiContractPublished upon success

🧠 Minimal Prompt Example

assignment: generate-api-spec
project:
  service_name: PaymentsService
  trace_id: trace-payments-api-773

inputs:
  use_cases_url: https://.../payments/use-cases.yaml
  input_ports_url: https://.../payments/input-ports.json
  output_ports_url: https://.../payments/output-ports.json

settings:
  api_type: rest
  publish_contract: true

πŸ§ͺ Input Validation Rules

Rule Enforced
service_name, trace_id, and at least one of use_cases_url or input_ports_url must be provided βœ…
DTO definitions must be resolvable βœ…
If version_strategy = semver, previous version must be detectable (if applicable) βœ…
URLs must resolve to valid, structured documents βœ…
If publish_contract = true, all outputs must pass schema validation βœ…

πŸ” Compatibility with Upstream Agents

  • Orchestration pipelines (e.g., Vision Architect Agent) use this input format
  • Fully compatible with Artifact Storage API, CI/CD Contract Validator, and Governance Auditor
  • Supports trace-driven correlation across Domain, Application, and Adapter layers

πŸ“€ Output Expectations

The API Designer Agent emits a suite of versioned, CI-ready, and traceable API contract artifacts, suitable for:

  • Service-to-service and client-to-service communication
  • Developer onboarding
  • API gateway routing
  • Observability instrumentation
  • Adapter generation
  • Test scaffolding
  • Compliance validation

All outputs are format-conformant, schema-validated, and lifecycle-traceable.


πŸ“¦ Primary Output Artifacts

Artifact Format Description
openapi.yaml YAML (OpenAPI 3.1) RESTful service contract
grpc-service.proto (optional) Proto3 Internal RPC interface definition
api-surface-summary.md Markdown Human-readable API endpoint summary
api-dto-schemas/*.schema.json JSON Schema Typed and validated input/output DTO definitions
api-versioning-map.yaml YAML Route version map with breaking change annotations
endpoint-observability.yaml YAML Span hints, trace headers, and correlation fields
ApiContractPublished JSON Event notifying successful API contract delivery

πŸ“˜ 1. openapi.yaml

| Format | OpenAPI 3.1 | | Sections | - paths: β€” route + method definitions
- components.schemas: β€” DTOs and reusable objects
- security: β€” OAuth2 or API key schemes
- x-connectsoft: β€” observability, version, trace metadata
- responses: β€” success, error, validation outputs

βœ… Must pass OpenAPI schema validation
βœ… Includes route versioning and deprecation markers (if applicable)


πŸ›°οΈ 2. grpc-service.proto (Optional)

  • Output for api_type: grpc or hybrid configurations
  • Includes:
    • service and rpc declarations
    • message definitions for request/response DTOs
    • Comments and @version annotations
    • Optionally decorated with observability fields (trace_id, user_id)

πŸ“„ 3. api-surface-summary.md

| Format | Markdown | | Purpose | Developer-friendly overview of service API surface | | Includes | - Endpoint list with methods, DTOs, auth scopes
- DTO/field descriptions
- Version info per route
- Change log (if applicable)


πŸ“¦ 4. api-dto-schemas/ (JSON Schemas)

| Format | JSON Schema Draft 7+ | | Purpose | Validation-compatible request/response DTOs | | Example File | CreateInvoiceRequest.schema.json | | Contents |

{
  "type": "object",
  "properties": {
    "amount": { "type": "number", "minimum": 0.01 },
    "dueDate": { "type": "string", "format": "date" }
  },
  "required": ["amount", "dueDate"]
}


🧭 5. api-versioning-map.yaml

| Format | YAML | | Purpose | Route β†’ version mapping, deprecation flags, change tracking |

routes:
  - path: /invoices
    method: POST
    version: v1
    deprecated: false
    breaking_change: false
  - path: /invoices
    method: POST
    version: v2
    deprecated: false
    breaking_change: true


πŸ“ˆ 6. endpoint-observability.yaml

| Format | YAML | | Purpose | Trace header injection, span naming, correlation expectations |

POST /invoices:
  trace_fields_required:
    - trace_id
    - correlation_id
    - user_id
  span_template:
    name: "billing.create-invoice"
    kind: server


πŸ“’ 7. Emitted Event: ApiContractPublished

| Format | JSON | | Purpose | Notifies CI/CD and downstream agents of spec readiness |

{
  "event": "ApiContractPublished",
  "service": "BillingService",
  "apiVersion": "v1.0.0",
  "openapiUrl": "https://contracts.connectsoft.dev/billing/openapi.yaml",
  "summaryUrl": "https://docs.connectsoft.dev/billing/api-surface-summary.md",
  "traceId": "api-trace-91129",
  "timestamp": "2025-05-01T22:32:00Z"
}


βœ… Validation Rules (Per Output)

Output Validation
openapi.yaml Must validate against OpenAPI 3.1 schema
*.schema.json Must pass JSON Schema syntax + optional field constraints
grpc-service.proto Must compile via protoc (if generated)
ApiContractPublished Must include trace_id, service, version, and URLs
endpoint-observability.yaml Must declare at least trace_id and span_template per operation

πŸ§ͺ CI/CD Compatibility

  • All outputs can be:
    • Stored in Artifact Storage
    • Diffed for breaking changes
    • Validated by Schema Validator Agent
    • Consumed by Adapter, Test, Gateway, and DevPortal Agents

🧠 Memory Strategy Overview

The API Designer Agent uses both short-term (session-specific) and long-term (semantic + structured) memory to:

  • Ensure consistency across microservices
  • Reuse proven endpoint patterns and schema fragments
  • Prevent duplication and contract drift
  • Maintain contract evolution history
  • Guide naming, versioning, and security modeling

🧠 Short-Term Memory (Session Context)

Memory Area Purpose
Mapped Use Cases Tracks which use cases were transformed into which endpoints
Generated DTO Index Cache of all request/response schemas generated in the session
Inferred Routes List of paths + methods to detect collisions
Retry Log Records skill-level corrections and fallback strategies used
Version Diff Cache Stores schema/component diffs during version comparison

Used for conflict prevention, retry loops, and consistent structure across endpoints in a single run.


πŸ—ƒοΈ Long-Term Memory (Semantic + Structured)

This memory persists across generations and services, enabling cross-context reuse and architectural consistency.

πŸ“¦ 1. Endpoint Naming & Verb Heuristics

Pattern Memory Hint
CreateInvoice β†’ POST /invoices βœ… Confidence: 0.95
GetClientById β†’ GET /clients/{id} βœ… Confidence: 1.0
ApplyDiscount β†’ POST /invoices/{id}/apply-discount βœ… Prefix rule reuse
CancelSubscription β†’ POST /subscriptions/{id}/cancel βœ… Suggests command-style routing

🧱 2. Schema Component Reuse

Component Description
Money { amount, currency }
Email { address, verified }
ProblemDetails Extended RFC 7807 with trace_id, error_code
Address { line1, line2, city, zip }
UserSummary { id, name, email }

Components are injected automatically when high-confidence matches are found in use case parameters or value objects.


πŸ›‘οΈ 3. Security + Observability Policy Fragments

Pattern Auto-Enforced
All write endpoints β†’ require trace_id βœ…
DTOs with email, phone β†’ tag fields as x-sensitive βœ…
Endpoint with client_id β†’ inject correlation_id βœ…
Role scope hints (billing.write, client.read) Suggested from glossary or reused mappings

πŸ“œ 4. Version History & Compatibility Ledger

Item Tracks
openapi.yaml@v1 Original schema with route/param list
openapi.yaml@v2 Diff against v1: new fields, route renames, deprecated methods
grpc-service.proto@v1.0 gRPC method changes tracked per service
DTO changelog Added/removed fields, enum expansions, constraint updates

Used by ApiVersionComparatorSkill and ChangelogEmitterSkill


πŸ” 5. Pattern Match Scoring

Memory Match Attributes
pattern_id e.g., post-invoice-v1
origin_trace_id Linked to previous generation
confidence_score Float between 0.0 and 1.0
verified: true Indicates governance-approved fragment
last_used_by: service_name For reuse impact analysis

πŸ” Semantic Memory Query Example

query: "CreateCustomer use case"
result:
  route: POST /customers
  dto: CreateCustomerRequest
  schema_source: "crm.customer"
  match_confidence: 0.91
  reused_fields:
    - email
    - address

πŸ“ˆ Memory Usage Metrics (Exposed to Observability Agent)

Metric Description
endpoint_pattern_reuse_total How many times a prior path/method combo was reused
schema_fragment_injection_count Count of VO/DTO reused
pattern_conflict_resolved_total How many times a naming or version collision was avoided via memory
breaking_change_prediction_accuracy How often version diff matches real change type

βœ… Benefits of Memory-Driven API Generation

Capability Value
βœ… Contract consistency across services APIs feel uniform across ConnectSoft
βœ… DTO reuse reduces drift Easier governance and maintenance
βœ… Version control with history Supports long-term evolution without regression
βœ… Traceability & audit Every contract has lineage and change rationale

βœ… Validation and Correction Framework

The API Designer Agent validates every output artifactβ€”OpenAPI, Protobuf, JSON Schema, and Markdownβ€”using a multi-phase pipeline with auto-correction, retry logic, and schema compliance enforcement.

Each validation step is observable, traceable, and tied to an output lifecycle span.


πŸ“‹ Validation Phases

1️⃣ Input & Structural Validation

Item Rule
use-cases.yaml, input/output ports Must be present and parsable
DTOs Must define at least one required field
Endpoint paths Must be unique within the API spec
Method + path combos Must not conflict with existing versioned routes
Parameters Must resolve to valid path/query/body types

❌ If failed: Retry with structure hint fallback or field inference


2️⃣ OpenAPI / gRPC Contract Schema Validation

Contract Rule
openapi.yaml Must validate against OpenAPI 3.1 schema
grpc-service.proto Must compile using protoc (syntax + message structure)
asyncapi.yaml (optional) Must conform to AsyncAPI v3 schema
DTOs Must pass JSON Schema validation (Draft 7+)
Required fields Must be defined and not nullable unless explicitly optional

❌ If failed: Use SchemaFixerSkill, inject defaults, and retry.


3️⃣ Metadata, Security, and Observability Validation

Rule Description
Every endpoint must include trace_id βœ… enforced via TraceHeaderEnforcerSkill
Sensitive fields must be tagged βœ… x-sensitive: true
Each endpoint must define at least 200, 4XX, and 5XX responses βœ…
OAuth2 scopes (if required) must resolve βœ… from memory or glossary
Version must be present βœ… api-versioning-map.yaml enforced

❌ Missing observability metadata triggers fallback to default span template


4️⃣ Versioning & Compatibility Validation

Validation Result
Spec diff run against previous version Breaking change detected triggers major version
Same version + incompatible schema Blocked and escalated
DTO enum changed with narrowed set Warning issued with compatibility note
Endpoint removed β†’ route marked as deprecated βœ… recorded in changelog

❌ Incompatible spec version reuse β†’ prompts VersionBumperSkill intervention


πŸ” Retry & Auto-Fix Behavior

Skill Retry Trigger Action
DtoSchemaBuilderSkill Field has invalid format Auto-patch with inferred type + retry
OpenApiBuilderSkill Route conflict Append version suffix or resolve with trace prefix
ValidationRuleInjectorSkill Constraint fails JSON schema Fallback to soft validation hint
GrpcProtoGeneratorSkill Protoc error Fallback to previous valid message definition and inject correction marker

🧠 Correction Logging Example

{
  "trace_id": "api-trace-9921",
  "skill": "OpenApiBuilderSkill",
  "retry_attempt": 2,
  "error": "duplicate route POST /invoices",
  "correction": "added version suffix /v2/invoices",
  "resolved": true
}

πŸ“ˆ Observability Metrics Emitted

Metric Description
openapi_validation_passed_total Count of successful OpenAPI schema validations
grpc_proto_compilation_failed_total Track failures in gRPC spec
retry_count_by_skill{name} Number of retries per skill
auto_correction_applied_total How often a fallback or fix was injected
breaking_change_detected_total Change severity scoring from diff engine

🧍 Human Oversight Triggers

Trigger Action
3+ retries on the same skill with partial success Emit ApiContractGenerationWarning
Compatibility diff fails with critical errors Escalate to Governance Agent
x-sensitive field lacks documentation Flag to Security Architect Agent
Unknown OAuth2 scope Warn and log fallback scope resolution

βœ… Benefits of Auto-Validated Pipeline

Value Impact
Clean OpenAPI + DTO schemas βœ… Reliable SDK generation
Proactive versioning βœ… CI-friendly diffs and changelogs
Traceable recovery βœ… Retry paths logged + span IDs present
Secure-by-default APIs βœ… All endpoints require trace_id, auth, scope

🀝 Collaboration Interfaces

The API Designer Agent is deeply integrated into the ConnectSoft AI Software Factory and collaborates with multiple upstream and downstream agents.
Its outputs serve as contracts of record used by adapters, tests, gateways, CI/CD pipelines, and documentation platforms.


πŸ”Ό Upstream Collaboration (Inputs)

Agent Interface
Application Architect Agent
- Provides use-cases.yaml, input-ports.json, output-ports.json
- Source of operation definitions and service boundaries

| Domain Modeler Agent |
- Provides domain-model.yaml, validation-map.yaml
- Supplies value objects, enums, and field validation rules |

| Event-Driven Architect Agent (optional) |
- For AsyncAPI or event-bound endpoint mapping
- Maps endpoint emissions to integration events and topics |

| Solution Architect Agent |
- Provides nfr.yaml and enforcement policies for observability, QoS, security |


πŸ”½ Downstream Collaboration (Consumers)

Agent Consumes

🧱 Adapter Generator Agent

  • openapi.yaml, *.proto, api-dto-schemas/*.json

    Generates REST/gRPC endpoint implementations and controllers


πŸ§ͺ Test Generator Agent

  • openapi.yaml, *.schema.json, endpoint-observability.yaml

    Creates integration and contract tests for API endpoints


πŸ” API Gateway Configurator Agent

  • openapi.yaml

    Extracts route β†’ service bindings, security policies, versioning


πŸ§‘β€πŸ’» Developer Portal Generator Agent

  • api-surface-summary.md, openapi.yaml, api-versioning-map.yaml

    Produces docs, diagrams, changelogs, and endpoint metadata


πŸ“ˆ Observability Agent

  • endpoint-observability.yaml

    Ensures span templates, trace propagation, and diagnostics are embedded into requests


πŸ—οΈ CI/CD Governance Agent

  • ApiContractPublished
  • api-versioning-map.yaml, api-changelog.md

    Enforces compatibility, schema drift prevention, and semantic versioning


πŸ“‘ Lifecycle Event

ApiContractPublished Event Payload

Field Description
event ApiContractPublished
service Source microservice
apiVersion Semantic version string (e.g., v1.0.0)
openapiUrl, summaryUrl, changelogUrl Contract artifact URLs
traceId, timestamp Traceability metadata for CI pipelines and audit dashboards

πŸ” Collaboration Flow Diagram

flowchart TD
    ApplicationArchitect -->|use-cases.yaml| ApiDesigner
    DomainModeler -->|validation-map.yaml| ApiDesigner
    EventDrivenArchitect -->|event-catalog.yaml| ApiDesigner

    ApiDesigner --> AdapterGenerator
    ApiDesigner --> TestGenerator
    ApiDesigner --> DeveloperPortal
    ApiDesigner --> APIGatewayConfigurator
    ApiDesigner --> ObservabilityAgent
    ApiDesigner --> CICDGovernance
Hold "Alt" / "Option" to enable pan & zoom

🧠 Shared Standards and Metadata

All artifacts include:

  • trace_id, project_id, bounded_context, service_name
  • agent_version, api_version, reuse_pattern (if applicable)
  • generated_by: API Designer Agent

These allow all downstream agents to validate, trace, and react accordingly.


πŸ”’ Security Considerations

Mechanism Action
Sensitive field detection Informs Security Architect Agent via field tags (x-sensitive)
Unrecognized scopes Escalated to Governance or Identity agent
Auth + trace metadata Passed to API Gateway Configurator and Observability Agent

βœ… Summary of Interfaces

Target Format
Adapter Generator openapi.yaml, .proto, DTO schemas
Test Generator OpenAPI + observability map
API Gateway OpenAPI paths + security schemes
Dev Portal Markdown + spec
CI/CD Contract event + changelog
Observability Agent Span templates and header rules

πŸ“‘ Observability Hooks

The API Designer Agent is fully observable through OpenTelemetry spans, structured logs, and trace-linked contract lifecycle events.

It allows the platform to:

  • Monitor API generation quality
  • Detect retry patterns and drift
  • Audit output lineage and semantic evolution
  • Validate CI/CD compatibility

πŸ“ˆ Key Telemetry Metrics

Metric Description
api_spec_generation_duration_ms Total runtime per contract
dto_schema_validation_errors_total Count of failed field-level schema validations
contract_retry_count_by_skill Skill-level retry frequencies
openapi_validation_passed_total Number of OpenAPI specs that pass final schema validation
grpc_proto_compilation_failed_total Protobuf specs that fail to compile (if generated)
api_version_conflict_detected_total Detected breaking change attempts on fixed major versions

πŸ” Span & Trace Logging

Each step emits:

  • span_name (e.g., openapi_build, dto_schema_emit)
  • duration_ms, status, trace_id
  • agent_version, retry_count
  • service_name, bounded_context

These are visualized in ConnectSoft CI dashboards and traced through ApiContractPublished β†’ downstream artifact use.


🧍 Human Oversight and Escalation

Although designed to be fully autonomous, the agent includes escalation safeguards:

Trigger Action
3+ retries on DtoSchemaBuilderSkill Emit ApiContractGenerationWarning
Breaking change in stable (v1.x) contract Escalate to Governance Officer
Missing trace_id or scope metadata Block publish and escalate to Platform Architect
Unrecognized role/scope or field type Emit ApiContractValidationFailed with payload snapshot

πŸ“œ Contract Audit Trail

All output artifacts embed metadata:

  • trace_id
  • api_version
  • agent_version
  • generated_on (UTC timestamp)
  • source_inputs[]
  • reuse_patterns[]

Enables full audit compliance and deterministic regeneration


πŸ“’ Emitted Lifecycle Events

Event Purpose
ApiContractPublished Notifies system of successful generation
ApiContractUpdated Used if semver-diff identified
ApiContractValidationFailed Fired when schema/semantic check fails hard
ApiContractDeprecated (optional) Marks routes deprecated in versioning map

πŸ“Š Governance Dashboard Integration

Feature Description
Changelog Viewer Shows diffs between v1, v2, etc.
Breaking Change Scanner Flags route, method, schema, or scope conflicts
Coverage Monitor % endpoints with span templates, trace fields
Audit Chain Viewer Links each API spec with trace, project, service

βœ… Final Outcomes

The API Designer Agent guarantees that:

  • Every service has a standardized, observable, versioned API
  • No API is deployed without a contract-first specification
  • All APIs are machine-readable and human-documentable
  • Downstream agents can consume and build with confidence and traceability

πŸ“¦ Final Output Artifact Recap

Artifact Format
REST Spec openapi.yaml
gRPC Interface grpc-service.proto (optional)
DTOs *.schema.json
Summary Docs api-surface-summary.md, api-versioning-map.yaml
Observability Map endpoint-observability.yaml
Emitted Event ApiContractPublished (JSON)