Skip to content

๐ŸŒ API Library Generator Agent Specification

๐ŸŽฏ Purpose and Factory Placement

๐Ÿง  Agent Identity

The API Library Generator Agent is a high-skill software engineering agent in the ConnectSoft AI Software Factory. It autonomously generates full-featured, production-ready API integration libraries based on the ConnectSoft.ApiLibraryTemplate, designed to interact with external systems, internal services, or third-party APIs.


๐Ÿ— Strategic Role in the Factory

This agent plays a foundational role in supporting the platformโ€™s modular and reusable architecture by producing API-bound libraries that encapsulate:

  • Authentication strategies (OAuth2, OpenID, API Key, etc.)
  • Typed HTTP client wrappers using resilient pipelines
  • Logging, metrics, tracing hooks
  • Request/response models
  • Configuration binding
  • Test scaffolding and mock support

It is typically invoked when:

  • A new integration to a SaaS, internal service, or partner API is needed
  • A service wants to reuse consistent, typed access to another HTTP interface
  • QA/DevOps teams need a mockable, testable, chaos-friendly API module

๐Ÿงฉ Alignment with ConnectSoft Principles

Principle How It Applies
โœ… Clean Architecture Separation of HTTP transport, service abstraction, DI, config, and logic layers
โœ… Modularization Feature flags for authentication, chaos, options, observability, tracing
โœ… Event-Driven Readiness Headers and event-correlation metadata patterns supported
โœ… Observability-First Emits logs, metrics, structured tracing, and chaos events
โœ… Security-First Supports secure credential handling, OpenID/JWT/OAuth integration, mutual TLS, and headers
โœ… Cloud-Native Works with Azure Pipelines, SDKs, options pattern, and K8s readiness
โœ… Multi-Tenant SaaS Support Injects tenant-aware headers, correlation IDs, and auth delegation features

๐Ÿงญ Agent Placement in System

flowchart TD
    VisionAgent --> PlannerAgent
    PlannerAgent --> APILibraryGeneratorAgent
    APILibraryGeneratorAgent --> QAAgent
    APILibraryGeneratorAgent --> CIOrchestratorAgent
    APILibraryGeneratorAgent --> PackagingAgent
    APILibraryGeneratorAgent --> MockServerAgent
Hold "Alt" / "Option" to enable pan & zoom

This agent often operates in coordination with:

  • ๐Ÿ”ง Backend Library Generator Agent โ€” shares options and metrics generation logic
  • ๐Ÿงช QA Agent โ€” consumes test project and chaos configurations
  • ๐Ÿ” Orchestrator/Coordinator Agents โ€” handle multi-step API call compositions

๐Ÿ”ง Factory Use Cases

Use Case Triggering Intent
๐Ÿ”Œ Integrating a third-party REST API generate-api-library --name=ConnectSoft.Integration.Zoom
โ™ป๏ธ Replacing fragile HTTP clients migrate-to-resilient-api-wrapper
๐Ÿงช Building a testable contract for a flaky partner generate-api-library --with-mock --with-chaos
๐Ÿ” Onboarding a new OAuth2-protected API generate-api-library --auth=oauth2

๐Ÿ“Œ Agent Responsibilities

๐Ÿง  Core Responsibility

The API Library Generator Agent is responsible for autonomously producing a complete, production-grade .NET API integration library that conforms to the ConnectSoft.ApiLibraryTemplate, with support for advanced configuration, authentication, testing, observability, and resiliency.


๐Ÿงฉ Functional Deliverables

Category Description
๐Ÿ“ฆ Solution Scaffold Generates .sln with two projects: core API library and its tests
๐Ÿงฑ API Wrapper Implements typed client(s) over HttpClient or Refit, with policy-based middleware (Polly)
๐Ÿ” Authentication Logic Adds handlers for specified auth schemes (API Key, OAuth2, etc.) and secrets injection
โš™๏ธ Resiliency Layer Generates policies: retry, circuit breaker, fallback, hedging, timeout, chaos injection
๐Ÿ“Š Observability Includes structured logging, OpenTelemetry spans, optional metrics (Prometheus / App Insights)
โš™๏ธ Options Binding Adds strongly-typed settings with IOptions<T>, validation, and user secrets compatibility
๐Ÿงช Test Scaffold Creates test project with mocks, integration test samples, WireMock.Net configuration
๐Ÿ” Configuration Support Handles user secrets, config sections, headers, TLS, and environment overrides
๐Ÿงช Mock Server Setup Optionally injects local mock support using WireMock.Net or in-memory fakes
๐Ÿ“„ Documentation Generates a README.md with API usage, configuration, and test instructions
๐Ÿš€ CI/CD Ready Artifacts Emits azure-pipelines.yml, .csproj with NuGet metadata, .gitignore
๐Ÿ” Retry and Self-Heal Logic Auto-regenerates outputs on failure using validation and memory graphs

โš™๏ธ Agent Modes of Operation

Mode Behavior
๐Ÿง  Planner Invocation Executes based on blueprint plan (e.g., โ€œconnect to external system Xโ€)
๐Ÿ”ง Manual CLI Call Accepts structured flags (e.g., --auth=oauth2 --useChaos=true)
๐Ÿ”„ Template Rebuild Trigger Regenerates an existing API wrapper with new feature flags
๐Ÿค– Auto-Healing Regeneration Retry path triggered after validation failure or config mismatch

๐Ÿ“ฆ Generated Components Overview

ConnectSoft.Integration.MyApi/
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.csproj
โ”œโ”€โ”€ MyApiClient.cs                โ† typed client
โ”œโ”€โ”€ IMyApiClient.cs              โ† interface
โ”œโ”€โ”€ MyApiClientOptions.cs        โ† IOptions<T>
โ”œโ”€โ”€ MyApiAuthenticationHandler.cs โ† (if auth enabled)
โ”œโ”€โ”€ ResiliencePolicies.cs        โ† Polly wrapper
โ”œโ”€โ”€ Observability.cs             โ† Logging, metrics, tracing
โ”œโ”€โ”€ MockServer/                  โ† (if mock enabled)
โ”‚   โ””โ”€โ”€ MyApiMockServer.cs
โ”œโ”€โ”€ Tests/
โ”‚   โ””โ”€โ”€ ConnectSoft.Integration.MyApi.Tests.csproj
โ”‚   โ””โ”€โ”€ MyApiClientTests.cs
โ”œโ”€โ”€ azure-pipelines.yml
โ””โ”€โ”€ README.md

๐Ÿงฉ Supported Use Cases and Scenarios

The API Library Generator Agent supports a wide variety of integration needs across domains, systems, and architectures. Its output enables plug-and-play usage in microservices, orchestrators, background jobs, and more โ€” all while maintaining factory standards for resilience, observability, security, and reusability.


๐ŸŽฏ Primary Scenarios

Scenario Description
๐ŸŒ Third-Party SaaS Integration Wrapping external REST/GraphQL APIs like Stripe, Zoom, Salesforce
๐Ÿ”„ Internal Service Gateway Creating client wrappers for internal microservices
๐Ÿงฑ Infrastructure Layer Creating reusable libraries for messaging, identity, search APIs
๐Ÿ›ก Secured API Interaction Supporting OAuth2, OpenID Connect, mutual TLS, API key-based endpoints
๐Ÿงช Testing, Mocking, Chaos Simulation Mocking external APIs using WireMock, injecting fault scenarios
๐Ÿ” Multi-Region / Multi-Host Resilience Supporting failover, hedging, timeouts, and retries per region
๐Ÿง  Multi-Tenant Token Providers Dynamic identity delegation (e.g., per tenant/client auth headers)
๐Ÿ’ก SDK or Connector Publishing Used as a published NuGet package in many projects
๐Ÿ” Compliance-Aware Integration Headers, tracing IDs, audit tags, and scoped secrets injected automatically

๐Ÿงฐ Examples from Use Cases

Example Input Flags Notes
ConnectSoft.Integration.Zoom --auth=oauth2 --useLogging --useRetry Creates a resilient OAuth2 wrapper for Zoom API
ConnectSoft.Integration.SearchService --auth=jwt --useOptions --multiHost Internal search integration with fallback region logic
ConnectSoft.Integration.InternalUsers --noAuth --useChaos --useMock Wraps internal API with simulated error scenarios
ConnectSoft.Integration.MarketingHub --auth=apikey --useMetrics Binds API Key from IOptions<T> config with metric observability
ConnectSoft.Integration.SamlSecureService --auth=saml --useHeaderInjection Integrates with SAML-based secure service with scoped headers

๐Ÿ” Resiliency Use Cases

Feature Supported
Retry w/ exponential backoff โœ…
Circuit breaker โœ…
Timeout w/ cancellation tokens โœ…
Fallback and failover hosts โœ…
Bulkhead isolation (if enabled) โœ…
Rate limiter with sliding window โœ…
Chaos injection (latency, error) โœ…
Multi-host hedging support โœ…

๐Ÿงช Mock and Test Use Cases

Scenario Feature
Generate WireMock test cases โœ…
Inject configurable mock server class โœ…
Run chaos tests in CI โœ…
Build Verify snapshot tests โœ…
Replace real client with in-memory handler โœ…
Provide config to enable/disable mocks โœ…

๐Ÿ“ฅ Required Inputs and Flag Detection

๐ŸŽฏ Purpose

This section defines how the agent interprets inputs to generate the correct API library structure, behaviors, and features โ€” including authentication methods, resilience strategies, testing/mocking, and observability options.

The agent supports:

  • Natural language prompts (via planners or developers)
  • Structured JSON-based intent calls (e.g., MCP or planner API)
  • CLI-style flag-based invocations

๐Ÿงฉ Required Inputs (Minimal Set)

