Tuesday, November 24, 2026

From Local Beans to an Official MCP Agent Registry: Building a Distributed, Human-on-the-Loop AIOps Governance Platform

From Local Beans to an Official MCP Agent Registry: Building a Distributed, Human-on-the-Loop AIOps Governance Platform
AIOps Model Context Protocol MCP Registry Spring AI Jaeger Milvus RAG NVIDIA Jetson Orin Human-in-the-Loop Vibe Coding

From Local Beans to an Official MCP Agent Registry: Building a Distributed, Human-on-the-Loop AIOps Governance Platform

Transparency Disclaimer: I did not write a single line of code for this project. Every Java class, Docker Compose configuration, MCP server registration manifest, and frontend script in the aiops-governance-orchestrator repository was generated by Google AI based on my architectural requirements, iterative testing, and operational feedback.

1. Why Hardcoded Agents Hit a Wall

In Phase 1 of building the AIOps Governance Operations Center, all specialist agents—telemetry scouts, latency/error analysts, and remediation executors—lived as local Spring @Component beans inside a single JVM (:8085). While convenient for an initial prototype, coupling agents inside one application meant adding a new diagnostic specialist or upgrading an agent required recompiling and redeploying the entire orchestrator.

In Phase 2, the platform evolved into a distributed, polyglot agent ecosystem powered by the Official Model Context Protocol (MCP) Registry (:8090). Specialist agents now run as standalone containerized MCP servers (:8091, :8092, :8093), self-publish their capabilities and routing metadata on startup, and are discovered dynamically at runtime over MCP Server-Sent Events (SSE).

AIOps Governance & Official MCP Registry Distributed Architecture
Figure 1: Distributed AIOps Governance Architecture with Official MCP Registry (:8090), Standalone MCP Agents (:8091–:8093), Jaeger, Milvus, and NVIDIA Jetson Orin GPU.

2. Complete Service & Port Reference

Component Port Role in the Architecture
aiops-governance-orchestrator :8085 Core control plane, Operations Center Web UI, TelemetryScoutAgent, McpRegistryClient, and PolicyGatekeeperAgent.
Official MCP Registry :8090 Upstream Go-based MCP Registry (modelcontextprotocol/registry) serving POST /v0/publish and GET /v0/servers.
Registry PostgreSQL :5433 Stores published ServerJSON manifests, SSE URLs, tool names, match keywords, and routing priorities.
security-analyst-mcp :8091 Standalone Spring AI MCP server specializing in admin, auth, and forbidden span anomalies (priority: 5).
latency-analyst-mcp :8092 Standalone Spring AI MCP server specializing in latency SLO violations and HTTP 5xx errors (priority: 10).
remediation-executor-mcp :8093 Standalone Spring AI MCP executor handling approved actions (OPEN_CIRCUIT_BREAKER, CLEAR_CACHE).
geo-time-mcp-server :8083 Monitored Spring Boot microservice exposing /api/admin/remediate for live circuit-breaker control.
jaeger-aiops-guardian :8084 MCP bridge querying Jaeger traces and exposing structured span summaries to TelemetryScoutAgent.
Jaeger UI / Query :16686 / :16685 Distributed trace ingestion, visualization, and span latency/error lookup.
Milvus Vector DB / Attu :19530 / :8000 Vector storage for application-specific runbooks and SLO evaluation criteria (Attu provides the visual UI).
NVIDIA Jetson Orin (Ollama) :11434 Edge GPU inference running qwen2.5:3b for root-cause diagnosis and nomic-embed-text for RAG embeddings.

3. End-to-End Incident Detection & Execution Flow

During a governance scan, the orchestrator coordinates telemetry inspection, dynamic agent discovery, edge GPU reasoning, and human sign-off—recording exact millisecond durations for every stage and every Jaeger span segment.

End-to-End AIOps Incident Detection, MCP Discovery & Human-on-the-Loop Approval Sequence
Figure 2: Step-by-step incident detection, MCP Registry discovery, Jetson Orin GPU inference, and Human-on-the-Loop remediation sequence with real execution timings.
Stage 1 • Scout
39 ms
TelemetryScoutAgent queries Jaeger and extracts anomalous spans.
Stage 2 • MCP Analyst
~1.5 s warm
latency-analyst-mcp (:8092) diagnoses root cause on Jetson Orin GPU (12,411 ms cold model load).
Stage 3 • HITL Gate
< 1 ms
PolicyGatekeeperAgent pauses execution until an operator approves in the UI.
Stage 4 • MCP Executor
157 ms
remediation-executor-mcp (:8093) opens the circuit breaker on timeapi.

4. Architectural Deep Dive

What Agent Registry Is Used?

The platform runs the Official Model Context Protocol (MCP) Registry (modelcontextprotocol/registry on :8090) backed by PostgreSQL (:5433). On startup, each Spring Boot MCP agent (:8091, :8092, :8093) obtains a registry token via POST /v0/auth/none, validates its manifest against the 2025-12-11 MCP schema, and registers via POST /v0/publish. Custom routing metadata—role (ANALYST or EXECUTOR), toolName, matchKeywords, allowedActions, priority, and internalSseUrl—is stored inside _meta["io.modelcontextprotocol.registry/publisher-provided"].

How Do Jaeger and Milvus Fit Into the Architecture?

  • Jaeger (:16686) — Real-Time Anomaly Detection: Monitored applications export OpenTelemetry spans to Jaeger. During a scan, TelemetryScoutAgent fetches spans exceeding the app's sloMaxLatencyMs threshold or carrying error=true, attaching each segment (operationName, durationMs, hasError, and clickable traceId) directly to the incident card.
  • Milvus (:19530) — Context-Aware Runbook RAG: Operators upload runbooks or remediation policies in the UI (+ Upload Criteria (Milvus)). CriteriaKnowledgeService embeds the rules via nomic-embed-text on the Jetson Orin GPU and stores them in Milvus. Before calling a remote MCP analyst, the orchestrator retrieves the top matching runbook rules via vector similarity search so the LLM's recommendation respects service-specific constraints.

