๐ 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
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.,
UseChaosrequiresUseRetry) - 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
๐ Sample Memory Graph Links¶
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
๐ 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
๐งฉ 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):
- Agent logs failure and trace (
output.validation.failed) - Root cause is inferred via
ValidateApiLibraryOutputSkill - Agent invokes
RetryFailedOutputSkillwith adaptive correction - 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=trueif 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
editorconfigfor 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]
๐ Code Contracts per Auth Type¶
๐น Example: OAuth2¶
Generated Files:
OAuth2AuthenticationHandler.csOAuth2Options.csIOAuth2TokenProvider.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,useRetryis automatically enforced - If
authTypeis notnone, circuit breaker is recommended multiHost=trueinjects 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:
HttpClientNameOperationNameRetryAttemptCorrelationId
- Levels:
Traceโ Request start/finishWarningโ Retry attemptErrorโ 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)¶
ActivitySourceemitted 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
IMeterandCounter<long>for:api_client_requests_totalapi_client_failures_totalapi_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>IMeterFactoryActivitySource
๐ 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
WireMockServerwith 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 testdetects and executes all tests in*.Testsproject- 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
Previewrelease 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 stepuseChaos=true: add chaos testsinternalOnly=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)¶
๐ง Memory and Trace Outputs¶
- Validation events are logged as spans:
validation.structure.startvalidation.failed.missingFilevalidation.passed.featureFlags
- Results are stored in vector DB with:
validationScoremissingArtifactsretryTriggered = true|false
Example:
๐ 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
๐ง 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:
๐ Human-in-the-Loop Escalation¶
If retryCount >= maxRetries or errors are critical:
- Agent emits
agent.intervention.requiredevent - 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
๐น 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
๐ 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 Interventionfooter 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
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:
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:
๐งฎ 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:
๐ฆ 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.0is specified, memory checks prevent overwrite unless--allowOverwriteis 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"
}
๐ README Footer¶
---
๐ฆ 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
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
ITenantContextinterface 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 |