Field Type Required Description
name string โœ… Library name (e.g., ConnectSoft.Integration.Zoom)
apiBaseUrl string โœ… Root endpoint of the target API
authType string โ›”๏ธ Authentication mechanism (none, apikey, oauth2, jwt, openid, saml, etc.)
useOptions boolean โ›”๏ธ Generate configuration via IOptions<T>
useRetry boolean โ›”๏ธ Add Polly retry + exponential backoff
useCircuitBreaker boolean โ›”๏ธ Adds circuit breaker policy
useChaos boolean โ›”๏ธ Enables chaos injection features
useMock boolean โ›”๏ธ Adds mock server scaffolding
useLogging boolean โ›”๏ธ Adds logging via ILogger<T>
useMetrics boolean โ›”๏ธ Adds metrics and Prometheus/OpenTelemetry hooks
multiHost boolean โ›”๏ธ Enables multiple base URLs for failover or regional fallback
buildDefinitionNumber string โ›”๏ธ Used in .csproj/pipeline for versioning metadata
framework string โ›”๏ธ Target framework(s): net8.0, net9.0, net8.0;net9.0

๐Ÿ”ง Sample Structured Input (Semantic Kernel or MCP Call)

{
  "intent": "generate-api-library",
  "parameters": {
    "name": "ConnectSoft.Integration.HubSpot",
    "apiBaseUrl": "https://api.hubapi.com",
    "authType": "apikey",
    "useRetry": true,
    "useChaos": false,
    "useOptions": true,
    "useMock": true,
    "useLogging": true,
    "buildDefinitionNumber": "87"
  }
}

๐Ÿ’ฌ Sample Free-Form Prompt

Create an API library for HubSpot using an API key. 
Add observability and retry logic, and include a mock server for testing.
Use .NET 8 and set the build version to 87.

โ†’ Internally resolved into the structured input above via the agentโ€™s Prompt Resolver Skill.


๐Ÿง  Flag Resolution Logic

Input Mode Mechanism
Prompt NLP + intent parser (with Semantic Kernel or OpenAI function calling)
CLI Flags resolved via template.json and CLI schema
Planner Parameters injected by blueprint planner
Memory Past values inferred from memory graph (e.g., retry defaults for Zoom integrations)

๐Ÿ“ค Expected Outputs (Code + Artifacts + Metadata)

๐ŸŽฏ Output Objective

The API Library Generator Agent must emit a complete and deployable .NET-based API integration library, composed of:

  • A primary library project
  • A test project
  • CI/CD pipeline definition
  • Optional mock server, observability, and chaos modules
  • A NuGet-compatible .csproj
  • A structured README
  • Metadata for tracking, publishing, and validation

๐Ÿ“ Directory Structure

ConnectSoft.Integration.MyApi/
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.sln
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi/
โ”‚   โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.csproj
โ”‚   โ”œโ”€โ”€ MyApiClient.cs
โ”‚   โ”œโ”€โ”€ IMyApiClient.cs
โ”‚   โ”œโ”€โ”€ MyApiAuthenticationHandler.cs       (if auth enabled)
โ”‚   โ”œโ”€โ”€ MyApiClientOptions.cs               (if UseOptions)
โ”‚   โ”œโ”€โ”€ Observability.cs                    (if UseLogging / UseMetrics)
โ”‚   โ”œโ”€โ”€ ResiliencePolicies.cs               (if UseRetry, etc.)
โ”‚   โ”œโ”€โ”€ ChaosInjector.cs                    (if UseChaos)
โ”‚   โ”œโ”€โ”€ MockServer/
โ”‚   โ”‚   โ””โ”€โ”€ MyApiMockServer.cs              (if UseMock)
โ”‚   โ””โ”€โ”€ README.md
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.Tests/
โ”‚   โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.Tests.csproj
โ”‚   โ”œโ”€โ”€ MyApiClientTests.cs
โ”‚   โ”œโ”€โ”€ MockTests.cs                        (if UseMock)
โ”‚   โ””โ”€โ”€ ChaosTests.cs                       (if UseChaos)
โ”œโ”€โ”€ azure-pipelines.yml
โ””โ”€โ”€ .gitignore

๐Ÿ“ฆ Artifact Requirements

Artifact Required Description
*.sln โœ… Solution including core and test projects
*.csproj โœ… Includes metadata: version, license, authors, repo URL
*.cs source files โœ… Client, auth, resilience, options, DI wiring
Options/ โ›”๏ธ Only if UseOptions = true
MockServer/ โ›”๏ธ Only if UseMock = true
README.md โœ… Template includes usage, configuration, and testing
azure-pipelines.yml โœ… Includes build, test, coverage, pack, push stages
Unit Tests โœ… MSTest scaffold; Verify, chaos, and integration tests optional
Mock Scenarios โ›”๏ธ WireMock mappings, if mocking is enabled
.gitignore โœ… With defaults for .NET, bin/, obj/, and test outputs

๐Ÿงช YAML Pipeline Expectations

  • Restore
  • Build
  • Test (with optional chaos test stage)
  • Generate code coverage
  • Pack to .nupkg
  • Push to internal NuGet feed
  • Static analysis (optional: dotnet format, analyzers)

๐Ÿ“Š Metadata Fields (from .csproj)

Field Description
PackageId ConnectSoft.Integration.MyApi
Version Derived from buildDefinitionNumber
Authors "ConnectSoft AI Software Factory"
RepositoryUrl Link to source control or registry
Description Short description of the library
TargetFrameworks Multi-TFM support if needed

๐Ÿ“„ README.md Sections

  • ๐Ÿ“Œ Purpose and Scope
  • โš™๏ธ Configuration and Environment Setup
  • ๐Ÿ” Authentication Details
  • ๐Ÿงช Test Instructions (Mock, Chaos, etc.)
  • ๐Ÿ“ฆ CI/CD and NuGet Usage
  • ๐Ÿ“ˆ Observability and Tracing
  • ๐Ÿ”„ Retry and Circuit Breaker Notes
  • ๐Ÿ“š References

๐Ÿง  Skills and Agent Knowledge Graph

๐ŸŽฏ Purpose

The agent is powered by a rich set of modular skills and operates using a knowledge graph that allows it to reason about:

  • Feature dependencies
  • Authentication patterns
  • Configuration and DI conventions
  • Resilience and testing best practices

These skills are reusable, testable Semantic Kernel functions or OpenAI tools and can be composed or triggered via planner agents, MCP intents, or internal prompts.


๐Ÿ›  Core Skills Used by Agent

Skill Name Purpose
ResolveApiLibraryFlagsSkill Parses user input to resolve CLI flags or prompt features
GenerateDotnetApiTemplateSkill Uses dotnet new ConnectSoft.ApiLibraryTemplate with resolved flags
InjectAuthenticationHandlerSkill Adds code for API Key, OAuth2, JWT, etc.
GenerateTypedHttpClientSkill Adds interfaces and implementation for resilient typed client
AddPollyResilienceSkill Adds retry, fallback, circuit breaker, timeout, and hedging policies
InjectChaosLayerSkill Adds chaos configuration and simulation classes
GenerateMockServerSkill Emits a WireMock-based mock server (optional)
CreateObservabilityHooksSkill Adds logs, metrics, OpenTelemetry spans
AddPipelineYamlSkill Generates or updates azure-pipelines.yml with build/test/pack/publish
GenerateTestsSkill Creates base MSTest/Verify tests with mocks
CreateReadmeSkill Writes README.md based on the library metadata and flags
ValidateApiLibraryOutputSkill Runs schema, structure, and file completeness validation
RetryFailedOutputSkill Uses internal memory to rerun failed generations with corrections
RegisterLibraryInMemoryGraphSkill Links newly generated library to knowledge base for reuse detection

๐Ÿงฉ Agent Knowledge Graph

The API Library Generator Agent is embedded into a semantic knowledge graph that includes:

  • Templates and their features (ConnectSoft.ApiLibraryTemplate)
  • Flag compatibilities (e.g., UseChaos requires UseRetry)
  • API types and patterns (e.g., paginated REST vs streaming APIs)
  • Auth strategies and their handlers
  • Observability best practices
  • Retry patterns based on failure types
  • Prior generated outputs, including:
    • Project names
    • Enabled flags
    • Known issues/resolutions
    • Build outputs and versions

graph TD
    A[ConnectSoft.Integration.HubSpot]
    B[UseRetry: true]
    C[UseMock: true]
    D[AuthType: apikey]
    E[LibraryVersion: 1.0.87]
    F[MockServer.cs]
    G[README.md]

    A --> B --> C --> D --> E --> F --> G
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿ“š Example Skill Chain (Semantic Kernel)

โ†’ ResolveApiLibraryFlagsSkill
โ†’ GenerateDotnetApiTemplateSkill
โ†’ InjectAuthenticationHandlerSkill
โ†’ AddPollyResilienceSkill
โ†’ GenerateTypedHttpClientSkill
โ†’ ValidateApiLibraryOutputSkill
โ†’ RetryFailedOutputSkill (if needed)

Each skill may be pre-wired into an orchestrator planner, or composed dynamically depending on prompt intent or blueprint stage.


๐Ÿ” Agent Workflow and Process Diagram

๐ŸŽฏ Purpose

This section defines the step-by-step operational flow the API Library Generator Agent follows from input resolution to final artifact emission, including retry and validation loops, and decision trees based on feature flags like useChaos, authType, or useMock.


๐Ÿง  High-Level Execution Flow