Where Are Jaeger Traces & Metrics Stored?

In the local Docker Compose stack, Jaeger runs as jaegertracing/all-in-one, storing trace spans in memory for fast, zero-setup local testing (traces clear when the container restarts). For persistent storage in production, switching Jaeger's SPAN_STORAGE_TYPE environment variable moves trace storage to Badger (local disk volume), Elasticsearch / OpenSearch, or Cassandra with zero changes to instrumented applications.

How Do You Adjust an Application's SLO?

  1. Open the Operations Center at http://localhost:8085 and locate the service under Onboarded Spring Boot Apps.
  2. Click Edit SLO & Policy to open the policy modal.
  3. Update Latency SLO Threshold (ms) (sloMaxLatencyMs), Allowed Actions, Evaluation Criteria, or the Require Human-on-the-Loop Approval toggle, then click Save Policy & SLO (POST /api/governance/apps).
  4. Subsequent governance scans immediately evaluate Jaeger spans against the updated SLO threshold.

Can You Onboard C#, Node.js, or Python Web Apps?

Yes — the orchestrator is completely language-agnostic. Any C# (.NET ASP.NET Core), Node.js (Express / NestJS), Python (FastAPI), or Go web service can be monitored as long as it fulfills two lightweight contracts:

  1. Export OpenTelemetry Traces to Jaeger: Configure the standard OpenTelemetry SDK/auto-instrumentation for C#, Node.js, or Python to export OTLP traces to Jaeger (http://localhost:4317 or :4318) with service.name matching the onboarded app name.
  2. Expose a Remediation Webhook: Expose an HTTP POST endpoint (such as /api/admin/remediate) accepting {"action": "...", "component": "..."} to toggle circuit breakers, flush caches, or adjust rate limits.
// Example C# ASP.NET Core Minimal API Remediation Webhook
app.MapPost("/api/admin/remediate", (RemediationRequest req) =>
{
    if (req.Action == "OPEN_CIRCUIT_BREAKER") CircuitBreakerState.Open(req.Component);
    if (req.Action == "CLEAR_CACHE") MemoryCacheManager.Clear(req.Component);
    return Results.Ok(new { status = "APPLIED", component = req.Component, action = req.Action });
});
// Example Node.js Express Remediation Webhook
app.post('/api/admin/remediate', (req, res) => {
  const { action, component } = req.body;
  if (action === 'OPEN_CIRCUIT_BREAKER') circuitBreakers.open(component);
  if (action === 'CLEAR_CACHE') caches.flush(component);
  res.json({ status: 'APPLIED', component, action });
});

5. Source Code Repository

Explore the full source code, Docker Compose manifests, and standalone MCP agent implementations on GitHub:
https://github.com/htotapally/aiops-governance-orchestrator.git

Sunday, November 22, 2026

From Distributed Traces to GPU-Accelerated AIOps: Building a Plug-and-Play Governance Operations Center (Part 2)

Plug-and-Play AIOps Governance: Building a Human-on-the-Loop Operations Center (Part 2)

How dynamic Spring AI routing agents, Milvus RAG evaluation criteria, and an 8 GB NVIDIA Jetson Orin Nano turn raw OpenTelemetry traces into governed, auditable incident response—with zero hand-written code.

Transparency Disclaimer: Every single line of Java, SQL, YAML, Dockerfile, and frontend code referenced in this series was entirely generated by Google AI—I did not write a single line of code myself. My role was strictly that of the systems architect: designing the topology, wiring the containers across a hybrid hardware setup, testing edge cases, and diagnosing bottlenecks. You can explore the complete source code on GitHub:

1. Recap: Why Governance Matters Beyond Auto-Remediation

In Part 1, we split workloads across a 64 GB Windows Docker Desktop host and an 8 GB NVIDIA Jetson Orin Nano GPU node (192.168.1.171:11434 running qwen2.5:3b and nomic-embed-text). When Jaeger captured a 1,024 ms trace (459eed2edf029bfc8a36ac609145caf1) breaching our 800 ms SLO, jaeger-aiops-guardian pinpointed timeapi.io and tripped its circuit breaker—dropping tail latency from 386 ms to < 5 ms via deterministic java.time.ZoneId fallback.

However, blindly auto-remediating every anomaly does not scale to production fleets. Different Spring Boot microservices have different SLO thresholds, runbook rules, and risk tolerances—and hardcoded if/else orchestrators quickly become brittle.

In Part 2, we built aiops-governance-orchestrator (:8085) from scratch around four core principles:

  • Easy Application Onboarding: Register any Spring Boot service via YAML or the Web UI with custom SLOs, allowed actions, and approval policies.
  • Per-App Evaluation Criteria in Milvus RAG: Upload Markdown, text, or JSON runbooks embedded via nomic-embed-text so each app is evaluated against its own operational rules.
  • Dual Plug-and-Play Routing Patterns: Dynamic specialist selection for both Runbook Analysts and Remediation Executors using Spring's @Order bean discovery.
  • Human-on-the-Loop (HITL) Operations Center: A lightweight Tailwind + Alpine.js web console at http://localhost:8085 that pauses high-impact actions for operator sign-off while recording a complete agentTimeline.

2. Hybrid Architecture & Dual Routing Patterns

Rather than wiring brittle point-to-point calls between agents, every specialist reads from and appends its structured findings to an immutable IncidentCase shared blackboard. TelemetryScoutAgent inspects OpenTelemetry spans from Jaeger and dynamically routes the incident through two plug-and-play Spring component registries:

  • Routing Pattern #1 (RunbookAnalystAgent): Evaluates incoming SpanSignal lists in @Order priority—dispatching security-sensitive paths to SecurityAnomalyAnalystAgent (@Order(5)), HTTP 5xx/exception traces to ErrorRunbookAnalyst (@Order(10)), and pure latency breaches to LatencyRunbookAnalyst (@Order(20)).
  • Routing Pattern #2 (RemediationAgent): Once PolicyGatekeeperAgent (or a human operator) approves the recommended action, the orchestrator dynamically selects the matching executor (CircuitBreakerRemediationAgent or CacheWarmupRemediationAgent).
