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¶
- Scaffold & code (5 min): Copy
apps/services/_template/intoapps/services/loyalty/, implementget_loyalty_balanceandredeem_points, updatetools.json, and runpytest. - Test locally (5 min): Register port
8016inlocal_mcp.py, wireloyaltyintoorder-ops-specialist, and test locally withesmeralda query --local-mcp. - Register in Catalog & Route via Envoy (5 min): Declare
catalog/teams/ai-coe/mcp/loyalty.yaml, routeloyaltythroughenvoyindev, and compile the resolved catalog. - Deploy & Verify Governance (10 min): Deploy with the shared
mcp-serviceTerraform module and verifyCallerGuard+X-Esmeralda-Billed-Team, Envoyesmeralda.usagelogs, and Agent Gateway403enforcement forsupport-assistant.
Prerequisites¶
- An Esmeralda checkout with
uvinstalled (always pass--frozensouv.lockis not rewritten locally). - For Step 4 (cloud deployment), a deployed
devenvironment whereuv run --frozen esmeralda verify --env dev --scenario storealready passes.
Step 1: Scaffold & Implement loyalty (5 min)¶
Copy the self-contained MCP starter template to create 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 viaotel_setup.py, andapp = CallerGuard(_starlette).caller_guard.py— byte-identical vendored copy ofesmeralda.attribution(do not edit this file; guard tests verify it stays identical).otel_setup.py,tools.json,test_main.py,pyproject.toml, andDockerfile.
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:
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:
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¶
- In
catalog/environments/dev.yaml, setgateway: envoyforloyaltyalongside the other store MCP servers. - In
infrastructure/live/dev/env.yaml, add"loyalty" = "envoy"insidegateways.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¶
- End-to-end store verification & gateway probes:
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.
CallerGuard&X-Esmeralda-Billed-Teamattribution: The sameesmeralda verifyrun executes the verified attribution probes onloyalty.esmeralda.internal:- Authorized callers receive the
X-Esmeralda-Billed-Teamresponse header derived from their verified token identity. - An unregistered caller identity receives HTTP 403.
-
Declaring another team's
X-Esmeralda-Cost-Centerheader receives HTTP 403 (underdeclared_mismatch: reject) or is billed back to the caller's own team (bill_own_team). -
Envoy
esmeralda.usagemetering: Inspect structured usage logs emitted by the Envoy adapter forloyalty.esmeralda.internal:
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.
- Asymmetric Agent Gateway egress (
403forsupport-assistant): Becausesupport-assistantwas intentionally omitted fromcallers:incatalog/teams/ai-coe/mcp/loyalty.yaml, theiap-egressunit did not grantsupport-assistantroles/iap.egressoronloyalty's Agent Registry entry (norroles/run.invokeron Cloud Run). - If you temporarily point
support-assistantdirectly athttps://loyalty.esmeralda.internal/mcp, the Central Agent Gateway blocks the request with HTTP 403 before it ever reaches Envoy or Cloud Run. - All loyalty calls must flow through
order-ops-specialistover A2A, preserving least-privilege blast radius.
Further Reading¶
- 1.2 MCP Tool Servers — Cloud Run MCP contract, custom audiences, and Agent Registry registration.
- 1.3 Private Front Door & Gateways — How
gateways.host_rulesroutes individual MCP servers throughdirectvsenvoy. - 2.5 Usage Telemetry Contract —
esmeralda.usageschema and per-team chargeback attribution. - 2.6 Service Catalog — Single source of truth for callers, gateways, and attribution allowlists.