flowchart TD
    A[๐ŸŸข Start: Generation Intent Received]
    B[๐ŸŽฏ Resolve Prompt or CLI Flags]
    C[๐Ÿงฐ Instantiate .NET Template]
    D[๐Ÿ” Inject Authentication Handler]
    E[๐Ÿ” Apply Resilience (Polly)]
    F[๐Ÿงฑ Generate HttpClient Wrapper + Interfaces]
    G[โš™๏ธ Add Configuration & Options Binding]
    H[๐Ÿ“Š Insert Observability (Logs, Metrics)]
    I[๐Ÿ”ฅ Add Chaos Injection Layer (if enabled)]
    J[๐Ÿงช Add Mock Server (if enabled)]
    K[โœ… Generate Unit & Integration Tests]
    L[๐Ÿ“„ Create README.md]
    M[๐Ÿ“ฆ Add azure-pipelines.yml]
    N[๐Ÿงช Validate Structure + Contracts]
    O{Valid?}
    P[๐ŸŽ‰ Final Output Ready]
    Q[โ™ป๏ธ Retry + Fix Failed Generation]

    A --> B --> C --> D --> E --> F --> G --> H
    H --> I --> J --> K --> L --> M --> N --> O
    O -->|Yes| P
    O -->|No| Q --> B
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿงฉ Subsystems Activated per Feature Flag

Feature Subsystem Triggered
authType != none InjectAuthenticationHandlerSkill
useOptions = true AddOptionsPatternSkill
useRetry = true AddRetryPolicySkill
useCircuitBreaker = true AddCircuitBreakerSkill
useChaos = true InjectChaosLayerSkill
useMock = true GenerateMockServerSkill
useLogging / useMetrics CreateObservabilityHooksSkill
useTest = true GenerateTestsSkill

๐Ÿงฎ Deterministic and Adaptive Paths

Type Example
Deterministic Path Always generates .sln, .csproj, test project, and README
Adaptive Path Chaos, mocking, authentication logic, pipeline YAML steps
Memory-Aware Path If a similar library was generated previously, it reuses inferred patterns (e.g., Zoom โ†’ OAuth2 reuse)

๐Ÿ” Retry Path

On any failure (e.g., missing Observability.cs, YAML misstructure):

  1. Agent logs failure and trace (output.validation.failed)
  2. Root cause is inferred via ValidateApiLibraryOutputSkill
  3. Agent invokes RetryFailedOutputSkill with adaptive correction
  4. Full generation loop is re-executed up to 2 times before escalating

๐Ÿง  Embedded Observability Hooks in Flow

  • Span: api-library.generator.start
  • Span: template.instantiated
  • Span: authentication.handler.injected
  • Span: validation.failed (if any)
  • Metric: generation.duration.ms, retry.count, features.enabled

๐Ÿงช Technologies and Stack

๐ŸŽฏ Purpose

This section outlines the technological foundations that power the API Library Generator Agent โ€” spanning its runtime environment, agent orchestration, generation templates, and supported platform tooling. These ensure it integrates deeply with the ConnectSoft ecosystem and supports advanced agentic automation.


๐Ÿง  Core Agent Platform

Layer Technology
๐Ÿง  AI Kernel Semantic Kernel (.NET) with planner + function orchestration
๐Ÿงฉ Language Model Azure OpenAI GPT-4 or GPT-4o via SK plugins
๐Ÿ” Orchestration MCP Protocol / MCP Server dispatches generate-api-library intent
๐Ÿงฑ Templates ConnectSoft.ApiLibraryTemplate installed via .NET CLI
๐Ÿง  Prompt Completion Engine Semantic Kernel skills with system + user prompts
๐Ÿ“š Memory Graph Vector DB (e.g., Azure Cognitive Search, Weaviate, or Qdrant) + JSON metadata store
๐Ÿ“ฆ Template Resolution .template.json + CLI schema from the ConnectSoft API Template

๐Ÿงฐ Runtime and Tooling

Area Tooling
โš™๏ธ Template Engine dotnet new (CLI) with --install for custom templates
๐Ÿงช Testing MSTest, Verify, WireMock.Net
๐Ÿ” Resiliency Polly (.NET), with fallback, retry, circuit breaker, hedging
๐Ÿ” Auth Support Custom DelegatingHandler + OpenIddict / IdentityModel libraries
๐Ÿ“ฆ NuGet Publishing Azure Artifacts + dotnet pack, dotnet nuget push
๐Ÿ“„ Documentation Markdown-based README.md from SK prompt templates
๐Ÿ“ˆ Observability OpenTelemetry SDK, Prometheus (metrics), Serilog (logs), Application Insights (traces)
๐Ÿš€ CI/CD Azure DevOps Pipelines (azure-pipelines.yml) auto-generated

๐Ÿงฌ Supported Integration Targets

Category Examples
SaaS APIs HubSpot, Zoom, Stripe, Salesforce, Greenhouse
Internal APIs UserService, ProductCatalogService, AuthZService
Hybrid APIs External but private partner APIs secured via JWT / OAuth2
Specialized APIs SAML endpoints, Kerberos-auth APIs, legacy HTTP Basic Auth endpoints

๐ŸŒ API Types Supported

API Pattern Supported
REST (OpenAPI or raw) โœ…
GraphQL โœ… (via GraphQL.Client or HTTP abstraction)
SOAP/XML โœ… (via HttpClient or WCF bridge wrapper)
gRPC-Gateway โœ… (via REST proxy)
Event-driven API/Callback โœ… (header injection + correlation ID support)

๐Ÿง  Skills Runtime (Semantic Kernel)

  • Fully integrated with Azure-hosted SK kernel, running custom Function Skills defined per feature area.
  • Modular support for chaining skills (SkillChainPlan).
  • Uses Function Calling via OpenAI-compatible model for input-to-flag resolution.

๐Ÿ”Œ Inter-Agent Interfaces

  • Interacts with:
    • ๐Ÿงช QA Agent โ†’ test validation
    • ๐Ÿ“ฆ Packaging Agent โ†’ NuGet metadata
    • ๐Ÿ” CI/CD Agent โ†’ YAML and pipeline automation
    • ๐Ÿง  Planner Agent โ†’ receives blueprint-level instructions
    • ๐Ÿงโ€โ™‚๏ธ Human Oversight โ†’ notification, retry feedback, and diff review (if override required)

๐Ÿงพ System Prompt Design

๐ŸŽฏ Purpose

The System Prompt is the foundational instruction used to bootstrap and constrain the behavior of the API Library Generator Agent. It defines the agentโ€™s identity, operational scope, constraints, supported flags, and formatting expectations. This prompt is used by Semantic Kernel when initializing or invoking the agent in zero-shot or planner-injected contexts.


๐Ÿง  Role Definition

You are the API Library Generator Agent in the ConnectSoft AI Software Factory. 
Your purpose is to autonomously generate a fully featured .NET-based API integration library 
using the ConnectSoft.ApiLibraryTemplate.

You generate reusable, testable, secure, and observable HTTP API wrappers 
based on structured flags and prompts.

You must support complex features such as:
- Authentication strategies: API Key, OAuth2, OpenID, JWT, SAML, Kerberos, etc.
- Resilient HTTP clients using Polly
- Chaos engineering features and fault injection
- WireMock-based mocks for test automation
- Observability (metrics, logging, tracing)
- Secure configuration using IOptions<T> with validation
- Azure Pipelines CI/CD support
- Clean Architecture layering and separation of concerns

Always adhere to Clean Architecture, Modular Design, Observability-First, 
and Security-First principles.

Only emit files, folders, content, or metadata relevant to generation. 
Do not respond with explanations or summaries.

๐Ÿงฉ Prompt Goals and Behavior Constraints

Area Behavior
๐Ÿงฑ Template Scope Agent is limited to ConnectSoft.ApiLibraryTemplate
๐Ÿ” Secure Defaults Avoid hardcoding secrets or plain tokens
๐Ÿงช Test Enforcement Always generate test project and mock scaffolds (if enabled)
๐Ÿง  Retry Readiness If generation fails, log, diagnose, and suggest a regeneration path
๐Ÿ“ฆ Output Structure Return clean file trees, YAML blocks, markdown sections as artifacts
๐Ÿ”— Semantic Consistency Align generated content with previous agent outputs when reusing patterns

๐Ÿ’ฌ Tone and Output Style

  • Declarative
  • Modular
  • File-oriented (never conversational)
  • Markdown-wrapped outputs (if applicable for documentation)
  • JSON-wrapped outputs (for CI pipelines or SK planner execution)

๐Ÿ›ก Safety and Sanity Constraints

Constraint Description
โŒ No command execution Do not invoke dotnet commands directly in output
โŒ No sensitive placeholders Do not include secrets like client_id, client_secret, token_url without clear placeholders
โœ… Masked Configuration Replace all sensitive values with <YOUR_*> placeholders
โœ… Only output files No explanations unless explicitly requested by orchestration agent

โœ‰๏ธ Input Prompt Template

๐ŸŽฏ Purpose

The Input Prompt Template is how the agent interprets structured or natural user input to map it to generation logic. This template helps translate user intents into generation instructions, transforming user requests into flag-driven commands for the ConnectSoft API Library template engine.


๐Ÿ“ฅ Supported Input Modes

Mode Source Description
๐Ÿง  Natural Language From user prompt or planner Human-readable instructions with inferred flags
๐Ÿ“‹ Structured JSON From blueprint or SK planner Direct injection of generation parameters
๐Ÿ’ป CLI-style Used for testing or scripting Emulates command-line usage of the template

๐Ÿงฉ Template Structure

๐Ÿ”น Natural Language Template (to SK planner or function calling)

Create an API integration library for [API Name] using [authType].
It should support [features], target .NET [TFM], and include [mock/chaos/tests] if needed.

Output should follow Clean Architecture, include tests, and generate CI pipeline.

๐Ÿ”น Examples