Part 2 Architecture: Plug-and-Play AIOps Governance Orchestrator
Figure 1: Hybrid 64 GB Host + 8 GB NVIDIA Jetson Orin Nano architecture for aiops-governance-orchestrator (:8085), featuring dual plug-and-play routing registries, Milvus RAG criteria storage, PostgreSQL state, and an optional Bifrost AI Gateway (:18080).

3. Per-App Evaluation Criteria with Milvus RAG

To ensure each onboarded Spring Boot application is judged by its own operational runbooks rather than generic prompts, CriteriaKnowledgeService chunks uploaded runbook documents, embeds them into 768-dimensional vectors using nomic-embed-text on the Jetson Orin GPU, and stores them in Milvus (governance_criteria_rag) tagged with appName.

# Upload per-app evaluation criteria into Milvus via Jetson Orin (nomic-embed-text)
$runbook = @{
    source = "geo-time-slo-runbook.md"
    content = "Rule 1: If nominatim lookup-location spans exceed 400ms, recommend CLEAR_CACHE on nominatim.`n`nRule 2: If timeapi get-time-zone spans exceed 800ms or fail with HTTP 5xx, recommend OPEN_CIRCUIT_BREAKER on timeapi."
} | ConvertTo-Json

Invoke-RestMethod -Method Post -Uri "http://localhost:8085/api/governance/apps/geo-time-mcp-server/criteria" -ContentType "application/json" -Body $runbook

During every scan, the selected analyst queries Milvus filtered strictly by appName == policy.getAppName(), retrieving the exact runbook rules before invoking qwen2.5:3b for structured root-cause diagnosis.

4. Proving Zero-Touch Extensibility: Adding a 20-Line Security Agent

The true test of a plug-and-play architecture is adding a brand-new capability without modifying a single line of existing orchestrator code. To prove this, we dropped SecurityAnomalyAnalystAgent into the agent package at @Order(5)—giving it higher priority than both error and latency analysts whenever a Jaeger span touches an /admin or /auth path:

@Component
@Order(5) // Highest priority: evaluated before ErrorRunbookAnalyst (@Order 10) and LatencyRunbookAnalyst (@Order 20)
public class SecurityAnomalyAnalystAgent implements RunbookAnalystAgent {

    private final ChatClient chatClient;
    private final CriteriaKnowledgeService criteriaKnowledgeService;

    private record LlmDiagnosis(String severity, String summary, String rootCauseComponent, String recommendedAction) {}

    public SecurityAnomalyAnalystAgent(ChatClient.Builder builder, CriteriaKnowledgeService criteriaKnowledgeService) {
        this.chatClient = builder.build();
        this.criteriaKnowledgeService = criteriaKnowledgeService;
    }

    @Override
    public String analystType() { return "SecurityAnomalyAnalystAgent"; }

    @Override
    public boolean supports(List<SpanSignal> signals) {
        return signals.stream().anyMatch(s ->
            s.operationName().toLowerCase().contains("admin")
            || s.operationName().toLowerCase().contains("auth")
            || s.operationName().toLowerCase().contains("forbidden")
        );
    }

    @Override
    public IncidentCase analyze(AppPolicy policy, List<SpanSignal> signals) {
        String criteria = criteriaKnowledgeService.retrieveAppCriteria(
            policy.getAppName(), signals.toString(), policy.getEvaluationCriteria()
        );
        LlmDiagnosis d = chatClient.prompt()
            .user("Security Analyst for " + policy.getAppName() + ". Criteria:\n" + criteria
                + "\nSet rootCauseComponent to timeapi or nominatim. Pick action from " + policy.getAllowedActions()
                + ". Spans: " + signals)
            .call()
            .entity(LlmDiagnosis.class);

        return IncidentCase.detected(policy.getAppName(), signals)
            .withAnalysis(analystType(), d.severity(), d.summary(), d.rootCauseComponent(), d.recommendedAction());
    }
}

After rebuilding the container and triggering a request to POST /api/admin/remediate, TelemetryScoutAgent captured the http post /api/admin/remediate span (traceId: a0fef50d73d4990aab6f1945a75047c7) and automatically routed it to SecurityAnomalyAnalystAgent:

PowerShell scan output showing SecurityAnomalyAnalystAgent in agentTimeline
Figure 2: Live governance scan JSON confirming TelemetryScoutAgent detected http post /api/admin/remediate, dynamically selected SecurityAnomalyAnalystAgent, and paused at PolicyGatekeeperAgent for operator sign-off.
Zero-Touch Result: Adding SecurityAnomalyAnalystAgent required zero edits to TelemetryScoutAgent, PolicyGatekeeperAgent, GovernancePipelineService, or the frontend UI. Spring's dependency injection automatically discovered the new @Order(5) bean and placed it at the front of the routing chain.

5. Human-on-the-Loop Operations Center in Action

Opening http://localhost:8085 brings the entire governance loop into a single dark-mode dashboard. Operators can inspect all active plug-and-play agents, onboard new Spring Boot applications, upload Milvus criteria files, and review the full four-step agentTimeline before clicking Approve & Execute Remediation:

AIOps Governance Operations Center UI showing INC-0A340B71 approved and remediated
Figure 3: The AIOps Governance Operations Center (:8085) after approving incident INC-0A340B71—displaying the complete handoff from TelemetryScoutAgent → SecurityAnomalyAnalystAgent → PolicyGatekeeperAgent → CircuitBreakerRemediationAgent (REMEDIATED).

6. Looking Ahead (Part 3): Evolving Toward an External Registry

In Part 2, keeping the application and agent registry inside aiops-governance-orchestrator gave us rapid iteration and tight integration with Spring's @Order lifecycle. As the platform scales across multiple teams and production replicas, externalizing the registry is the natural next architectural phase:

Evolution Phase Architecture Pattern Key Capabilities Unlocked
Phase 1 (Part 2) In-App Registry + Spring @Order Beans Single-node deployment, zero-friction local testing, in-process specialist routing.
Phase 2 (Persistence) Externalized Policy Store (PostgreSQL :5433) Persists onboarded apps, SLOs, and IncidentCase audit logs across container restarts and replicas.
Phase 3 (Federation) External Agent & MCP Control Plane (PostgreSQL + Bifrost :18080) Standalone specialist agents self-register over HTTP/MCP while Bifrost centralizes LLM & MCP tool governance.

From Distributed Traces to GPU-Accelerated AIOps: Building a Self-Healing Microservice Architecture (Part 1)

From Distributed Traces to GPU-Accelerated AIOps: Building a Self-Healing Microservice Architecture (Part 1)
Part 1 of 2 Java 21 & Spring AI MCP Jetson Orin Nano GPU

From Distributed Traces to GPU-Accelerated AIOps: Building a Self-Healing Microservice Architecture (Part 1)

Transparency Disclaimer & Source Repositories

Every single line of Java, SQL, YAML, Dockerfile, and frontend code referenced in this series was entirely generated by Google AI—I did not write a single line of code myself. My role was strictly that of the systems architect: designing the topology, wiring the containers across a hybrid hardware setup, testing edge cases, and diagnosing bottlenecks. Explore the complete source code on GitHub:

Modern microservice architectures give engineering teams remarkable agility, but they also turn everyday latency spikes into distributed puzzles. When a downstream third-party API slows down, log lines rarely tell the whole story—instead, delays cascade across virtual threads, database checkpoints, and user-facing Service Level Objectives (SLOs).

In this two-part series, we explore how to move from passive observability to governed, AI-driven incident response:

  • Part 1 (This Post): Instrumenting a hybrid neuro-symbolic Spring Boot service with OpenTelemetry and Jaeger, offloading local LLM and embedding inference to an NVIDIA Jetson Orin Nano GPU, and building an autonomous Model Context Protocol (MCP) guardian that detects SLO breaches and trips circuit breakers automatically.
  • Part 2 (Coming Next): Building a lightweight Security & AIOps Operations Center from scratch—integrating semantic runbook retrieval via a Milvus RAG store and a Human-on-the-Loop approval console so operators can inspect evidence, approve remediations, and persist structured root-cause memories.

1. The Hybrid Hardware & Container Architecture

Rather than running heavy LLM weights on CPU alongside Docker containers, this architecture splits workloads across two nodes on the local network:

  1. Primary Host Laptop (64 GB RAM — Docker Desktop): Runs the containerized Spring Boot 3.4+ / Java 21 microservices, Jaeger (OTLP collector and trace query API), PostgreSQL (stateful Human-in-the-Loop checkpoints), and Milvus + Attu (vector storage for semantic city-alias resolution and incident runbooks).
  2. Dedicated GPU Inference Node (NVIDIA Jetson Orin Nano — 8 GB Unified RAM): Runs Ollama (dustynv/ollama with CUDA 12.6) at 100% GPU offload, serving qwen2.5:3b (2.9 GB VRAM) for structured root-cause diagnosis and nomic-embed-text (768-dimensional vectors) for semantic retrieval.
Distributed Hybrid AIOps Infrastructure Diagram showing 64GB Windows Host Laptop and 8GB NVIDIA Jetson Orin Nano GPU Node
Figure 1: Distributed Hybrid AIOps Topology — Containerized Spring Boot MCP servers, Milvus, PostgreSQL, and Jaeger on a 64 GB host paired with 100% CUDA GPU inference on an 8 GB NVIDIA Jetson Orin Nano.

2. How the Telemetry & Remediation Loop Works

Step A: Hybrid Neuro-Symbolic Execution (geo-time-mcp-server, :8083)

The monitored application (geo-time-adaptive-agent) resolves U.S. city queries into verified local times and geographic coordinates. Instead of routing every request through a slow chat loop, it uses a deterministic fast-path in Java 21 virtual threads—falling back to Milvus semantic search (nomic-embed-text) for colloquial city aliases (like "The Big Apple") and PostgreSQL HITL checkpoints when city names are ambiguous (like "Springfield").

Every inbound request and downstream external HTTP call (nominatim.openstreetmap.org and timeapi.io) is instrumented with OpenTelemetry and exported over OTLP (:4318) directly to Jaeger (:16686).

Step B: Catching a Real SLO Breach in Jaeger

Our operational SLO defines any /api/geo-time/query trace exceeding 800 ms as degraded. Below is the Jaeger span breakdown captured during testing (1.02s total duration across 12 spans):

Figure 2: Real Jaeger trace waterfall (459eed2edf029bfc8a36ac609145caf1) showing a 1,024 ms request breaching the 800 ms SLO due to combined external geocoding and time-zone API latency.

Looking at the span breakdown immediately isolates why the request crossed our 800 ms threshold:

  • Local Milvus + Jetson Embedding Lookup (resolve-city-alias → milvus query → embedding): Completed in just ~40 ms.
  • Upstream Geocoding (lookup-location): Took ~468 ms.
  • Downstream Time-Zone API (get-time-zone): Stretched out another ~386 ms at the tail end of the waterfall, pushing total end-to-end latency to 1,024 ms.

Step C: Autonomous Diagnosis & Remediation (jaeger-aiops-guardian, :8084)

