Skip to content

Workshop: Build and Register a loyalty MCP Server through Envoy

Estimated time: 15–30 minutes

In this lab you extend Esmeralda's Garimpo (a curated online secondhand and vintage store) customer-support scenario (support-assistant → order-ops-specialist) by adding a 6th MCP tool server — loyalty — and routing it end-to-end through the Envoy gateway adapter with full platform governance.

flowchart LR
    User["End User / esmeralda query"] --> SA["support-assistant<br/>(ADK, team: cx)"]
    SA -->|"A2A (allowed)"| OOS["order-ops-specialist<br/>(A2A, team: ai-coe)"]
    SA -.->|"MCP (403 denied at Agent Gateway)"| AGW["Central Agent Gateway"]
    OOS -->|"MCP + ID token (allowed)"| AGW --> Envoy["Envoy Adapter<br/>(esmeralda.usage metering)"]
    Envoy --> Loyalty["loyalty MCP Server<br/>(Cloud Run + CallerGuard)"]

What You Will Build & Verify

  1. Scaffold & code (5 min): Copy apps/services/_template/ into apps/services/loyalty/, implement get_loyalty_balance and redeem_points, update tools.json, and run pytest.
  2. Test locally (5 min): Register port 8016 in local_mcp.py, wire loyalty into order-ops-specialist, and test locally with esmeralda query --local-mcp.
  3. Register in Catalog & Route via Envoy (5 min): Declare catalog/teams/ai-coe/mcp/loyalty.yaml, route loyalty through envoy in dev, and compile the resolved catalog.
  4. Deploy & Verify Governance (10 min): Deploy with the shared mcp-service Terraform module and verify CallerGuard + X-Esmeralda-Billed-Team, Envoy esmeralda.usage logs, and Agent Gateway 403 enforcement for support-assistant.

Prerequisites

  • An Esmeralda checkout with uv installed (always pass --frozen so uv.lock is not rewritten locally).
  • For Step 4 (cloud deployment), a deployed dev environment where uv run --frozen esmeralda verify --env dev --scenario store already passes.

Step 1: Scaffold & Implement loyalty (5 min)

Copy the self-contained MCP starter template to create apps/services/loyalty/:

cp -r apps/services/_template apps/services/loyalty

The template already includes:

  • main.py — FastMCP mounted at /mcp (stateless_http=True, json_response=True, host_origin_protection=False), GET /health, OpenTelemetry via otel_setup.py, and app = CallerGuard(_starlette).
  • caller_guard.py — byte-identical vendored copy of esmeralda.attribution (do not edit this file; guard tests verify it stays identical).
  • otel_setup.py, tools.json, test_main.py, pyproject.toml, and Dockerfile.

1.1 Implement the loyalty tools

Update apps/services/loyalty/pyproject.toml so name = "loyalty", then replace the example tool in apps/services/loyalty/main.py with two Garimpo loyalty tools using the synthetic customer IDs (CUST-1001 through CUST-1004):

BALANCES: dict[str, dict[str, object]] = {
    "CUST-1001": {"customer_name": "Camila Rocha", "tier": "gold", "points": 2450},
    "CUST-1002": {"customer_name": "Mateo Alvarez", "tier": "platinum", "points": 8200},
    "CUST-1003": {"customer_name": "Priya Nair", "tier": "standard", "points": 410},
    "CUST-1004": {"customer_name": "Lucas Meyer", "tier": "standard", "points": 900},
}


@mcp.tool()
def get_loyalty_balance(customer_id: str) -> dict:
    """Return the Garimpo loyalty tier and points balance for a synthetic customer ID."""
    with trace_tool("get_loyalty_balance", customer_id=customer_id):
        record = BALANCES.get(customer_id)
        if not record:
            return {"found": False, "customer_id": customer_id, "error": "Customer not found"}
        return {"found": True, "customer_id": customer_id, **record}


@mcp.tool()
def redeem_points(customer_id: str, points: int, order_id: str = "") -> dict:
    """Redeem loyalty points toward a Garimpo order (100 points = $1.00 credit)."""
    with trace_tool("redeem_points", customer_id=customer_id, points=points):
        record = BALANCES.get(customer_id)
        if not record:
            return {"status": "denied", "reason": "Customer not found"}
        if points <= 0 or points > int(record["points"]):
            return {"status": "denied", "reason": "Invalid or insufficient points", "available": record["points"]}
        record["points"] = int(record["points"]) - points
        return {
            "status": "redeemed",
            "customer_id": customer_id,
            "order_id": order_id,
            "redeemed_points": points,
            "credit_usd": round(points / 100.0, 2),
            "remaining_points": record["points"],
        }