Generate a .NET API wrapper for Stripe using API Key authentication.
Add retries, logging, and configuration. Include a mock server for testing.
Build a resilient API client for HubSpot with OAuth2 and options pattern.
Target net8.0 and enable chaos injection for staging.

๐Ÿงพ Structured JSON Template

{
  "intent": "generate-api-library",
  "parameters": {
    "name": "ConnectSoft.Integration.HubSpot",
    "apiBaseUrl": "https://api.hubapi.com",
    "authType": "oauth2",
    "useRetry": true,
    "useLogging": true,
    "useChaos": false,
    "useMock": true,
    "useOptions": true,
    "buildDefinitionNumber": "87",
    "framework": "net8.0"
  }
}

๐Ÿง  Prompt Template Internals

Internally resolved flags map to:

  • dotnet new ConnectSoft.ApiLibraryTemplate
  • With symbols such as:

  • --auth=oauth2

  • --useChaos=true
  • --useRetry=true
  • --useOptions=true
  • --multiHost=false

The agent uses:

  • Semantic Kernel prompt injection
  • Function calling for JSON transformation
  • Memory graphs to auto-complete or override missing values (e.g., default to useRetry=true if chaos enabled)

๐Ÿ›ก Prompt Validation Rules

Check Logic
โœ… Required Fields name, apiBaseUrl
โŒ Invalid Combinations useChaos=true with useRetry=false is not allowed
โ›”๏ธ Legacy Auth Modes authType=basic triggers warning and fallback to API key
๐Ÿ”„ Memory Overrides Reuse previous flag sets for known APIs (e.g., Zoom โ†’ authType=oauth2)

๐Ÿ“ฆ Output Contracts (Solution, Projects, Files)

๐ŸŽฏ Purpose

The output contract defines the complete structure and standards for what the API Library Generator Agent must emit โ€” across source code, configuration, testing, pipelines, and metadata. This enforces consistency, observability, and production readiness for each generated integration.


๐Ÿ“ Folder and File Structure

ConnectSoft.Integration.MyApi/
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.sln
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi/
โ”‚   โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.csproj
โ”‚   โ”œโ”€โ”€ MyApiClient.cs
โ”‚   โ”œโ”€โ”€ IMyApiClient.cs
โ”‚   โ”œโ”€โ”€ Authentication/
โ”‚   โ”‚   โ””โ”€โ”€ MyApiAuthenticationHandler.cs
โ”‚   โ”œโ”€โ”€ Configuration/
โ”‚   โ”‚   โ””โ”€โ”€ MyApiClientOptions.cs
โ”‚   โ”œโ”€โ”€ Resilience/
โ”‚   โ”‚   โ””โ”€โ”€ ResiliencePolicies.cs
โ”‚   โ”œโ”€โ”€ Observability/
โ”‚   โ”‚   โ””โ”€โ”€ Observability.cs
โ”‚   โ”œโ”€โ”€ Chaos/
โ”‚   โ”‚   โ””โ”€โ”€ ChaosInjector.cs
โ”‚   โ”œโ”€โ”€ MockServer/
โ”‚   โ”‚   โ””โ”€โ”€ MyApiMockServer.cs
โ”‚   โ””โ”€โ”€ README.md
โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.Tests/
โ”‚   โ”œโ”€โ”€ ConnectSoft.Integration.MyApi.Tests.csproj
โ”‚   โ”œโ”€โ”€ MyApiClientTests.cs
โ”‚   โ”œโ”€โ”€ MockTests.cs
โ”‚   โ””โ”€โ”€ ChaosTests.cs
โ”œโ”€โ”€ azure-pipelines.yml
โ”œโ”€โ”€ .gitignore
โ””โ”€โ”€ Directory.Packages.props (optional)

๐Ÿงฑ Project Composition

Project Purpose
*.MyApi Core logic: client, DI, options, auth, resilience
*.MyApi.Tests Unit + chaos + mock tests using MSTest, Verify, WireMock

๐Ÿ”น .csproj Output Contract

Key properties:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <PackageId>ConnectSoft.Integration.MyApi</PackageId>
    <Version>1.0.87</Version>
    <Authors>ConnectSoft AI Software Factory</Authors>
    <Description>Resilient API client for MyApi with support for observability and mock testing.</Description>
    <RepositoryUrl>https://dev.azure.com/connectsoft/...</RepositoryUrl>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  </PropertyGroup>
</Project>

๐Ÿ“„ README.md Contract

Must include the following sections:

  • ๐Ÿ“Œ Purpose
  • โš™๏ธ Setup and Configuration
  • ๐Ÿ” Authentication
  • ๐Ÿš€ CI/CD and Versioning
  • ๐Ÿงช Testing Instructions
  • ๐Ÿ” Retry and Chaos Settings
  • ๐Ÿ“ˆ Observability Hooks
  • ๐Ÿ“š References

๐Ÿ“„ azure-pipelines.yml Contract

  • Stages: restore, build, test, pack, push
  • Optional: snapshot verification, chaos test pipeline
  • Emits coverage reports and trace logs

๐Ÿ“‹ .gitignore and .editorconfig

  • Standard ignore for .NET, test artifacts, .user, .vs
  • Optional editorconfig for team consistency

๐Ÿง  Short-Term and Long-Term Memory Design

๐ŸŽฏ Purpose

The agent uses short-term (contextual) and long-term (persistent) memory to:

  • Maintain state during generation
  • Reuse knowledge from past library generations
  • Auto-fill common patterns (e.g., default auth type per API)
  • Detect and correct prior errors

This memory system enhances automation, enables feedback loops, and supports traceability across the ConnectSoft factory.


๐Ÿง  Short-Term Memory

Used for:

  • Prompt context (flags, intent, planner injection)
  • Intermediate generation states
  • Transient validation results
  • Last retry reason and correction candidate
Type Implementation
Context Semantic Kernel context.Variables
Execution state Temporary in-memory JSON structure
Trace spans Propagated OpenTelemetry span context
Prompt snippets Local prompt history per skill

Example:

{
  "apiName": "HubSpot",
  "authType": "oauth2",
  "useRetry": true,
  "useChaos": false,
  "retryReason": "Missing ResiliencePolicies.cs"
}

๐Ÿง  Long-Term Memory (Knowledge Graph + Vector DB)

Stored in:

  • ๐Ÿ“š Structured JSON Knowledge Graph (e.g., Azure Table, Cosmos DB)
  • ๐Ÿ“ฆ Vector Embeddings DB (e.g., Azure Cognitive Search, Qdrant, Weaviate)

Key Dimensions:

Dimension Sample
๐Ÿ” Past Generated Libraries "ConnectSoft.Integration.Zoom"
๐Ÿงฉ Flag Sets { "authType": "oauth2", "useMock": true }
๐Ÿ” Feature Tags ["retry", "chaos", "mock", "observability"]
๐Ÿ”„ Retry Patterns "ZoomClient failed โ†’ OAuthToken injection patch"
๐Ÿ”Œ API Patterns ["GraphQL", "REST", "Paginated"]
โ›”๏ธ Failure Cases "CircuitBreaker.cs missing โ†’ regenerate"
๐Ÿ“Š Metrics avgGenerationTime, successRate, retryCount

๐Ÿ—‚ Memory Graph Sample (JSON Model)

{
  "library": "ConnectSoft.Integration.Zoom",
  "authType": "oauth2",
  "features": ["useRetry", "useMock", "useOptions"],
  "lastValidated": "2025-06-12T15:20:00Z",
  "validationStatus": "success",
  "linkedAgents": ["QAAgent", "CIOrchestratorAgent"]
}

๐Ÿ“ˆ Memory Use Cases

Use Case Description
Pre-fill defaults Automatically select OAuth2 for known APIs like Zoom
Validate structure Use prior artifact layout to verify completeness
Detect anomalies Compare current output to previous similar generation
Refactor reuse Planner queries memory to suggest reusing a known client
Avoid duplication Prevent regenerating the same client twice with same config

๐Ÿ” Authentication Method Selection and Integration

๐ŸŽฏ Purpose

This section defines how the agent supports and injects authentication strategies into the generated API library, aligning with clean architecture and ConnectSoft security-first principles. It ensures flexible and secure communication with external/internal APIs, supporting multiple token-based, header-based, or credential-based schemes.


๐Ÿ” Supported Authentication Types

Type Description Output
none No authentication Client is public, used for open APIs
apikey API key in header/query ApiKeyAuthenticationHandler.cs
oauth2 OAuth 2.0 client credentials flow OAuth2AuthenticationHandler.cs
jwt Bearer JWT token JwtAuthenticationHandler.cs
openid OpenID Connect ID token with discovery OpenIdAuthenticationHandler.cs
saml SAML assertion with encoded envelope SamlAuthenticationHandler.cs
kerberos Windows-integrated / network auth KerberosAuthenticationHandler.cs
certificate Client certificate in TLS ClientCertificateHandler.cs
basic (legacy) Base64 username/password (discouraged) BasicAuthHandler.cs

๐Ÿงฉ Internal Integration Flow

flowchart TD
    A[Input: authType flag] --> B[ResolveAuthHandlerSkill]
    B --> C[Generate DelegatingHandler]
    C --> D[Register in HttpClientFactory]
    D --> E[Inject configuration options]
    E --> F[Add to .csproj & README.md]
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿ›  Code Contracts per Auth Type

๐Ÿ”น Example: OAuth2

Generated Files:

  • OAuth2AuthenticationHandler.cs
  • OAuth2Options.cs
  • IOAuth2TokenProvider.cs (from shared library or template)
  • IOptions<OAuth2Options> DI binding

Code Snippet:

public class OAuth2AuthenticationHandler : DelegatingHandler
{
    private readonly IOAuth2TokenProvider tokenProvider;

    public OAuth2AuthenticationHandler(IOAuth2TokenProvider tokenProvider)
    {
        this.tokenProvider = tokenProvider;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = await tokenProvider.GetTokenAsync();
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return await base.SendAsync(request, cancellationToken);
    }
}

โš™๏ธ Configuration Binding

All auth types use the IOptions<T> pattern with validated config sections:

{
  "Authentication": {
    "Type": "OAuth2",
    "ClientId": "<YOUR_CLIENT_ID>",
    "ClientSecret": "<YOUR_CLIENT_SECRET>",
    "TokenEndpoint": "https://provider.com/oauth/token",
    "Scopes": ["api.read", "api.write"]
  }
}

๐Ÿ“„ Documentation Injection

Generated README.md includes:

  • Explanation of selected auth type
  • Sample configuration
  • Security best practices
  • Link to token providers or SSO documentation

๐Ÿง  Smart Selection (via memory + planner)

If user says:

โ€œCreate a Zoom API wrapperโ€

Then:

  • Agent looks up Zoom โ†’ authType: oauth2
  • Injects OAuth2 handler by default
  • Skips asking unless user overrides with authType=apikey

โ™ป๏ธ Resilience Strategy Generation (Polly Layers)

๐ŸŽฏ Purpose

This section defines how the agent integrates resilience policies using Polly into the generated API client. These strategies ensure robustness under failure scenarios like timeouts, retries, circuit breaking, and transient faults โ€” fully aligned with ConnectSoft's Resiliency-First principle.


๐Ÿ›  Polly-Based Strategies Supported

Strategy Description Trigger Flag File
Retry Retries failed requests with exponential backoff --useRetry RetryPolicy.cs
Circuit Breaker Stops requests temporarily after failures --useCircuitBreaker CircuitBreakerPolicy.cs
Fallback Returns fallback response on failure (derived from memory or context) FallbackPolicy.cs
Timeout Cancels slow requests via timeout Auto-enabled TimeoutPolicy.cs
Hedging Runs multiple requests concurrently for redundancy --multiHost or --hedgePolicy HedgingPolicy.cs
Chaos Injects latency/errors for testing --useChaos ChaosPolicy.cs

๐Ÿงฑ Resilience Layer Architecture

MyApiClient
 โ””โ”€โ”€ IHttpClientFactory
     โ””โ”€โ”€ HttpClient(name)
         โ”œโ”€โ”€ AuthenticationHandler
         โ”œโ”€โ”€ ObservabilityHandler
         โ””โ”€โ”€ PolicyHandler (Polly)
              โ”œโ”€โ”€ Retry
              โ”œโ”€โ”€ Circuit Breaker
              โ”œโ”€โ”€ Timeout
              โ””โ”€โ”€ Hedging (if enabled)

๐Ÿ“ Generated Code Files

File Description
ResiliencePolicies.cs Composite policy registration and wiring
RetryPolicy.cs Retry with jittered backoff
CircuitBreakerPolicy.cs Trip threshold config + open delay
TimeoutPolicy.cs Timeout duration logic
ChaosPolicy.cs Latency + random failure injection (only if useChaos=true)

๐Ÿงฉ Retry Example (Exponential Backoff)

return HttpPolicyExtensions
    .HandleTransientHttpError()
    .WaitAndRetryAsync(
        retryCount: 3,
        sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
        onRetry: (outcome, timespan, retryAttempt, context) =>
        {
            logger.LogWarning($"Retry {retryAttempt} after {timespan.TotalSeconds}s due to {outcome.Exception?.Message}");
        });

โš™๏ธ DI & HttpClient Registration Example

services.AddHttpClient<IMyApiClient, MyApiClient>()
    .AddHttpMessageHandler<OAuth2AuthenticationHandler>()
    .AddPolicyHandler(ResiliencePolicies.GetCombinedPolicy());

๐Ÿ“„ README Injection

Agent documents:

  • All enabled resilience policies
  • How to tune retry/circuit breaker config
  • Example fallback messages
  • Chaos testing usage

๐Ÿง  Smart Flag Rules

  • If useChaos=true, useRetry is automatically enforced
  • If authType is not none, circuit breaker is recommended
  • multiHost=true injects hedging policy scaffold

๐Ÿ“ˆ Observability Hooks (Logging, Tracing, Metrics)

๐ŸŽฏ Purpose

This section defines how the agent generates and wires observability capabilities into the API library, allowing it to emit structured logs, distributed traces, and Prometheus/OpenTelemetry-compatible metrics. This aligns with ConnectSoftโ€™s Observability-First design principle.


๐Ÿ” Observability Dimensions

Dimension Mechanism Flag
Logging ILogger<T> using Serilog or Microsoft.Extensions.Logging --useLogging
Tracing OpenTelemetry activity spans + baggage/context propagation Always-on
Metrics Prometheus + OTel counters/timers using IMeterFactory --useMetrics

๐Ÿงฑ Observability Code Structure

ConnectSoft.Integration.MyApi/
โ”œโ”€โ”€ Observability/
โ”‚   โ”œโ”€โ”€ Observability.cs
โ”‚   โ”œโ”€โ”€ MyApiClientLogging.cs
โ”‚   โ””โ”€โ”€ MyApiMetrics.cs

๐Ÿชต Logging Contract

  • All logs follow structured format with fields:
    • HttpClientName
    • OperationName
    • RetryAttempt
    • CorrelationId
  • Levels:
    • Trace โ†’ Request start/finish
    • Warning โ†’ Retry attempt
    • Error โ†’ Exception fallback or circuit break open

Sample:

_logger.LogTrace("Sending request to {Url}", request.RequestUri);
_logger.LogWarning("Retrying due to error: {Error}", ex.Message);

๐Ÿงต Tracing (OpenTelemetry)

  • ActivitySource emitted per client
  • Spans: api.request.start, api.request.retry, api.request.fail
  • Tags:
    • http.url, http.status_code, api.retry_count
  • Propagated headers: traceparent, correlation-id, etc.

Sample:

using var activity = _activitySource.StartActivity("Zoom.GetMeeting");
activity?.SetTag("http.method", request.Method.Method);
activity?.SetTag("retry", retryCount);

๐Ÿ“Š Metrics (OpenTelemetry Metrics)

  • Auto-registered IMeter and Counter<long> for:
    • api_client_requests_total
    • api_client_failures_total
    • api_client_duration_ms

Sample:

_clientMetrics.Requests.Add(1, new("endpoint", "GetUser"));
_clientMetrics.Duration.Record(stopwatch.ElapsedMilliseconds, new("endpoint", "GetUser"));

๐Ÿ“ฆ Dependency Configuration

  • DI registered from ObservabilityModule.cs
  • Includes setup for:
    • ILogger<MyApiClient>
    • IMeterFactory
    • ActivitySource

๐Ÿ“„ README.md Additions

Section Content
Logging Log levels, sample messages, how to enable Serilog sinks
Tracing Explains span emission and distributed trace support
Metrics Example metrics, Prometheus scraping, Grafana dashboard link

๐Ÿง  Memory/Planner Enhancements

If prompt includes:

โ€œSupport for debugging, monitoring, or telemetryโ€

Agent automatically enables --useLogging --useMetrics.


๐Ÿงช Mock Server and Testing Output

๐ŸŽฏ Purpose

This section describes how the agent generates a fully isolated mock server and a suite of automated tests for validating the generated API library. It ensures repeatable, side-effect-free tests using mocks and wire formats, enforcing ConnectSoft's Testability-First and Contract-Driven Development principles.


๐Ÿงฑ Mock Server Structure