Instead of waiting for a human engineer to manually click through Jaeger waterfalls at 2:00 AM, jaeger-aiops-guardian exposes Jaeger's trace API and service admin endpoints as Spring AI MCP tools (inspectServiceTraces and executeServiceRemediation):

  1. Trace Inspection: AutonomousFleetObserver queries Jaeger for traces exceeding 800 ms on geo-time-mcp-server.
  2. GPU Root-Cause Diagnosis: The slow spans are serialized and sent over the LAN to qwen2.5:3b running at 100% GPU on the Jetson Orin Nano, which identifies timeapi as the root-cause component and selects OPEN_CIRCUIT_BREAKER.
  3. Standardized Remediation: jaeger-aiops-guardian invokes POST /api/admin/remediate on geo-time-mcp-server, immediately tripping the circuit breaker:
Executed OPEN_CIRCUIT_BREAKER on geo-time-mcp-server (timeapi): {"status":"APPLIED","component":"timeapi","circuitOpen":true}
Outcome: Self-Healing Latency Recovery & Graceful Degradation

The moment OPEN_CIRCUIT_BREAKER flipped circuitOpen to true on timeapi, geo-time-mcp-server stopped blocking virtual threads on slow external HTTP calls to timeapi.io and switched seamlessly to deterministic local IANA timezone resolution (java.time.ZoneId):

Before Remediation
1,024 ms (SLO Breach)
timeapi.io Span
386 ms → < 5 ms
Post-Remediation Status
HEALTHY (< 800 ms SLO)
  • Zero User Disruption: End users continued receiving accurate, verified local time cards with zero failed requests.
  • Cascading Failure Prevention: Short-circuiting the degraded external dependency eliminated tail-latency amplification across concurrent virtual threads.
  • Closed-Loop Verification: Subsequent health scans by jaeger-aiops-guardian confirmed traces dropped back well below the 800 ms SLO threshold.

3. What's Next in Part 2: Building a Lightweight Security & AIOps Operations Center

Coming Up in Part 2

Blindly auto-remediating every anomaly works for safe, reversible actions like tripping a circuit breaker on a flaky external API—but high-impact changes require policy gates, institutional runbook knowledge, and human sign-off.

In Part 2, we will build a lightweight Security & AIOps Operations Center (:8085) from scratch to replace heavy, complex enterprise scaffolding with a transparent, self-hosted governance engine:

  • Semantic Runbook & Incident Memory (milvus-memory-broker, :8080): Grounding LLM recommendations in PDF operational manuals and past post-mortems stored in Milvus.
  • Policy-Driven Human-on-the-Loop Console (:8085): Pausing high-risk actions so an operator can review Jaeger spans, Milvus runbook citations, and Jetson GPU reasoning before clicking Approve or Reject.

Saturday, November 21, 2026

From Spaghetti Prompts to Composed Orchestration: Agentic RAG-as-a-Tool with Spring AI and Milvus

Transparency Disclaimer: The architectural diagram and the entire codebase in this project were developed by Google AI—I did not write or add a single line of code. My role was strictly that of the architect and systems thinker: defining the architectural boundaries, integrating the infrastructure components, testing edge cases, and guiding the structural refactoring. Full source code is available on GitHub at github.com/htotapally/geo-time-adaptive-agent.

In my previous post, we built a sub-second Adaptive UI on top of Java 21, Spring Boot, Spring AI, Bifrost, PostgreSQL, and local Ollama (Qwen 2.5 7B)—all available in our open-source repository at github.com/htotapally/geo-time-adaptive-agent.

Since that post, we expanded the system with local text embeddings (using embeddinggemma-2:270m and a Milvus vector database) so the agent can resolve cultural city nicknames like "The Big Easy" or "Music City" when exact geocoding lookups return zero matches.

As we added that vector fallback, I noticed a classic software engineering trap creeping into our controller: long, monolithic methods. When intent parsing, external geocoding, vector search, parallel fan-out, and Human-in-the-Loop (HITL) checkpoints all live inside one giant method, the code becomes hard to read and nearly impossible to unit test.

1. Why Monolithic Agent Methods Hurt Engineering Quality

In many AI tutorials, the main request handler turns into a sprawling wall of prompt strings, if/else branches, and inline API calls. Even when the logic works, it violates clean software design:

  • Poor Readability: You cannot tell at a glance what the high-level workflow is doing without tracing every nested conditional.
  • Broken Unit-Testability: Testing whether a >5 match guardrail triggers a PostgreSQL checkpoint forces you to mock the entire world or spin up a live LLM.
  • Hidden Architectural Patterns: Important agentic behaviors—like semantic fallback and evaluator validation—get buried in implementation noise.

2. Refactoring to a 4-Step Composed Orchestration

Applying the Composed Method pattern, we refactored GeoTimeAgentController.queryCity() so the top-level endpoint reads like a clean 4-stage architectural pipeline, delegating execution to small, atomic methods:

@PostMapping("/query")
public LocationTimeReport queryCity(@RequestBody QueryRequest request) {
    String rawQuery = request.query().trim();

    // Step 1: Hybrid Semantic Router / Intent Extraction
    ParsedIntent intent = parseIntent(rawQuery);

    // Step 2: Deterministic Tool Execution (Structured Geocoding)
    List<LocationMatch> matches = findMatchingLocations(intent);

    // Step 3: Agentic RAG-as-a-Tool (Autonomous Vector Fallback on Zero Matches)
    if (matches.isEmpty()) {
        matches = resolveViaRagFallback(rawQuery);
    }

    // Step 4: Dynamic Control Flow (Pipeline vs. Parallel Fan-Out vs. HITL Guardrail)
    String resolvedCity = matches.isEmpty() ? intent.city() : matches.get(0).city();
    return routeByAmbiguity(resolvedCity, matches);
}

4-Stage Composed Agentic Orchestration & Milvus RAG Fallback

3. How Each Atomic Step Maps to an Agentic AI Pattern

The most rewarding outcome of this refactoring was seeing that each atomic Java method evolved into a textbook Agentic AI design pattern:

Orchestration Step Agentic Design Pattern Architectural Role
1. parseIntent(rawQuery) Hybrid Semantic Router Splits structured inputs ("Gary, IN") in <1ms; routes unstructured sentences to Qwen 2.5 7B via Bifrost.
2. findMatchingLocations(intent) Deterministic MCP Tool Execution Queries live Open-Meteo geocoding APIs using strongly typed Java records rather than risking LLM hallucinations.
3. resolveViaRagFallback(rawQuery) Agentic RAG-as-a-Tool Invokes Milvus + embeddinggemma-2:270m only when exact geocoding returns 0 matches (e.g., "The Big Easy" → "New Orleans, Louisiana").
4. routeByAmbiguity(city, matches) Dynamic Control Flow & Evaluator Selects Direct Card + Evaluator (1 match), Virtual-Thread Fan-Out (2–5 matches), or PostgreSQL HITL Checkpoint (>5 matches).

4. Agentic RAG-as-a-Tool vs. Naive RAG

Traditional RAG pipelines run vector similarity search on every single user query—adding unnecessary latency and risking noisy matches even when the user typed an exact city name like "Atlanta, Georgia".

By encapsulating Milvus and local embeddinggemma-2:270m embeddings inside resolveViaRagFallback(), vector search becomes an autonomous fallback microservice: structured APIs handle exact queries in milliseconds, and semantic search triggers strictly when exact lookup comes up empty.

5. Independent Unit Testing for Every Stage

Because every stage is now a focused, single-responsibility method, you can write fast, isolated JUnit tests for each agentic behavior:

  • Test Intent Parsing: Verify parseIntent("Gary, IN") resolves deterministically without touching ChatClient.
  • Test RAG Fallback: Mock lookupLocation("The Big Easy") returning empty and assert resolveViaRagFallback() queries Milvus and resolves New Orleans.
  • Test Guardrail Routing: Pass 10 mock matches into routeByAmbiguity() and verify a PostgreSQL HITL checkpoint is created without fanning out external API calls.

Explore the Full Source Code

Inspect the complete Spring Boot 3.4+, Spring AI MCP, Milvus VectorStore, Bifrost, and Adaptive UI codebase on GitHub:

View Repository on GitHub →

Friday, November 20, 2026

Beyond the Chatbot: Building a Sub-Second Adaptive UI with Spring Boot, Bifrost, and Local LLMs

Beyond the Chatbot: Building a Sub-Second Adaptive UI with Spring Boot, Bifrost, and Local LLMs
Transparency Disclaimer Every single line of Java, SQL, YAML, and HTML/JavaScript code in this project was generated through pair-programming with Google AI. I did not write a single line of code manually. My role was strictly that of the architect and systems thinker—defining the architectural patterns, connecting the infrastructure components, testing edge cases, and diagnosing bottlenecks.

In my previous post, I explored how Agentic Orchestration is really just Service-Oriented Architecture (SOA) with an LLM control plane. Once the backend services, guardrails, and PostgreSQL checkpoints were working via MCP (Model Context Protocol), the next question was obvious: How should an actual end user interact with this system?

Most AI demos today default to a chat-first interface—a blank text box where every interaction requires typing sentences and waiting for streaming paragraphs. As an architect, that feels like a step backward. If a user simply wants the current local time in "Gary, Indiana", they don't want a conversation; they want a clean, structured UI card. They only need a chat interface when the system hits genuine ambiguity and needs human clarification.

To test this idea, I built a self-hosted Adaptive UI on top of Java 21, Spring Boot, Spring AI, Bifrost, PostgreSQL, and Ollama (Qwen 2.5 7B). Along the way, I ran straight into a 20-second latency wall—and discovered the exact hybrid pattern needed to make it 30x faster.

1. What Is an Adaptive UI?

Instead of forcing every request through a chatbot, an Adaptive UI acts like a deterministic web application when inputs are clear, and dynamically pops up a conversational modal only when the agent encounters ambiguity or requires Human-in-the-Loop (HITL) approval.

In our Spring Boot application, a single strongly typed JSON contract (LocationTimeReport) drives three completely different user experiences:

  • Mode 1 — Unambiguous Pipeline ("Gary, Indiana"): The backend resolves Lake County, Indiana (America/Chicago) and validates the offset. No chat window appears. The page immediately renders a clean, green-bordered result card with the verified local time.
  • Mode 2 — Moderate Ambiguity ("Springfield"): The backend finds 4 matching U.S. states across 3 time zones and resolves them concurrently on Java 21 Virtual Threads. A Disambiguation Modal pops up displaying clickable cards for Illinois, Missouri, Massachusetts, and Oregon. Clicking a card promotes that state straight to the main view.
  • Mode 3 — High Ambiguity & HITL Checkpoint ("Franklin" → "Virginia"): The backend hits the > 5 matches guardrail, freezes all candidate coordinates into a PostgreSQL agent_checkpoints table (PAUSED_FOR_HITL), and returns a checkpointId. An Interactive Clarification Chat Drawer pops up where typing "Virginia" resumes the saved Postgres state and transitions smoothly into the verified result card.

2. The 20-Second Latency Wake-Up Call

In my first iteration, I let Spring AI's ChatClient and Qwen 2.5 7B (running locally on Ollama behind the Bifrost AI gateway) orchestrate every single step from scratch. Even for a straightforward query like "Gary, Indiana", the UI took 15 to 25 seconds to respond.

Why? Because the system was paying for four sequential LLM inference round-trips over Docker networking:

  1. Send the prompt + 6 JSON tool schemas to Qwen 2.5 7B → model decides to call lookupLocation.
  2. Send geocoding results back to Qwen 2.5 7B → model decides to call getTimeZone.
  3. Send the IANA zone back to Qwen 2.5 7B → model decides to call getCurrentTime.
  4. Send the timestamp back to Qwen 2.5 7B → model builds the draft report, calls validateTimeReport, and serializes the final JSON.

We were using a 7-billion-parameter neural network to execute a deterministic Step 1 → Step 2 → Step 3 sequence that compiled Java bytecode can run in less than one millisecond.

3. The Fix: Hybrid Neuro-Symbolic Fast-Path