1.2 Keep tools.json in sync

Update apps/services/loyalty/tools.json so its tool definitions match get_loyalty_balance and redeem_points exactly. At deploy time, Terraform publishes this file to the Central Agent Registry as the service's mcp_server_spec.

1.3 Run unit tests

Update apps/services/loyalty/test_main.py to test /health, both tools, and CallerGuard allow/deny behavior, then run:

uv run --frozen --directory apps/services/loyalty pytest

Step 2: Test Locally with esmeralda query --local-mcp (5 min)

2.1 Register the local port

Add loyalty on port 8016 (right after the 5 store servers on 8011–8015) in packages/esmeralda/src/esmeralda/local_mcp.py:

Server("loyalty", "loyalty", "main:app", "apps/services/loyalty", 8016),

2.2 Wire loyalty into order-ops-specialist

In apps/agents/order-ops-specialist/agent.yaml, add the production and local URLs:

env:
  LOYALTY_MCP_URL: "https://loyalty.esmeralda.internal/mcp"

local_env:
  LOYALTY_MCP_URL: "http://localhost:8016/mcp"

Attach the toolset in apps/agents/order-ops-specialist/agent/agent.py (or tools.py):

loyalty_toolset = mcp.toolset(
    os.environ.get("LOYALTY_MCP_URL", "https://loyalty.esmeralda.internal/mcp"),
    prefix="loyalty",
)

2.3 Run the full agent chain on your workstation

--local-mcp automatically starts every local MCP server referenced by local_env, waits for /health, executes the query, and stops the servers cleanly on exit:

uv run --frozen esmeralda query \
  --agent-dir apps/agents/support-assistant \
  --local-mcp \
  "How many loyalty points does Camila Rocha (CUST-1001) have, and how much credit is that worth?"

Confirm that support-assistant delegates to order-ops-specialist, which calls loyalty_get_loyalty_balance on 127.0.0.1:8016.


Step 3: Register in the Service Catalog & Route via Envoy (5 min)

3.1 Create the catalog target

Create catalog/teams/ai-coe/mcp/loyalty.yaml:

schema: esmeralda.catalog
schema_version: 1

name: loyalty
kind: mcp
description: MCP server on Cloud Run that manages Garimpo loyalty points balances and redemptions (synthetic data).
owner_team: ai-coe
deploy: { unit: services/loyalty }
serving: { token: id, probe: mcp }

# Asymmetric least-privilege: only order-ops-specialist and test-vm may call loyalty.
# support-assistant is intentionally excluded and must delegate over A2A.
callers:
  order-ops-specialist: {}
  test-vm: {}

observability:
  usage_sources: [workload]
  framework: custom

3.2 Route loyalty through Envoy in dev

  1. In catalog/environments/dev.yaml, set gateway: envoy for loyalty alongside the other store MCP servers.
  2. In infrastructure/live/dev/env.yaml, add "loyalty" = "envoy" inside gateways.host_rules:
gateways = {
  enabled = ["envoy"]
  default = "direct"
  host_rules = {
    "loyalty" = "envoy"
    # ... existing host rules ...
  }
}

3.3 Resolve and inspect the compiled catalog

uv run --frozen esmeralda catalog resolve --env dev --write
uv run --frozen esmeralda catalog show --env dev --target loyalty

Verify that catalog show displays gateway: envoy, owner_team: ai-coe, and only order-ops-specialist and test-vm under allowed callers. See 2.6 Service Catalog for how catalog compilation drives IAM, Agent Gateway, and CallerGuard.


Step 4: Deploy via mcp-service & Verify Governance (10 min)

4.1 Add the Terragrunt unit (zero wrapper module boilerplate)

Create infrastructure/live/dev/layer-5-workloads/services/loyalty/terragrunt.hcl pointing directly to the shared mcp-service module (infrastructure/modules/5-workloads/services/mcp-service):

include "root" {
  path = find_in_parent_folders("root.hcl")
}

terraform {
  source = "../../../../../modules//5-workloads/services/mcp-service"
}

dependency "cicd"       { config_path = "../../../../shared/layer-0-cicd" }
dependency "projects"   { config_path = "../../../layer-1-projects" }
dependency "networking" { config_path = "../../../layer-2-networking" }
dependency "security"   { config_path = "../../../layer-3-security" }

dependency "order_ops_specialist" {
  config_path = "../../agents/order-ops-specialist"
  mock_outputs = {
    agent_identity_principal = "principal://agents.global.org-0000000000.system.id.goog/resources/aiplatform/projects/000000000000/locations/us-central1/reasoningEngines/mock-order-ops-specialist"
  }
  mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}