Component File Description
WireMock Server MyApiMockServer.cs Starts WireMock.NET server with scenario mappings
Mappings MockDefinitions/*.json Endpoint-specific mocks
Fixture Setup MockServerFixture.cs Shared test context for parallel-safe mocks
Configuration mocksettings.json Port, host, startup delay, chaos injection toggles

๐Ÿ“ Directory Layout

ConnectSoft.Integration.MyApi/
โ””โ”€โ”€ MockServer/
    โ”œโ”€โ”€ MyApiMockServer.cs
    โ”œโ”€โ”€ MockServerFixture.cs
    โ”œโ”€โ”€ mocksettings.json
    โ””โ”€โ”€ MockDefinitions/
        โ”œโ”€โ”€ GetUser.json
        โ””โ”€โ”€ CreateOrder.json

๐Ÿงช Test Output (MSTest + Verify)

Type File Description
Unit Test MyApiClientTests.cs Tests with dependency injection mocks
Mock Integration MockTests.cs Real calls against mock server
Chaos Tests ChaosTests.cs Verifies failure handling, retry, circuit breaker
Snapshot Tests VerifyResponses.cs JSON output validation using Verify
Error Scenarios ErrorHandlingTests.cs Simulates timeouts, malformed responses, etc.

๐Ÿ” Mock Behavior

  • Based on WireMockServer with route-specific configuration
  • Supports:
    • Static responses
    • Dynamic responses via template interpolation
    • Response delays
    • Forced errors (status 500, 429, timeout)
server
  .Given(Request.Create().WithPath("/users/1").UsingGet())
  .RespondWith(Response.Create().WithStatusCode(200)
      .WithHeader("Content-Type", "application/json")
      .WithBody("{ \"id\": 1, \"name\": \"Test User\" }"));

๐Ÿ”ฌ Test Runner Integration

  • dotnet test detects and executes all tests in *.Tests project
  • WireMock server is spun up in-memory or on a fixed port
  • Tests can be run in CI pipeline using parallel-safe execution

๐Ÿ“„ README.md Enhancements

Sections added:

  • Running tests locally with mocks
  • Mock configuration and override support
  • Testing real vs. mocked APIs
  • Snapshot-based regression strategy
  • Known limitations (e.g., streaming APIs not supported in mocks)

๐Ÿง  Planner and Memory-Driven Additions

  • If prompt includes โ€œinclude mock serverโ€, agent auto-activates:
    • --useMock
    • --useRetry (ensures retry logic works with mock delay injection)
  • Agent remembers failure patterns (e.g., missing mock config) and regenerates fixtures accordingly

๐Ÿš€ CI/CD Pipeline Generation and Enrichment

๐ŸŽฏ Purpose

This section defines how the agent generates a production-grade Azure DevOps pipeline (YAML-based) for the API library. The pipeline enforces automation of build, test, packaging, and publishing steps, with optional support for mocking, chaos testing, and static analysis โ€” aligned with ConnectSoftโ€™s Automation-First and Security-First principles.


๐Ÿ“„ Generated File: azure-pipelines.yml

Location: Root of the solution folder Target CI Provider: Azure DevOps CI/CD Integration Points:

  • NuGet internal publishing
  • Build artifact generation
  • Test and snapshot validation
  • Optional Preview release tagging

๐Ÿงฑ Pipeline Structure (Default)

trigger:
  branches:
    include:
      - main
      - release/*

variables:
  DOTNET_VERSION: '8.x'
  BUILD_CONFIGURATION: 'Release'

pool:
  vmImage: 'windows-latest'

stages:
  - stage: Build
    jobs:
      - job: Build
        steps:
          - task: UseDotNet@2
            inputs:
              version: $(DOTNET_VERSION)
          - script: dotnet restore
          - script: dotnet build --configuration $(BUILD_CONFIGURATION)

  - stage: Test
    jobs:
      - job: Test
        steps:
          - script: dotnet test --configuration $(BUILD_CONFIGURATION) --collect:"Code Coverage"

  - stage: Package
    condition: succeeded()
    jobs:
      - job: Pack
        steps:
          - script: dotnet pack --no-build --configuration $(BUILD_CONFIGURATION)
          - publish: '**/*.nupkg'
            artifact: nuget-package

  - stage: Publish
    condition: succeeded()
    jobs:
      - job: NugetPush
        steps:
          - script: dotnet nuget push $(Pipeline.Workspace)/**/*.nupkg --source "<FEED_URL>" --api-key "<API_KEY>"

๐Ÿงช Optional Enrichments (based on flags)

Feature YAML Additions
--useMock Add mock server boot before tests
--useChaos Inject chaos test job/stage
--verifySnapshots Run Verify diff validation
--staticAnalysis Add dotnet format or SonarCloud step
--multiTFM Add matrix strategy for multiple .NET TFMs

๐Ÿ“ฆ Artifacts and Outputs

Artifact Description
nuget-package .nupkg output of API library
test-results Test result XML and coverage reports
snapshots Snapshot diffs from Verify (if used)

๐Ÿ“‹ Sample Enrichment Snippet: Chaos Test Stage

- stage: ChaosTests
  condition: and(succeeded(), eq(variables['useChaos'], 'true'))
  jobs:
    - job: RunChaosTests
      steps:
        - script: dotnet test --filter Category=Chaos

๐Ÿง  Planner/Memory Use

If previous generation used:

  • useMock=true: auto-add mock test step
  • useChaos=true: add chaos tests
  • internalOnly=true: push to internal ConnectSoft feed only
  • --multiHost: enable matrix testing

๐Ÿ“„ README Enhancements

Includes:

  • CI/CD badge section
  • NuGet push step explanation
  • Coverage report viewer links
  • Instructions for manual local pack and push

โœ… Output Validation Rules and Post-Checks

๐ŸŽฏ Purpose

This section defines how the agent performs automated post-generation validation to ensure the produced API library meets all ConnectSoft Factory standards, covering structure, configuration, security, and testability. This step guarantees production readiness before releasing the generated code to users or CI/CD.


๐Ÿ” Validation Categories

Category Check Tool/Skill
๐Ÿ“ Project Structure Required folders and files exist ValidateProjectStructureSkill
๐Ÿ“„ Solution Consistency .sln contains all .csproj references ValidateSolutionSkill
๐Ÿ”ง Template Flags Generated output matches selected flags ValidateFeatureImplementationSkill
๐Ÿ”’ Secrets Masking No hardcoded credentials/tokens ScanForSecretsSkill
๐Ÿ” Retry/Chaos If enabled, policies present and registered CheckResiliencePolicyWiringSkill
๐Ÿงช Test Presence All required test classes exist VerifyTestCoverageSkill
๐Ÿงช Mock Validity Mock definitions match client calls WireMockValidationSkill
๐Ÿ“œ README Markdown includes all required sections CheckReadmeCompletenessSkill
๐Ÿงฌ CI Pipeline azure-pipelines.yml includes valid stages LintCiYamlSkill

๐Ÿ“‹ Example Structural Checklist

Must Exist Validation
MyApiClient.cs โœ…
I<API>Client.cs โœ…
Observability.cs โœ… if --useLogging
MockServer/ โœ… if --useMock
ChaosInjector.cs โœ… if --useChaos
*.Tests.csproj โœ…
azure-pipelines.yml โœ…

๐Ÿšจ Failure Categories and Auto-Recovery

Failure Correction
Missing handler for auth Re-run InjectAuthenticationHandlerSkill
Missing test file Auto-generate stub test
README section incomplete Patch using GenerateReadmeSkill
Retry enabled, but policy missing Regenerate ResiliencePolicies.cs
Invalid YAML syntax Fix indentation, validate using YAML Linter

๐Ÿงช Sample YAML Validation (CI Pipeline)

steps:
  - script: yamllint azure-pipelines.yml
    displayName: "Lint Azure DevOps Pipeline"

๐Ÿง  Memory and Trace Outputs

  • Validation events are logged as spans:
    • validation.structure.start
    • validation.failed.missingFile
    • validation.passed.featureFlags
  • Results are stored in vector DB with:
    • validationScore
    • missingArtifacts
    • retryTriggered = true|false

Example:

{
  "validationScore": 95,
  "missing": ["RetryPolicy.cs"],
  "retryTriggered": true
}

๐Ÿ“„ README Additions

Post-validation section includes:

  • Passed checks
  • Optional โ€œFixes appliedโ€ changelog
  • Validation result badge (โœ… Passed or โš ๏ธ Partially Repaired)

โ™ป๏ธ Retry and Self-Correction Strategy

๐ŸŽฏ Purpose

This section defines how the agent handles failures, incomplete outputs, and misalignments during or after generation. The retry mechanism ensures the agent can self-heal, auto-regenerate, or request human review based on the severity and type of error โ€” enabling robust autonomy in the ConnectSoft Factory.


๐Ÿ”„ Retry Loop Lifecycle

flowchart TD
    A[Generation Completed]
    B[Validation Phase]
    C{All Valid?}
    D[Log & Mark Success]
    E[Detect Errors]
    F[Classify Failure Type]
    G[Apply Self-Correction Plan]
    H[Regenerate Only Affected Parts]
    I[Re-Validate]
    J{Retry Limit Exceeded?}
    K[Escalate to Human-in-the-Loop]
    L[Complete With Warning]

    A --> B --> C
    C -- Yes --> D
    C -- No --> E --> F --> G --> H --> I --> C
    I -- No --> J
    J -- Yes --> K --> L
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿง  Failure Classification Model

Type Examples Auto-Correctable?
๐Ÿ”น Structural Missing file, invalid folder โœ… Yes
๐Ÿ”ธ Semantic Wrong DI registration, YAML syntax error โœ… Yes
๐Ÿ”บ Logical Missing retry block while useRetry=true โœ… Yes
๐Ÿ”ป Semantic Mismatch Wrong authType injected ๐ŸŸก Partial
โ— Critical Multiple failures, generation crash โŒ Human needed

๐Ÿ”ง Auto-Recovery Examples

Issue Correction
README.md missing Observability section Patch-in using GenerateReadmeSkill
RetryPolicy.cs missing Re-run AddResiliencePoliciesSkill
*.csproj missing test reference Inject via FixProjectReferencesSkill
azure-pipelines.yml stage misnamed Recreate pipeline via RegenerateCiYamlSkill

๐Ÿ” Retry Limits

  • ๐Ÿงฎ Default: 3 retries
  • ๐Ÿ“Š Each retry is tracked with metadata:
{
  "retryCount": 2,
  "lastFailure": "Missing Observability.cs",
  "autoRecovered": true
}

๐Ÿ” Human-in-the-Loop Escalation

If retryCount >= maxRetries or errors are critical:

  • Agent emits agent.intervention.required event
  • Optional: Sends summary to assigned engineer or Architect Agent
  • Flags retry logs + partial outputs for manual diff

๐Ÿง  Memory Logging for Retry Patterns

Field Description
lastRetryReason Textual description
correctedBy Skill used for patch
outputHash Diff between pre/post retry result
retrySuccess Boolean status

๐Ÿ“„ README Annotation

When retries were applied, include footer section:

โš ๏ธ Auto-repair applied by the Agent (v3):
- Missing RetryPolicy.cs โ†’ added
- YAML formatting fixed
- Observability file regenerated

๐Ÿค Collaboration Interfaces and Agent Interactions

๐ŸŽฏ Purpose

This section defines how the API Library Generator Agent interacts with other agents, APIs, and systems within the ConnectSoft AI Software Factory. These interfaces enable cross-agent workflows, artifact reuse, and task orchestration, forming part of the Agentic Development Lifecycle.


๐Ÿง  Directly Collaborating Agents