Applying the core lesson from SOA—never pay LLM latency for deterministic control flow—we refactored the Spring Boot orchestrator into a Hybrid Fast-Path:

Execution Concern Pure LLM Loop (~20s) Hybrid Fast-Path (~500ms)
Structured Routing 4 sequential LLM inference turns Compiled Java 21 branching (< 1ms)
Multi-State Fan-Out LLM parses & summarizes all branches Java 21 Virtual Threads (parallelStream)
HITL State Resume LLM re-plans tool calls from scratch Direct PostgreSQL checkpoint lookup (< 5ms)
Role of Qwen 2.5 7B Every single step (heavy bottleneck) Semantic edges only (messy intent & chat replies)

Key Architectural Takeaways

  1. Ditch "Chat-First" for Structured Workflows: Use clean UI cards for deterministic results, clickable pills for bounded choices, and pop up a conversational chat drawer only when ambiguity or human approval demands it.
  2. Code Is Commodity; Architecture Is the Differentiator: With modern AI generating the boilerplate Java, SQL, and Alpine.js/Tailwind frontend in minutes, an engineer's highest-leverage skill is knowing where to place deterministic boundaries, state checkpoints, and LLM reasoning.
  3. Hybrid Beats Pure-Agent Every Time: Pairing compiled Java 21 + PostgreSQL state with a local LLM via an AI gateway like Bifrost gives you sub-second speed on happy paths and genuine natural-language adaptability on messy edge cases.
geo-time-adaptive-agent is the link to the code.

Thursday, November 19, 2026

Agentic Orchestration Is Just SOA with an LLM Control Plane—And That’s a Good Thing

Agentic Orchestration Is Just SOA with an LLM Control Plane—And That’s a Good Thing
Transparency Disclaimer Every single line of Java, SQL, YAML, and HTML/JavaScript code in this project was generated through pair-programming with Google AI. I did not write a single line of code manually. My role was strictly that of the architect and systems thinker—defining the architectural patterns, connecting the infrastructure components, testing edge cases, and diagnosing bottlenecks.

If you have spent years building Service-Oriented Architectures (SOA), Enterprise Service Buses (ESBs), or microservice sagas, looking at modern "Agentic AI" diagrams can trigger a strong sense of déjà vu.

You have discrete services with strict schemas. You have a gateway governing routing, rate limits, and fallbacks. You have state persistence for long-running workflows, and telemetry tracking latency and failures.

Recently, I built a hands-on proof of concept to test where traditional SOA ends and true agentic orchestration begins. Using Java 21, Spring Boot, Spring AI (MCP), Bifrost, PostgreSQL, and local Ollama models (alongside Claude), I wanted to answer one question: What actually changes when you put an LLM in the driver's seat of a microservice mesh?

The short answer: The services don't change, the governance doesn't change, and state management doesn't change. What changes is who writes the glue code.


The Trap: Building a Pipeline and Calling It an "Agent"

When developers first experiment with tool-calling, they often build a fixed sequence like this:

  • LocationService(city) → returns County and State.
  • TimeZoneService(state) → returns the IANA Time Zone.
  • TimeService(zoneId) → returns the formatted local time.

If a user queries "Atlanta", the system executes Step 1 → Step 2 → Step 3 and outputs JSON.

As an architect, your immediate reaction should be: Why is there an LLM here? Every request follows the exact same compile-time path. A standard Spring Boot REST controller handles this 100x faster, cheaper, and with zero chance of hallucination.

To justify an LLM control plane, you have to introduce runtime ambiguity, split domain rules, and multi-turn state interruptions where hardcoded if/else trees become brittle.


The Architecture: Classic SOA Meets MCP

Instead of treating the LLM like magic, I structured the stack using classic SOA discipline, exposing Spring Boot services over the Model Context Protocol (MCP):

  • Service Layer (Spring Boot + Spring AI MCP): Exposes Java @Tool methods with strict Java record DTOs (LocationMatch, TimeZoneInfo, LocationTimeReport) backed by live geocoding APIs and local circuit-breaker fallbacks.
  • The ESB / AI Gateway (Bifrost): Sits in front of the MCP server and model providers—handling tool discovery, routing between local Ollama instances and Claude, rate limits, and fallback policies.
  • State & Telemetry Store (PostgreSQL): Persists workflow checkpoints for human-in-the-loop interruptions and records execution metrics.
  • The Control Plane (LLM Orchestrator): Reads the JSON contracts and dynamically decides which tools to call, when to fan out in parallel, when to self-correct, and when to pause.

Four Patterns That Prove Why the LLM Layer Matters

Once the plumbing was live, testing four specific scenarios revealed where an LLM control plane genuinely outperforms static orchestration:

1. Dynamic Supervisor-Worker Fan-Out ("Springfield")

When you query "Atlanta", the agent executes a linear 3-step chain. When you query "Springfield", LocationService returns four distinct U.S. states across three time zones (Illinois, Missouri, Massachusetts, and Oregon). Without writing a single loop in Java, the LLM acts as a Supervisor: it recognizes the ambiguity, emits parallel getTimeZone and getCurrentTime calls across all four states in a single turn (executed concurrently on Java 21 Virtual Threads), and aggregates the results into a unified JSON array.

2. Guardrail Circuit-Breakers ("Franklin")

What happens when a user queries "Franklin"—a city name that exists in over a dozen U.S. states? Without guardrails, an autonomous fan-out triggers dozens of downstream API calls and burns unnecessary tokens. By encoding a Circuit-Breaker policy (> 5 matches), the agent inspects the intermediate result count, halts the parallel fan-out immediately, and shifts strategy.

3. Stateful Human-in-the-Loop Checkpoints ("Franklin" → "Tennessee")