locals {
  env_vars      = read_terragrunt_config(find_in_parent_folders("env.yaml"))
  name          = basename(get_terragrunt_dir())
  callers       = try(local.env_vars.locals.catalog[local.name].callers, [])
  agent_callers = [for c in local.callers : c if contains(["a2a", "adk"], try(local.env_vars.locals.catalog[c].kind, ""))]
  image_name    = "loyalty"
  image_ref     = "${local.image_name}:${local.env_vars.locals.container_tag}"
}

inputs = {
  service_name          = local.name
  description           = try(local.env_vars.locals.catalog[local.name].description, "")
  project_id            = dependency.projects.outputs.mcps_project_id
  governance_project_id = dependency.projects.outputs.governance_project_id
  environment           = local.env_vars.locals.environment
  region                = local.env_vars.locals.region
  network_id            = dependency.networking.outputs.network_id
  subnet_id             = dependency.networking.outputs.subnet_id
  container_image       = "${dependency.cicd.outputs.dev_repository_url}/${local.image_ref}"
  tools_spec_path       = "${get_repo_root()}/apps/services/loyalty/tools.json"
  internal_hostname     = "${local.name}.${dependency.networking.outputs.entrypoint_domain}"
  otlp_endpoint         = try(local.env_vars.locals.telemetry.otlp_endpoint, "")

  invoker_service_accounts = distinct(compact(concat(
    [for c in local.agent_callers : "${local.env_vars.locals.catalog[c].unit}:agent_identity_principal"],
    [for c in local.callers : dependency.security.outputs["${replace(c, "-", "_")}_sa_email"] if !contains(local.agent_callers, c)],
  )))

  caller_allowlist = try(local.env_vars.locals.attribution.caller_guard, false) ? {
    policy  = local.env_vars.locals.catalog_attribution.policy
    callers = try(local.env_vars.locals.catalog_attribution.allowlists[local.name], [])
  } : null

  identity_refs = merge(
    { for k, v in dependency.security.outputs : "layer-3-security:${k}" => v if can(regex("_sa_email$", k)) && v != null },
    { "agents/order-ops-specialist:agent_identity_principal" = dependency.order_ops_specialist.outputs.agent_identity_principal },
  )
}

Wire the new services/loyalty dependency into gateways/envoy/terragrunt.hcl and iap-egress/terragrunt.hcl (and mirror the unit in prd to maintain environment parity).

4.2 Build and deploy

Build the container image in Cloud Build and apply the affected Layer 5 units in dependency order:

uv run --frozen esmeralda build loyalty
uv run --frozen esmeralda deploy services/loyalty gateways/envoy entrypoint iap-egress --env dev

4.3 Verify all four governance controls

  1. End-to-end store verification & gateway probes:
uv run --frozen esmeralda verify --env dev --scenario store

Confirm loyalty.esmeralda.internal appears in the gateway probe table with mcp id envoy HTTP 200 and that both order-ops-specialist (including :context) and support-assistant pass.

  1. CallerGuard & X-Esmeralda-Billed-Team attribution: The same esmeralda verify run executes the verified attribution probes on loyalty.esmeralda.internal:
  2. Authorized callers receive the X-Esmeralda-Billed-Team response header derived from their verified token identity.
  3. An unregistered caller identity receives HTTP 403.
  4. Declaring another team's X-Esmeralda-Cost-Center header receives HTTP 403 (under declared_mismatch: reject) or is billed back to the caller's own team (bill_own_team).

  5. Envoy esmeralda.usage metering: Inspect structured usage logs emitted by the Envoy adapter for loyalty.esmeralda.internal:

uv run --frozen esmeralda logs loyalty --env dev --minutes 15

In Cloud Logging (or the BigQuery log sink), filter for jsonPayload.schema="esmeralda.usage" and jsonPayload.target="loyalty" to confirm every MCP call is metered with caller team, latency, and status code. See 2.5 Usage Telemetry Contract.

  1. Asymmetric Agent Gateway egress (403 for support-assistant): Because support-assistant was intentionally omitted from callers: in catalog/teams/ai-coe/mcp/loyalty.yaml, the iap-egress unit did not grant support-assistant roles/iap.egressor on loyalty's Agent Registry entry (nor roles/run.invoker on Cloud Run).
  2. If you temporarily point support-assistant directly at https://loyalty.esmeralda.internal/mcp, the Central Agent Gateway blocks the request with HTTP 403 before it ever reaches Envoy or Cloud Run.
  3. All loyalty calls must flow through order-ops-specialist over A2A, preserving least-privilege blast radius.

Further Reading