Agent Interaction Purpose
๐Ÿงฑ Template Resolver Agent Receives or requests .template.json and symbol map Ensures correct base template and symbol resolution
๐ŸŽฏ Planner Agent Injects intent โ†’ generate-api-library with flags Triggers execution, provides blueprint alignment
๐Ÿงช QA Agent Receives test suite โ†’ validates API client behavior Post-generation quality control
๐Ÿ” CI/CD Agent Consumes azure-pipelines.yml โ†’ integrates into factory pipeline Automates build/test/release for the generated library
๐Ÿ” Validation Agent Performs deeper static analysis, security scanning Reports findings back to planner or initiates retry
๐Ÿค– Release Manager Agent Handles versioning, tagging, changelog, and publishing to NuGet Tracks lifecycle of generated packages
๐Ÿง‘โ€๐Ÿ’ป Human-in-the-Loop Agent Escalation target in edge/failure cases Allows guided correction or manual override

๐Ÿ” Message Protocols (MCP-Oriented)

Protocol Direction Description
intent:generate-api-library โ† Planner โ†’ Generator Triggers generation with flags
event:library.generated โ†’ Generator โ†’ QA + CI/CD Agents Notifies downstream agents
query:previous-outputs โ†” Memory Interface Reuse known flags, APIs, or retry data
event:validation.failed โ†’ Validation Agent โ†’ Planner Triggers retry or human handoff
command:revalidate โ†’ Generator (self) Retry generation post-fix
log:span.execution โ†’ Tracer/Observer Agent For OpenTelemetry spans, retries, and actions

๐Ÿงฑ Shared Artifact Contracts

Artifact Consumer Agent Format
*.sln + *.csproj QA Agent, CI Agent MSBuild-compliant solution
*.nupkg Release Manager NuGet 3.0 Package
*.md (README) Docs Agent Markdown
mocksettings.json Test Runner Agent JSON
validation.json Planner Retry planning
azure-pipelines.yml DevOps Agent YAML

๐Ÿง  Agent-Aware Output Annotation

Each output includes Agent Metadata Block, e.g.:

{
  "generatedBy": "ApiLibraryGeneratorAgent",
  "agentVersion": "v1.5.7",
  "timestamp": "2025-06-14T11:20:00Z",
  "linkedAgents": ["QAAgent", "CIOrchestratorAgent", "ReleaseManagerAgent"]
}

๐Ÿ”— External API Collaboration

API Type Example Use
OpenAPI JSON Zoom, Stripe Used as generation input
GraphQL SDL GitHub API Parsed and scaffolded
Token Providers OAuth2 endpoints Used in generated clients
Prometheus Gateway Metrics Enables observability

๐Ÿ›ฐ Observability Instrumentation and Tracing Hooks

๐ŸŽฏ Purpose

This section outlines how the agent emits execution telemetry, trace spans, and logs during its generation lifecycle. It ensures that all internal steps are observable for debugging, performance analysis, and compliance auditing โ€” following ConnectSoftโ€™s Observability-First principle.


๐Ÿ“ก OpenTelemetry Integration

Type Tooling Description
Traces ActivitySource, Activity Per-agent operation span logging
Metrics Meter, Counter, Histogram Measures generation time, retries, success rate
Logs ILogger<Agent> or SK FunctionLogger Logs contextual decisions, failures, recovery attempts

๐Ÿ“ Trace Span Lifecycle

sequenceDiagram
    participant Planner
    participant Agent
    participant Validator
    participant Observer

    Planner->>Agent: trigger(generation)
    activate Agent
    Agent->>Agent: Start Span "agent.api-library.generate"
    Agent->>Agent: Load Template (span)
    Agent->>Agent: Generate Projects (span)
    Agent->>Agent: Inject Auth (span)
    Agent->>Agent: Generate Pipeline (span)
    Agent->>Validator: validate(output)
    Validator-->>Agent: report(status)
    Agent->>Agent: Finalize Span + Status
    Agent->>Observer: Emit Metric Events
    deactivate Agent
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿ”น Trace Span Tags

Each span includes:

Tag Example
agent.name ApiLibraryGeneratorAgent
agent.version v1.6.0
template.name ConnectSoft.ApiLibraryTemplate
generation.status success / retry / failure
feature.flags ["useMock","useRetry","useChaos"]
execution.time_ms 2784

๐Ÿ“Š Metrics Schema

Metric Type Dimensions
agent_api_library_generation_total Counter `status=success failure`
agent_api_library_retry_count Counter `reason=missing_file auth_error`
agent_api_library_duration_ms Histogram authType, flags
agent_api_library_validation_errors_total Counter `type=structure logic retry`

๐Ÿชต Log Levels and Examples

Level Message
Trace Injecting OAuth2 handler for HubSpot client
Info Generated 2 projects and 17 files
Warning Missing RetryPolicy.cs, initiating correction
Error Invalid pipeline YAML detected during validation

๐Ÿ“ฆ Emitted Artifacts

File Description
trace.json Full OpenTelemetry trace context (optional per run)
generation.log File-based log for full execution
metrics.prom Prometheus exposition format (if requested)

๐Ÿง  Memory Injection

Logged traces and retry results are stored in long-term memory with validation scores and retry patterns for future improvement or reuse.


๐Ÿง‘โ€๐Ÿ’ป Human Intervention Hooks and Escalation Paths

๐ŸŽฏ Purpose

This section defines how and when the API Library Generator Agent triggers human-in-the-loop (HITL) workflows โ€” enabling oversight, guided recovery, or approval during failure recovery, ambiguity resolution, or critical generation moments.

This ensures reliability while keeping control available for architects, senior engineers, or product owners.


๐Ÿง  Intervention Triggers

Trigger Type Condition Action
โŒ Hard failure Unrecoverable error after N retries Escalate to human agent
โ“ Ambiguous input Conflicting authType or unclear API schema Ask human to confirm intent
โš ๏ธ Invalid pipeline or build CI step fails lint or validation check Pause and notify
๐Ÿ”’ Secrets detection Sensitive strings found in source Mask and await approval
๐Ÿงช Test suite incomplete Critical test cases missing Generate prompt to fill gaps
๐Ÿ“ README conflict Regeneration overrides manually edited doc Trigger diff approval
๐Ÿ“ˆ High retry count > 3 retries for same error in last week Flag pattern for review

๐Ÿงฉ Human Intervention Workflow

flowchart TD
    A[Agent detects escalation condition]
    B[Logs reason + state]
    C[Notifies Human Review Portal / Engineer]
    D[Engineer reviews, approves or corrects]
    E[Agent resumes / reboots generation]

    A --> B --> C --> D --> E
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿ”” Notification Targets

Target Method
DevOps portal Comment on generation ticket (e.g., Azure DevOps work item)
Agent Console Alert in Web UI or chat-driven interface
Email/Webhook Configurable notification to team leads
GitOps approval Push to PR and require approval tag

๐Ÿ›  Review Packaged Metadata

The agent includes a traceable metadata bundle for human reviewers:

{
  "retryAttempts": 3,
  "missingFiles": ["RetryPolicy.cs"],
  "conflictingInput": "authType=none but OAuth2 endpoint provided",
  "proposedFix": "Switch to authType=oauth2",
  "allowManualPatch": true
}

โœ๏ธ Approval and Override Options

Option Description
โœ… Approve retry with suggested fix Agent will reattempt generation
๐Ÿ›  Patch inputs manually Human edits input flags, submits override
โน Cancel generation Abort and mark task failed
๐Ÿ“ Annotate feedback Suggest changes to planner or retry agent

๐Ÿง  Feedback Injection to Memory

Each human action updates vector memory:

Memory Field Example
humanApprovalReason "OAuth2 manually enforced by architect"
interventionTimestamp "2025-06-14T12:32:00Z"
patchedFields ["authType", "useChaos"]
agentRebooted true

This influences future generations and error avoidance logic.


๐Ÿ“„ README and Audit Logs

  • If human fix was applied, a โš  Human Intervention footer is added
  • Trace and logs clearly mark which output elements were human-approved

๐Ÿงฉ Integration with Template Registry and SDK Versions

๐ŸŽฏ Purpose

This section defines how the agent connects to the ConnectSoft Template Registry and aligns generated code with approved SDK versions, NuGet packages, and shared library constraints. This guarantees version consistency, cross-library compatibility, and upgradability across the platform.


๐Ÿ— Template Registry Integration

The agent resolves templates via the ConnectSoft Template Resolver Agent and MCP-compatible metadata schemas.

Source Format Example
template.json Standardized metadata Includes identity, shortName, symbolMap, tags
Registry Index JSON over HTTP or local file Lists all available templates and versions
SDK Constraint File YAML/JSON version lock Defines min/max SDK versions and package pins

๐Ÿ”– Example Template Metadata (Resolved)

{
  "identity": "ConnectSoft.ApiLibraryTemplate",
  "version": "2.1.0",
  "sdk": "8.0",
  "defaultSymbols": {
    "authType": "oauth2",
    "useChaos": false,
    "useRetry": true
  }
}

๐Ÿงฉ Template Compatibility Matrix

Property Source Description
sdkVersion Template metadata Used to pin .NET SDK in global.json and pipeline
minSKVersion Template Ensures Semantic Kernel compatibility
packageMap Registry or template file Maps NuGet packages to allowed versions
featuresAvailable Registry Enables conditional flags (e.g., chaos only in v2.0+)

๐Ÿ“ Output Injections Based on Registry

File Registry Data Injected
.template.json Template version, symbol map
.csproj Version-pinned dependencies
global.json SDK version
azure-pipelines.yml UseDotNet@2 version set from registry
README.md Template version + date of generation

๐Ÿ”ง Sample SDK Injection

global.json

{
  "sdk": {
    "version": "8.0.203"
  }
}