In traditional SOA, long-running workflows waiting on human approval use the Saga / Process Manager pattern to externalize state. I applied the exact same pattern to the agent:

  • Turn 1 (Pause): When "Franklin" hits the > 5 guardrail, the agent calls saveHitlCheckpoint(), saving the candidate list into a PostgreSQL agent_checkpoints table (status = PAUSED_FOR_HITL) and returning a checkpointId (chk-franklin-1360).
  • Turn 2 (Resume): When the user replies "Use Tennessee for checkpoint chk-franklin-1360", the agent calls resumeHitlCheckpoint(). It loads the saved candidate straight from Postgres—skipping external geocoding APIs completely—marks the row RESUMED, and finishes the calculation.

4. Evaluator-Optimizer Self-Reflection ("Gary, Indiana")

Smaller local models running on a workstation (like Gemma or Qwen via Ollama) are fast and private, but they occasionally make domain assumptions—such as assuming all of Indiana uses America/Indiana/Indianapolis, forgetting that Gary sits in Lake County (America/Chicago).

To fix this without escalating every request to a cloud model, I added a deterministic @Tool called validateTimeReport(draft). When I injected a faulty Eastern Time assumption for Gary, Indiana, the Java validator rejected it with a plain-English critique:

"Split-timezone rule violation: Lake County, Indiana must use 'America/Chicago'."

The local model read the error, autonomously queried the Central Time zone, re-validated until valid: true, and documented its own correction in the final JSON output.


How SOA Maps to Agentic Orchestration

If you are an enterprise developer transitioning into AI engineering, your SOA experience isn't obsolete—it is your biggest advantage:

Architectural Layer Traditional SOA / Microservices Agentic Orchestration
Service Contracts WSDL / OpenAPI / Protobuf MCP Tool Schemas & Java record DTOs
Gateway / ESB Kong / Apigee / MuleSoft AI Gateway (Bifrost) for routing & fallbacks
State Management Saga / BPMN Process State in DB Postgres HITL Checkpoints (PAUSED → RESUMED)
Control Flow Compile-time if/else trees Runtime LLM reasoning over tool outputs
Error Handling Static retries & Dead-Letter Queues Evaluator-Optimizer semantic self-correction

The Golden Rule

The biggest mistake engineering teams make today is replacing clean, deterministic microservice pipelines with probabilistic LLM loops.

Never use an agent where a standard REST pipeline will do. Keep your core services fast, strongly typed, and deterministic. Reserve the LLM control plane for the messy edges where rigid code breaks down: translating unstructured human intent, dynamically fanning out across ambiguous results, pausing for human clarification, and self-healing when domain rules fail.

When you treat an LLM not as a replacement for software architecture, but as a dynamic control plane sitting on top of solid SOA, you get the best of both worlds: the adaptability of AI and the reliability of enterprise engineering.

Monday, August 4, 2025

A2A SDK Function Call

Weather Tool with multiple arguments

Have started looking into google's A2A SDK.  While going through the getting started guide as provided by google, was stuck with function call, with a function having multiple arguments,  Function call example as provided by google was helpful, but it was not clear how to pass the multiple arguments while calling the tool.  Spent two days googling for the answer without luck.

Option 1 - Calling Weather Tool using a simple query 

First option that worked was just pass a single query as argument with the query containing parameters potentially matching to the function arguments.  The tool/function that was used for testing is:

# @title Define the get_weather Tool
def get_weather(city: str, country: str, unit: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city (e.g., "New York", "London", "Tokyo").
        country (str): The name of the county (e.g., "England", "Great Britan", "USA", "United States", "Japan"
        unit (str): The temperature unit, either 'Celsius' or 'Fahrenheit'.

    Returns:
        dict: A dictionary containing the weather information.
              Includes a 'status' key ('success' or 'error').
              If 'success', includes a 'report' key with weather details.
              If 'error', includes an 'error_message' key.
    """
    print(f"--- Tool: get_weather called for city: {city} ---") # Log tool execution
    print(f"country: {country}")
    print(f"unit: {unit}")
    city_normalized = city.lower().replace(" ", "") # Basic normalization

    # Mock weather data
    mock_weather_db = {
        "newyork": {"status": "success", "report": "The weather in New York is sunny with a temperature of 25°C."},
        "london": {"status": "success", "report": "It's cloudy in London with a temperature of 15°C."},
        "tokyo": {"status": "success", "report": "Tokyo is experiencing light rain and a temperature of 18°C."},
    }

    if city_normalized in mock_weather_db:
        return mock_weather_db[city_normalized]
    else:
        return {"status": "error", "error_message": f"Sorry, I don't have weather information for '{city}'."}

Code used while calling the agent is:

part = types.Part.from_text(text=query)
. . .
. . .
content = types.Content(role='user', parts=[part])

Query used

"What is the weather like in London Britan?  Temperature must be in Fahrenheit"

The output from the execution was:

>>> User Query: What is the weather like in London Britan?  Temperature must be in Fahrenheit
--- Tool: get_weather called for city: London ---
country: Great Britan
unit: Fahrenheit
<<< Agent Response: I am sorry. I cannot fulfill this request. The weather report I received is in Celsius, but you asked for Fahrenheit. I am unable to convert units.
 

Based on the results it is my understanding that the agent able extract required parameters to call the function from the query provided.  Since the implementation was independent of the unit, even though the parameter was not used anywhere in the function other than printing, it is not clear why the agent is looking for a temperature converter. 

Option 2 - Function Call

After stumbling across python api, specially

from google.genai import types

contents = types.Part.from_function_call(
name='get_weather_by_location',
args={'location': 'Boston'}
)

 I modified content generation using the following code:

 part = types.Part.from_function_call(
            name='get_weather',
            args={'city': 'London', 'unit': 'Fahrenheit'}
        )

Output from the code execution was:

>>> User Query: What is the weather like in London Britan?  Temperature must be in Fahrenheit
--- Tool: get_weather called for city: London ---
country: United Kingdom
unit: Fahrenheit
<<< Agent Response: OK. The weather in London, United Kingdom is cloudy with a temperature of 15°C.

which is inline with what was expected by the execution of a function.  No mention of temperature converter tool in the output.

Question 

It is not clear why the difference in the results is different in the two cases?