Directory.Packages.props

<ItemGroup>
  <PackageVersion Include="Microsoft.Extensions.Http.Polly" Version="8.0.0" />
  <PackageVersion Include="WireMock.Net" Version="1.5.32" />
</ItemGroup>

๐Ÿง  Template-Aware Feature Flags

When generating with:

dotnet new api-library --authType none --useChaos true

Agent resolves:

  • Does current template version support useChaos?
  • If not, it logs:

"Flag 'useChaos' is not supported in template version 1.3.4. Upgrade to 2.0+"


๐Ÿง  Memory and Registry Alignment

Memory Role Example
Last used version ConnectSoft.ApiLibraryTemplate@2.0.1
Failed version attempts 1.3.0 (retry due to YAML incompatibility)
Preferred registry path https://templates.connectsoft.dev/index.json

๐Ÿท Licensing, Versioning, and Artifact Metadata

๐ŸŽฏ Purpose

This section ensures the generated API library includes proper open-source or commercial licensing, adheres to consistent versioning schemes, and embeds standardized metadata in all build and packaging artifacts โ€” aligned with ConnectSoft's factory governance and publishing protocols.


๐Ÿ“„ Licensing Strategies

License Type Flag Result
MIT --license mit (default) Adds LICENSE, PackageLicenseExpression=MIT
Apache 2.0 --license apache Adds LICENSE, copyright
Proprietary --license proprietary Adds legal block, excludes license file
Custom --license-path ./custom/LICENSE.txt Injects custom license content

LICENSE Template Example:

MIT License

Copyright (c) 2025 ConnectSoft

Permission is hereby granted, free of charge, ...

๐Ÿงฎ Semantic Versioning Strategy

Component Source Rule
Package version template.json + Git tag Format: 1.0.0, 1.1.0-preview.2
GitVersioning Optional integration Auto-inferred from branch/tag
Assembly version .csproj metadata Aligned with NuGet version
Output artifact name Used in CI/CD ConnectSoft.Integration.Zoom.1.0.0.nupkg

Sample CI Injection:

dotnet pack -p:PackageVersion=1.2.0 -p:IncludeSymbols=true

๐Ÿ“ฆ NuGet Metadata Fields

Field Value
Authors "ConnectSoft Factory"
Company "ConnectSoft Ltd"
RepositoryUrl GitHub or internal DevOps URL
PackageTags "integration;api-client;resilient;observable"
PackageProjectUrl Docs or readme link
Description Auto-generated from API summary

๐Ÿ“ Injected Files

File Description
LICENSE Legal license file
CHANGELOG.md Human-readable version history
Directory.Build.props Package metadata for all projects
version.json Machine-readable version metadata
README.md Footer includes version, template, license info

๐Ÿง  Memory and Planner Use

  • Last published version for same API is recorded
  • Planner can auto-increment patch version if none provided
  • If --forceVersion 1.0.0 is specified, memory checks prevent overwrite unless --allowOverwrite is also set

๐Ÿงพ Sample version.json Output

{
  "library": "ConnectSoft.Integration.Zoom",
  "version": "1.2.0",
  "generatedBy": "ApiLibraryGeneratorAgent",
  "template": "ConnectSoft.ApiLibraryTemplate@2.0.1",
  "sdk": "8.0.203",
  "license": "MIT",
  "timestamp": "2025-06-14T12:55:00Z"
}

---

๐Ÿ“ฆ Version: 1.2.0  
๐Ÿงฑ Template: ConnectSoft.ApiLibraryTemplate@2.0.1  
๐Ÿ“œ License: MIT  
๐Ÿง  Generated by: ConnectSoft API Library Generator Agent (v1.6.0)  

๐Ÿงฉ Multi-Tenant Compatibility and Extensibility Points

๐ŸŽฏ Purpose

This section ensures that the generated API library supports multi-tenant SaaS integration patterns and provides built-in extensibility hooks for ConnectSoft developers and downstream agents to customize, override, or extend behavior โ€” in line with Clean Architecture and Open/Closed principles.


๐Ÿข Multi-Tenant Design Patterns

Feature Description Result
๐Ÿท Tenant-Aware Headers Adds X-Tenant-ID, X-Org-ID, or configurable keys Injected into all outgoing HTTP requests
๐Ÿง  Context Injection Supports ITenantContext abstraction Enables DI-based tenant resolution
๐Ÿ” Token Scoping Token scopes can be tenant-aware (e.g., per-tenant token cache) Optional per-tenant OAuth2 strategy
๐Ÿงพ Logging Enrichment Tenant ID included in logs, traces, metrics Used for traceability per tenant
๐Ÿ”„ Retry and Throttling Policies Adjustable per tenant or tier Can be injected dynamically based on plan/edition

๐Ÿงฌ Generated Code: Tenant Hook Injection

ITenantContext.cs

public interface ITenantContext
{
    string TenantId { get; }
    string Environment { get; }
}

TenantAwareHttpHandler.cs

public class TenantAwareHttpHandler : DelegatingHandler
{
    private readonly ITenantContext tenantContext;

    public TenantAwareHttpHandler(ITenantContext tenantContext)
    {
        this.tenantContext = tenantContext;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Add("X-Tenant-ID", tenantContext.TenantId);
        return base.SendAsync(request, cancellationToken);
    }
}

๐Ÿงฉ Extensibility Points

Hook Description Pattern
IAuthTokenProvider Override auth acquisition Strategy pattern
IRequestModifier Customize headers/query/payload pre-send DI injectable
IResponseTransformer Adjust raw responses to domain types Adapter pattern
AddCustomPolicies() Inject extra Polly policies Optional delegate
HttpClientBuilderExtensions Add/remove handlers or tracing Fluent customization hook
MockResponseProvider Override mock return logic (test only) Virtual methods or DI

๐Ÿ“„ README Additions

Multi-Tenant Support: This API library is tenant-aware. To integrate with your SaaS platform, implement the ITenantContext interface and register your multi-tenant resolver.


๐Ÿง  Planner and Agent Collaboration

  • Planner tags clients that require multi-tenant support
  • Generator agent injects ITenantContext + conditional handler
  • Retry agent uses tenant tier to auto-scale policies (e.g., Bronze vs. Platinum retry count)

๐Ÿง  Memory Trace Example

{
  "tenantEnabled": true,
  "injectedInterfaces": ["ITenantContext", "IRequestModifier"],
  "customizationHooks": ["AddCustomPolicies", "TenantAwareHttpHandler"]
}

๐Ÿง  Final Summary, Self-Description, and Agent Metadata Blueprint

๐ŸŽฏ Purpose

This final section consolidates the agentโ€™s identity, purpose, capabilities, interfaces, and metadata schema into a complete self-description. It enables agent discovery, orchestration, self-awareness, and integration into ConnectSoftโ€™s Agent Registry and MCP-based orchestration layer.


๐Ÿงพ Agent Metadata Blueprint (MCP-Compatible)

{
  "id": "agent.api-library-generator",
  "name": "API Library Generator Agent",
  "version": "1.6.0",
  "description": "Generates robust, testable, and tenant-aware API integration libraries with built-in observability, CI/CD pipelines, and mock infrastructure.",
  "cluster": "software-engineering.backend",
  "inputSchema": {
    "apiType": "rest|graphql",
    "authType": "none|apikey|oauth2",
    "flags": [
      "useMock",
      "useRetry",
      "useChaos",
      "useMetrics",
      "multiHost"
    ]
  },
  "output": [
    "*.sln",
    "*.csproj",
    "MyApiClient.cs",
    "Observability.cs",
    "README.md",
    "LICENSE",
    "azure-pipelines.yml",
    "*.Tests/",
    "MockServer/",
    "version.json"
  ],
  "skillsUsed": [
    "TemplateResolutionSkill",
    "GenerateHttpClientSkill",
    "InjectAuthenticationSkill",
    "AddResiliencePoliciesSkill",
    "GenerateObservabilitySkill",
    "GenerateTestsAndMocksSkill",
    "BuildPipelineSkill",
    "ValidateOutputSkill",
    "SelfCorrectionSkill",
    "EmitTelemetrySkill"
  ],
  "collaborators": [
    "TemplateResolverAgent",
    "QAAgent",
    "CIOrchestratorAgent",
    "ReleaseManagerAgent",
    "ValidationAgent",
    "HumanInLoopAgent"
  ],
  "memory": {
    "shortTerm": "context window + prompt",
    "longTerm": "validation traces, retry logs, prior runs, diff metadata"
  },
  "license": "MIT or as specified by flag",
  "observability": {
    "otelSpans": true,
    "metrics": true,
    "logs": true
  },
  "extensibilityHooks": [
    "ITenantContext",
    "IRequestModifier",
    "AddCustomPolicies"
  ]
}

๐Ÿ“Œ System Prompt

You are the API Library Generator Agent inside ConnectSoft AI Software Factory. Your task is to generate resilient, observable, multi-tenant-capable API libraries with full test, mock, and CI/CD support. Follow clean architecture, .NET 8 SDK, Semantic Kernel conventions, and enforce security and automation defaults. Collaborate with downstream agents, validate your outputs, and retry when necessary.

๐Ÿง  Self-Description Summary

Category Description
Role Backend engineering agent
Core Output .NET 8 API integration library (NuGet-ready)
Built-In Layers Auth, Retry, Logging, Tracing, Metrics, Mocks, CI
Customizable Token providers, policies, tenant resolution
Validation Structural, semantic, retry with auto-repair
Traceability Fully traced with span, logs, retry metadata
Deployment Ready Includes Azure pipeline, packaging, tagging
Interoperable Collaborates with >6 other agents
Memory-Aware Learns from failures, adjusts future behavior