[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77H7QDRF3109M7YEZ2Y4TFV":3,"skill-same:01M77H7QDRF3109M7YEZ2Y4TFV":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":45,"repositoryHtmlUrl":52,"repositoryHomepageUrl":53,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M77H7QDRF3109M7YEZ2Y4TFV","greenhelix-agent-commerce-discovery",null,"Agent Commerce Discovery. Build machine-readable service catalogs, knowledge graphs, and UCP\u002FMCP\u002FA2A protocol endpoints so AI shopping agents can discover, evaluate, and transact with your services autonomously.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-discovery\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-commerce-discovery\nversion: \"1.3.1\"\ndescription: \"Agent Commerce Discovery. Build machine-readable service catalogs, knowledge graphs, and UCP\u002FMCP\u002FA2A protocol endpoints so AI shopping agents can discover, evaluate, and transact with your services autonomously.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [discovery, knowledge-graph, ucp, mcp, structured-data, schema-org, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, AGENT_SIGNING_KEY, STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - AGENT_SIGNING_KEY\n        - STRIPE_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent Commerce Discovery\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nForty percent of digital commerce services are invisible to AI agents. Not because the services are bad, but because they are structured for humans -- HTML pages, marketing copy, PDF brochures -- and agents cannot parse any of it. The services exist, the demand exists, and the agents have budgets to spend. But the transaction never happens because the agent never finds the service. This is the discovery gap, and it is the single largest source of lost revenue in the agentic economy.\nBetween January 2025 and March 2026, AI-referred traffic to commerce services grew 805% year-over-year. Google Shopping Graph now indexes over 45 billion product listings with structured attributes. ChatGPT's product search handles 2.3 million commerce queries per day. Perplexity Shopping launched with 30+ retail partners and AI-native product cards. The agents are shopping. The question is whether they can find you.\nThis guide is the practitioner's manual for making your services discoverable to AI agents. It covers the full stack: knowledge graphs that model your service catalog as machine-readable entities, protocol endpoints that announce your capabilities through UCP, MCP, A2A, and ACP, structured data that agents can parse and compare, real-time catalog synchronization that prevents stale listings, trust signals that help agents rank you above competitors, and analytics that measure whether discovery is actually converting into transactions. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint.\n\n## What You'll Learn\n- Chapter 1: The Discovery Problem\n- Chapter 2: Commerce Knowledge Graphs from Scratch\n- Chapter 3: The Protocol Stack: UCP, MCP, A2A, ACP\n- Chapter 4: Building .well-known Discovery Endpoints\n- Chapter 5: Structured Data & Schema.org for Agent Readability\n- Chapter 6: Real-Time Catalog Sync & Graph Maintenance\n- Chapter 7: Trust Signals & Reputation in Agent Discovery\n- Chapter 8: Measuring Discovery Performance\n- Conclusion: The Discovery Flywheel\n\n## Full Guide\n\n# Agent Commerce Discovery: Knowledge Graphs, Protocol Endpoints & Structured Data for AI-Discoverable Services\n\nForty percent of digital commerce services are invisible to AI agents. Not because the services are bad, but because they are structured for humans -- HTML pages, marketing copy, PDF brochures -- and agents cannot parse any of it. The services exist, the demand exists, and the agents have budgets to spend. But the transaction never happens because the agent never finds the service. This is the discovery gap, and it is the single largest source of lost revenue in the agentic economy.\n\nBetween January 2025 and March 2026, AI-referred traffic to commerce services grew 805% year-over-year. Google Shopping Graph now indexes over 45 billion product listings with structured attributes. ChatGPT's product search handles 2.3 million commerce queries per day. Perplexity Shopping launched with 30+ retail partners and AI-native product cards. The agents are shopping. The question is whether they can find you.\n\nThis guide is the practitioner's manual for making your services discoverable to AI agents. It covers the full stack: knowledge graphs that model your service catalog as machine-readable entities, protocol endpoints that announce your capabilities through UCP, MCP, A2A, and ACP, structured data that agents can parse and compare, real-time catalog synchronization that prevents stale listings, trust signals that help agents rank you above competitors, and analytics that measure whether discovery is actually converting into transactions. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint.\n\n---\n\n## Table of Contents\n\n1. [The Discovery Problem](#chapter-1-the-discovery-problem)\n2. [Commerce Knowledge Graphs from Scratch](#chapter-2-commerce-knowledge-graphs-from-scratch)\n3. [The Protocol Stack: UCP, MCP, A2A, ACP](#chapter-3-the-protocol-stack-ucp-mcp-a2a-acp)\n4. [Building .well-known Discovery Endpoints](#chapter-4-building-well-known-discovery-endpoints)\n5. [Structured Data & Schema.org for Agent Readability](#chapter-5-structured-data--schemaorg-for-agent-readability)\n6. [Real-Time Catalog Sync & Graph Maintenance](#chapter-6-real-time-catalog-sync--graph-maintenance)\n7. [Trust Signals & Reputation in Agent Discovery](#chapter-7-trust-signals--reputation-in-agent-discovery)\n8. [Measuring Discovery Performance](#chapter-8-measuring-discovery-performance)\n\n---\n\n## Chapter 1: The Discovery Problem\n\n### Why 40% of Commerce Services Are Invisible\n\nThe number comes from a March 2026 analysis by Forrester: of 2,400 digital service providers surveyed, 40.3% had no machine-readable service description of any kind -- no JSON-LD, no OpenAPI spec, no agent card, no structured catalog. Their services existed only as human-readable web pages. For AI agents performing commerce queries, these services might as well not exist.\n\nThe root cause is architectural. Traditional web commerce optimized for a single consumer: a human with a browser. The human reads marketing copy, interprets images, navigates menus, and fills out checkout forms. Every element of the commerce experience -- product descriptions, pricing pages, comparison charts, testimonials -- is designed for visual consumption by a person sitting at a screen. AI agents consume none of this. An agent does not \"see\" your landing page. It sends structured queries to discovery endpoints, parses JSON responses, compares attributes programmatically, and executes transactions via API. If your service is not described in a format agents can query, you are invisible to the fastest-growing channel in digital commerce.\n\n### The Shift from Human Browsing to Agent Crawling\n\nHuman discovery follows a browse-and-click pattern: Google search, scan results, click through, read page, compare tabs, make decision. The entire flow assumes visual attention and manual navigation. Agent discovery follows a query-and-parse pattern: send structured query, receive structured response, compare attributes algorithmically, execute highest-ranked option. The flows have almost nothing in common.\n\n| Dimension | Human Browsing | Agent Crawling |\n|---|---|---|\n| **Discovery method** | Keyword search, link following | Structured API queries, `.well-known` endpoint crawling |\n| **Content format** | HTML, images, video | JSON-LD, OpenAPI specs, agent cards |\n| **Comparison method** | Visual side-by-side, gut feeling | Programmatic attribute matching, scoring algorithms |\n| **Decision speed** | Minutes to days | Milliseconds to seconds |\n| **Price sensitivity** | Influenced by anchoring, framing | Exact numerical comparison with configurable thresholds |\n| **Trust evaluation** | Reviews, brand recognition | Cryptographic verification, trust scores, claim chains |\n| **Transaction method** | Shopping cart, checkout form | API call with payment proof |\n\nThe implication is stark: optimizing for human browsing does nothing for agent crawling. A beautifully designed landing page with compelling copy and high-resolution product photos generates zero signal for an agent that queries the REST API (`POST \u002Fv1\u002F{tool}`) with `{\"tool\": \"search_services\", \"input\": {\"query\": \"data enrichment API under $0.01 per call with 99.9% uptime SLA\"}}`. The agent needs structured attributes, machine-readable pricing, and verifiable SLA terms. It needs to find your service through a discovery protocol, not a Google search.\n\n### How the Major Platforms Do Discovery\n\n**Google Shopping Graph** indexes 45 billion product listings by crawling structured data from merchant websites. It prioritizes Merchant Center feeds (structured XML\u002FJSON), followed by Schema.org JSON-LD embedded in product pages, followed by inferred attributes from unstructured HTML (lowest priority, lowest accuracy). Products with complete structured data appear in AI Overviews, Shopping tab results, and Gemini product recommendations. Products without structured data are deprioritized or excluded entirely.\n\n**ChatGPT Product Search** (launched with GPT-4o shopping in April 2025) uses a combination of web crawling and direct merchant integrations. It surfaces product cards with structured attributes -- price, ratings, availability, specifications -- pulled from merchant APIs, affiliate feeds, and Schema.org markup. Merchants integrated through ACP (Agentic Commerce Protocol) get priority placement because ACP provides real-time inventory and pricing data that ChatGPT can trust to be current.\n\n**A2A Discovery** (Google's Agent-to-Agent protocol) uses Agent Cards published at `\u002F.well-known\u002Fagent.json`. An agent discovers another agent by fetching its Agent Card, which describes capabilities, supported input\u002Foutput formats, authentication requirements, and service endpoints. A2A discovery is agent-to-agent, not agent-to-product -- it is how autonomous agents find other agents to delegate tasks to or purchase services from.\n\n**GreenHelix Marketplace** provides a unified discovery layer across all these patterns. The `search_services` tool queries the marketplace index using structured attributes. The `best_match` tool returns the single best service for a given requirement set. The `register_service` tool publishes your service with structured metadata that agents can query. Your service appears in marketplace search results and can be discovered by any agent with API access.\n\n### The Cost of Being Undiscoverable\n\nThe 805% year-over-year growth in AI-referred traffic is not evenly distributed. It concentrates on services that are machine-readable. A March 2026 analysis of 500 SaaS products found that those with complete structured data (JSON-LD, OpenAPI spec, and at least one discovery protocol endpoint) captured 14x more AI-referred traffic than those without. The relationship was not proportional -- it was binary. Services were either discoverable or they were not. There was no middle ground of \"partially discoverable.\"\n\nThe revenue impact is direct. AI-referred traffic converts at 2.3x the rate of organic search traffic because agents only send users (or other agents) to services that match the query criteria. An agent that finds your service has already verified that your pricing, capabilities, and availability meet the requirements. The \"lead\" is pre-qualified by the agent's scoring algorithm. Losing that channel means losing your highest-converting traffic source.\n\n```python\nimport requests\nfrom typing import Any\n\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\n\nclass DiscoveryClient:\n    \"\"\"Client for GreenHelix A2A Commerce Gateway discovery operations.\"\"\"\n\n    def __init__(self, api_key: str):\n        self.api_key = api_key\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        })\n\n    def execute(self, tool: str, input_data: dict[str, Any]) -> dict:\n        \"\"\"Execute a single tool on the gateway.\"\"\"\n        resp = self.session.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            timeout=30,\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def search_services(self, query: str, filters: dict | None = None) -> dict:\n        \"\"\"Search the GreenHelix marketplace for services.\"\"\"\n        payload = {\"query\": query}\n        if filters:\n            payload[\"filters\"] = filters\n        return self.execute(\"search_services\", payload)\n\n    def best_match(self, requirements: dict) -> dict:\n        \"\"\"Find the single best service match for given requirements.\"\"\"\n        return self.execute(\"best_match\", requirements)\n\n\n# Initialize -- used throughout this guide\nclient = DiscoveryClient(api_key=\"your-api-key-here\")\n\n# Example: search for data enrichment services\nresults = client.search_services(\n    query=\"data enrichment API\",\n    filters={\n        \"max_price_per_call\": 0.01,\n        \"min_uptime_sla\": 99.9,\n        \"protocols\": [\"ucp\", \"a2a\"],\n    },\n)\nprint(f\"Found {len(results.get('services', []))} matching services\")\n```\n\nThis client object is referenced in every subsequent chapter. Store your API key in an environment variable (`GREENHELIX_API_KEY`), never in source code.\n\n> **Key Takeaways**\n>\n> - 40% of digital services have zero machine-readable descriptions. They are invisible to AI agents regardless of quality.\n> - AI-referred commerce traffic grew 805% YoY. Services with complete structured data capture 14x more of this traffic.\n> - Agent discovery is query-and-parse, not browse-and-click. Optimizing for humans does nothing for agents.\n> - Google Shopping Graph, ChatGPT, A2A, and GreenHelix all rely on structured data. No structured data means no discovery.\n> - See P21 (Agent-Ready Commerce) for building the full agent-ready storefront on top of discovery.\n\n---\n\n## Chapter 2: Commerce Knowledge Graphs from Scratch\n\n### What Is a Commerce Knowledge Graph?\n\nA knowledge graph is a structured representation of entities, their properties, and the relationships between them. In commerce, the entities are services, providers, pricing tiers, SLAs, certifications, and transactions. The relationships connect them: a provider *offers* a service, a service *has* a pricing tier, a pricing tier *includes* an SLA, an SLA *guarantees* an uptime level. The properties are the machine-readable attributes: price per call, latency percentile, geographic availability, supported authentication methods.\n\nTraditional databases store this data in tables. Knowledge graphs store it as triples: subject-predicate-object. \"DataEnrichmentAPI\" -- \"hasPricing\" -- \"PayPerCallTier\". \"PayPerCallTier\" -- \"costPerCall\" -- \"0.005 USD\". \"DataEnrichmentAPI\" -- \"guarantees\" -- \"99.95% Uptime SLA\". The advantage of the graph structure is that agents can traverse relationships without knowing the schema in advance. An agent can start from a service node, follow edges to discover pricing, SLA terms, trust scores, and provider identity -- all without a predefined query template.\n\n### Entities, Relationships, and Properties\n\nA commerce knowledge graph for agent-discoverable services contains five core entity types:\n\n| Entity Type | Description | Key Properties |\n|---|---|---|\n| **Service** | The product or capability being offered | name, description, category, version, status |\n| **Provider** | The entity (agent or organization) offering the service | agent_id, public_key, registration_date, trust_score |\n| **PricingTier** | A specific pricing configuration | tier_name, cost_per_call, monthly_cap, currency, billing_model |\n| **SLA** | Service level agreement terms | uptime_guarantee, latency_p99, support_response_time |\n| **Certification** | Verified claims about the service or provider | cert_type, issuer, valid_from, valid_until, verification_hash |\n\nThe relationships between these entities form the graph:\n\n```\nProvider --[offers]--> Service\nService --[hasPricing]--> PricingTier\nService --[guarantees]--> SLA\nProvider --[holds]--> Certification\nService --[requires]--> Certification (for consumers)\nService --[dependsOn]--> Service (for composed services)\n```\n\n### Modeling Your Service Catalog as a Graph\n\nThe first step is translating your existing service catalog into graph form. Most teams start with a flat list of services in a database table or a YAML config file. The graph transformation adds structure that agents can navigate.\n\n```python\nimport json\nfrom dataclasses import dataclass, field, asdict\nfrom typing import Optional\n\n\n@dataclass\nclass SLA:\n    uptime_guarantee: float\n    latency_p99_ms: int\n    support_response_hours: int\n    penalty_per_violation_pct: float = 5.0\n\n\n@dataclass\nclass PricingTier:\n    tier_name: str\n    cost_per_call: float\n    currency: str = \"USD\"\n    monthly_cap: Optional[float] = None\n    billing_model: str = \"pay_per_call\"\n    volume_discounts: dict = field(default_factory=dict)\n\n\n@dataclass\nclass ServiceNode:\n    service_id: str\n    name: str\n    description: str\n    category: str\n    version: str\n    provider_agent_id: str\n    pricing_tiers: list[PricingTier] = field(default_factory=list)\n    sla: Optional[SLA] = None\n    tags: list[str] = field(default_factory=list)\n    dependencies: list[str] = field(default_factory=list)\n    supported_protocols: list[str] = field(default_factory=list)\n    status: str = \"active\"\n\n\nclass CommerceKnowledgeGraph:\n    \"\"\"In-memory knowledge graph for agent-discoverable services.\"\"\"\n\n    def __init__(self):\n        self.services: dict[str, ServiceNode] = {}\n        self.edges: list[dict] = []\n\n    def add_service(self, service: ServiceNode) -> None:\n        \"\"\"Add a service node to the graph.\"\"\"\n        self.services[service.service_id] = service\n\n        # Auto-generate relationship edges\n        for tier in service.pricing_tiers:\n            self.edges.append({\n                \"subject\": service.service_id,\n                \"predicate\": \"hasPricing\",\n                \"object\": tier.tier_name,\n                \"properties\": asdict(tier),\n            })\n\n        if service.sla:\n            self.edges.append({\n                \"subject\": service.service_id,\n                \"predicate\": \"guarantees\",\n                \"object\": f\"{service.service_id}_sla\",\n                \"properties\": asdict(service.sla),\n            })\n\n        for dep in service.dependencies:\n            self.edges.append({\n                \"subject\": service.service_id,\n                \"predicate\": \"dependsOn\",\n                \"object\": dep,\n            })\n\n    def query_by_attribute(self, **kwargs) -> list[ServiceNode]:\n        \"\"\"Query services by attribute filters.\"\"\"\n        results = []\n        for service in self.services.values():\n            match = True\n            for key, value in kwargs.items():\n                if key == \"max_cost_per_call\":\n                    if not any(\n                        t.cost_per_call \u003C= value\n                        for t in service.pricing_tiers\n                    ):\n                        match = False\n                elif key == \"min_uptime\":\n                    if not service.sla or service.sla.uptime_guarantee \u003C value:\n                        match = False\n                elif key == \"category\":\n                    if service.category != value:\n                        match = False\n                elif key == \"protocol\":\n                    if value not in service.supported_protocols:\n                        match = False\n            if match:\n                results.append(service)\n        return results\n\n    def to_jsonld(self) -> list[dict]:\n        \"\"\"Export the graph as JSON-LD for agent consumption.\"\"\"\n        output = []\n        for service in self.services.values():\n            node = {\n                \"@context\": \"https:\u002F\u002Fschema.org\",\n                \"@type\": \"Service\",\n                \"@id\": f\"urn:greenhelix:service:{service.service_id}\",\n                \"name\": service.name,\n                \"description\": service.description,\n                \"category\": service.category,\n                \"version\": service.version,\n                \"provider\": {\n                    \"@type\": \"Organization\",\n                    \"identifier\": service.provider_agent_id,\n                },\n                \"offers\": [\n                    {\n                        \"@type\": \"Offer\",\n                        \"name\": tier.tier_name,\n                        \"price\": str(tier.cost_per_call),\n                        \"priceCurrency\": tier.currency,\n                        \"priceSpecification\": {\n                            \"@type\": \"UnitPriceSpecification\",\n                            \"price\": str(tier.cost_per_call),\n                            \"priceCurrency\": tier.currency,\n                            \"unitText\": \"per API call\",\n                            \"billingModel\": tier.billing_model,\n                        },\n                    }\n                    for tier in service.pricing_tiers\n                ],\n            }\n            if service.sla:\n                node[\"termsOfService\"] = {\n                    \"uptimeGuarantee\": service.sla.uptime_guarantee,\n                    \"latencyP99Ms\": service.sla.latency_p99_ms,\n                    \"supportResponseHours\": service.sla.support_response_hours,\n                }\n            output.append(node)\n        return output\n\n    def sync_to_marketplace(self, discovery_client) -> list[dict]:\n        \"\"\"Register all services on GreenHelix marketplace.\"\"\"\n        results = []\n        for service in self.services.values():\n            cheapest_tier = min(\n                service.pricing_tiers,\n                key=lambda t: t.cost_per_call,\n            ) if service.pricing_tiers else None\n\n            result = discovery_client.execute(\"register_service\", {\n                \"agent_id\": service.provider_agent_id,\n                \"service_name\": service.name,\n                \"description\": service.description,\n                \"category\": service.category,\n                \"tags\": service.tags,\n                \"pricing\": {\n                    \"model\": cheapest_tier.billing_model if cheapest_tier else \"contact\",\n                    \"base_price\": str(cheapest_tier.cost_per_call) if cheapest_tier else \"0\",\n                    \"currency\": cheapest_tier.currency if cheapest_tier else \"USD\",\n                },\n                \"sla\": asdict(service.sla) if service.sla else None,\n                \"protocols\": service.supported_protocols,\n            })\n            results.append(result)\n        return results\n\n\n# Build a sample graph\ngraph = CommerceKnowledgeGraph()\n\ngraph.add_service(ServiceNode(\n    service_id=\"data-enrichment-v2\",\n    name=\"DataEnrich Pro\",\n    description=\"Real-time company data enrichment with 95% match rate\",\n    category=\"data-enrichment\",\n    version=\"2.1.0\",\n    provider_agent_id=\"agent-dataenrich-prod\",\n    pricing_tiers=[\n        PricingTier(\"starter\", cost_per_call=0.005, monthly_cap=100.0),\n        PricingTier(\"growth\", cost_per_call=0.003, monthly_cap=500.0,\n                    volume_discounts={\"10000\": 0.002, \"100000\": 0.001}),\n    ],\n    sla=SLA(uptime_guarantee=99.95, latency_p99_ms=200,\n            support_response_hours=4),\n    tags=[\"enrichment\", \"company-data\", \"real-time\", \"api\"],\n    supported_protocols=[\"ucp\", \"a2a\", \"mcp\"],\n))\n\ngraph.add_service(ServiceNode(\n    service_id=\"sentiment-analysis-v3\",\n    name=\"SentimentLens\",\n    description=\"Multi-language sentiment analysis with aspect extraction\",\n    category=\"nlp\",\n    version=\"3.0.1\",\n    provider_agent_id=\"agent-sentimentlens-prod\",\n    pricing_tiers=[\n        PricingTier(\"basic\", cost_per_call=0.001),\n        PricingTier(\"premium\", cost_per_call=0.008,\n                    volume_discounts={\"50000\": 0.005}),\n    ],\n    sla=SLA(uptime_guarantee=99.9, latency_p99_ms=150,\n            support_response_hours=8),\n    tags=[\"nlp\", \"sentiment\", \"multilingual\", \"aspect-extraction\"],\n    supported_protocols=[\"ucp\", \"mcp\"],\n))\n\n# Query the graph\ncheap_services = graph.query_by_attribute(\n    max_cost_per_call=0.005,\n    min_uptime=99.9,\n)\nprint(f\"Services matching criteria: {[s.name for s in cheap_services]}\")\n\n# Export as JSON-LD\njsonld = graph.to_jsonld()\nprint(json.dumps(jsonld[0], indent=2))\n```\n\n### JSON-LD and Schema.org Vocabulary\n\nJSON-LD (JavaScript Object Notation for Linked Data) is the standard format for embedding structured data in web pages and API responses. It uses `@context` to map property names to Schema.org URIs, `@type` to declare the entity type, and `@id` to provide a globally unique identifier. AI agents -- whether they are Google's crawlers, ChatGPT's shopping engine, or a GreenHelix marketplace indexer -- parse JSON-LD to extract structured attributes.\n\nThe Schema.org vocabulary provides standardized types for commerce: `Service`, `Offer`, `Organization`, `PriceSpecification`, `AggregateRating`, `Review`. Using these types ensures your data is interoperable across all agent ecosystems. A service described as `@type: Service` with `offers` containing `@type: Offer` and `priceSpecification` will be parsed identically by Google Shopping Graph, Perplexity Shopping, and GreenHelix `search_services`.\n\nThe `to_jsonld()` method in the `CommerceKnowledgeGraph` class above handles the conversion. The critical detail is using string representations for prices (`str(tier.cost_per_call)`) rather than floats, avoiding floating-point precision issues that cause agents to reject or miscompare pricing data. See P18 (Pricing & Monetization) for the full treatment of decimal-safe pricing.\n\n> **Key Takeaways**\n>\n> - A commerce knowledge graph models services as entities with typed relationships: provider offers service, service has pricing, pricing includes SLA.\n> - Five core entity types: Service, Provider, PricingTier, SLA, Certification. Each has machine-readable properties.\n> - JSON-LD with Schema.org vocabulary is the interoperability standard. All major agent platforms parse it.\n> - Build the graph in code, export as JSON-LD for web crawlers, and sync to GreenHelix marketplace via `register_service` for agent-native discovery.\n> - Always use string-typed prices to avoid floating-point comparison failures.\n\n---\n\n## Chapter 3: The Protocol Stack: UCP, MCP, A2A, ACP\n\n### Four Protocols, Four Jobs\n\nThe agentic commerce stack has consolidated around four protocols, each solving a distinct problem in the discovery-to-transaction lifecycle. Implementing the wrong one first wastes months. Implementing all four without understanding the dependencies creates a maintenance burden that outweighs the benefit. This chapter provides the decision framework.\n\n**UCP (Unified Commerce Protocol)** is the discovery and capability advertisement layer. A UCP profile published at `\u002F.well-known\u002Fucp` tells agents what your service does, how it is priced, what payment methods it accepts, and where to find its API. UCP is the front door. Without it, agents that crawl for services have no standard entry point. UCP profiles are JSON documents with a defined schema: capabilities, pricing, authentication requirements, SLA terms, and payment methods. Think of it as a machine-readable business card that also includes the full menu and the credit card terminal specs.\n\n**MCP (Model Context Protocol)** is the tool execution layer. An MCP server exposes tools -- functions with JSON Schema-defined inputs and outputs -- that LLMs and agents can call. MCP handles tool discovery (listing available tools and their schemas), tool invocation (sending structured inputs and receiving structured outputs), and context management (maintaining state across multi-turn tool interactions). If UCP tells an agent your service exists, MCP tells it how to call your service.\n\n**A2A (Agent-to-Agent Protocol)** is the task delegation layer. A2A defines how agents discover each other (Agent Cards at `\u002F.well-known\u002Fagent.json`), exchange task requests (JSON-based task messages with structured parts), and stream progress updates (Server-Sent Events). A2A is designed for agent-to-agent workflows where one agent delegates a task to another, monitors progress, and receives results. It overlaps with MCP in discovery but diverges in execution: MCP is function-call oriented, A2A is task-oriented.\n\n**ACP (Agentic Commerce Protocol)** is the payment and checkout layer. ACP extends Stripe Checkout for AI agents, providing structured product catalogs, cart management, and payment flow orchestration. ACP is the narrowest of the four protocols -- it specifically handles the commercial transaction, not discovery, not tool execution, not task delegation.\n\n### The Dependency Chain\n\nThe protocols are not independent. They form a dependency chain:\n\n```\nDiscovery        Execution         Transaction\n┌──────┐        ┌──────┐          ┌──────┐\n│ UCP  │───────▶│ MCP  │─────────▶│ ACP  │\n│      │───────▶│ A2A  │─────────▶│      │\n└──────┘        └──────┘          └──────┘\n```\n\nUCP must come first. An agent cannot call your MCP tools or send you A2A tasks if it cannot discover you. MCP and A2A operate in parallel -- some agents prefer function calls (MCP), others prefer task delegation (A2A), many support both. ACP comes last because payment only matters after an agent has discovered your service and decided to use it.\n\n### Decision Matrix: Which Protocol to Implement First\n\n| Factor | UCP First | MCP First | A2A First | ACP First |\n|---|---|---|---|---|\n| **You sell API services** | Yes -- agents need to discover your capabilities | Second -- expose tools after discovery | Optional -- most API consumers prefer MCP | Third -- add payment after execution works |\n| **You sell to LLM-powered agents** | Yes | Yes -- LLMs call MCP tools natively | Lower priority | After MCP |\n| **You sell to autonomous agent fleets** | Yes | Optional | Yes -- fleets use A2A for task delegation | After A2A |\n| **You are a marketplace** | Yes | Yes -- expose search\u002Fpurchase as tools | Yes -- agents discover marketplace via A2A | Yes -- checkout via ACP |\n| **You need payment immediately** | Still first -- discovery before payment | No | No | No -- useless without discovery |\n\nThe universal answer: **implement UCP first, then MCP or A2A depending on your buyer profile, then ACP**.\n\n### Protocol Selection Logic\n\n```python\ndef select_protocols(\n    service_type: str,\n    buyer_profile: str,\n    needs_payment: bool,\n    existing_protocols: list[str],\n) -> list[dict]:\n    \"\"\"Determine which discovery protocols to implement and in what order.\n\n    Returns prioritized list of protocols with implementation guidance.\n    \"\"\"\n    recommendations = []\n\n    # UCP is always first -- it is the discovery foundation\n    if \"ucp\" not in existing_protocols:\n        recommendations.append({\n            \"protocol\": \"ucp\",\n            \"priority\": 1,\n            \"reason\": \"Discovery foundation -- agents cannot find you without it\",\n            \"effort_days\": 2,\n            \"endpoint\": \"\u002F.well-known\u002Fucp\",\n        })\n\n    # MCP vs A2A depends on buyer profile\n    if buyer_profile in (\"llm_agents\", \"api_consumers\", \"developers\"):\n        if \"mcp\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"mcp\",\n                \"priority\": 2,\n                \"reason\": \"LLM agents and API consumers prefer function-call semantics\",\n                \"effort_days\": 3,\n                \"endpoint\": \"\u002Fmcp\u002Ftools\",\n            })\n        if \"a2a\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"a2a\",\n                \"priority\": 3,\n                \"reason\": \"Secondary -- covers autonomous agent fleets\",\n                \"effort_days\": 4,\n                \"endpoint\": \"\u002F.well-known\u002Fagent.json\",\n            })\n    elif buyer_profile in (\"autonomous_fleets\", \"enterprise_agents\"):\n        if \"a2a\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"a2a\",\n                \"priority\": 2,\n                \"reason\": \"Autonomous fleets use A2A for task delegation\",\n                \"effort_days\": 4,\n                \"endpoint\": \"\u002F.well-known\u002Fagent.json\",\n            })\n        if \"mcp\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"mcp\",\n                \"priority\": 3,\n                \"reason\": \"Secondary -- covers LLM-based tool calling\",\n                \"effort_days\": 3,\n                \"endpoint\": \"\u002Fmcp\u002Ftools\",\n            })\n\n    # ACP always comes after execution layer\n    if needs_payment and \"acp\" not in existing_protocols:\n        recommendations.append({\n            \"protocol\": \"acp\",\n            \"priority\": 4,\n            \"reason\": \"Payment layer -- implement after discovery and execution\",\n            \"effort_days\": 5,\n            \"endpoint\": \"\u002Facp\u002Fcheckout\",\n        })\n\n    return sorted(recommendations, key=lambda r: r[\"priority\"])\n\n\n# Example: SaaS API selling to LLM-powered agents\nplan = select_protocols(\n    service_type=\"api_service\",\n    buyer_profile=\"llm_agents\",\n    needs_payment=True,\n    existing_protocols=[],\n)\nfor step in plan:\n    print(f\"Priority {step['priority']}: {step['protocol'].upper()} \"\n          f\"({step['effort_days']} days) -- {step['reason']}\")\n```\n\n### Registering Protocol Support on GreenHelix\n\nOnce you have implemented protocol endpoints, register them on the marketplace so agents know which protocols you support:\n\n```python\n# Register your service with protocol metadata\nresult = client.execute(\"register_service\", {\n    \"agent_id\": \"agent-dataenrich-prod\",\n    \"service_name\": \"DataEnrich Pro\",\n    \"description\": \"Real-time company data enrichment API\",\n    \"category\": \"data-enrichment\",\n    \"tags\": [\"enrichment\", \"company-data\", \"api\"],\n    \"pricing\": {\n        \"model\": \"pay_per_call\",\n        \"base_price\": \"0.005\",\n        \"currency\": \"USD\",\n    },\n    \"protocols\": [\"ucp\", \"mcp\", \"a2a\"],\n    \"endpoints\": {\n        \"ucp\": \"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fucp\",\n        \"mcp\": \"https:\u002F\u002Fdataenrich.example.com\u002Fmcp\u002Ftools\",\n        \"a2a\": \"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fagent.json\",\n    },\n})\nprint(f\"Service registered: {result}\")\n```\n\nAgents searching the marketplace can then filter by protocol:\n\n```python\n# Find services that support A2A\na2a_services = client.search_services(\n    query=\"data enrichment\",\n    filters={\"protocols\": [\"a2a\"]},\n)\n```\n\n> **Key Takeaways**\n>\n> - Four protocols form a stack: UCP (discovery), MCP (tool execution), A2A (task delegation), ACP (payment).\n> - UCP is always implemented first. Without discovery, no other protocol matters.\n> - MCP for LLM-powered agents, A2A for autonomous agent fleets. Most services should implement both.\n> - ACP handles payment and is always implemented last in the chain.\n> - Register protocol endpoints on GreenHelix via `register_service` so agents can filter by supported protocol.\n> - See P21 (Agent-Ready Commerce) Chapter 3 for detailed UCP\u002FACP\u002Fx402 payment rail comparison.\n\n---\n\n## Chapter 4: Building .well-known Discovery Endpoints\n\n### The Discovery Endpoint Pattern\n\nThe `.well-known` URI pattern (RFC 8615) provides a standardized location for machine-readable metadata. Agents crawling for services check these paths before attempting any other discovery method. If your service is at `https:\u002F\u002Fapi.example.com`, agents will look for:\n\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fucp` -- UCP service profile\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fagent.json` -- A2A agent card\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fai-plugin.json` -- OpenAI\u002FChatGPT plugin manifest\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fopenapi.yaml` -- OpenAPI specification\n\nMissing any of these endpoints means missing agents that use that specific discovery method. The cost of serving static JSON at four paths is trivial. The cost of not serving it is invisibility to entire agent ecosystems.\n\n### UCP Profile: The Complete Service Advertisement\n\nThe UCP profile is the most comprehensive discovery document. It combines capability advertisement, pricing, payment methods, SLA terms, and API documentation references into a single JSON document.\n\n```python\nimport json\nfrom datetime import datetime, timezone\n\n\ndef build_ucp_profile(\n    service_name: str,\n    service_description: str,\n    provider_agent_id: str,\n    capabilities: list[dict],\n    pricing_tiers: list[dict],\n    payment_methods: list[str],\n    sla: dict,\n    api_spec_url: str,\n    trust_score: float | None = None,\n) -> dict:\n    \"\"\"Build a UCP profile document for \u002F.well-known\u002Fucp.\"\"\"\n    profile = {\n        \"ucp_version\": \"1.0\",\n        \"service\": {\n            \"name\": service_name,\n            \"description\": service_description,\n            \"provider\": {\n                \"agent_id\": provider_agent_id,\n                \"trust_score\": trust_score,\n                \"verification_status\": \"verified\" if trust_score and trust_score > 0.7 else \"unverified\",\n            },\n            \"status\": \"active\",\n            \"last_updated\": datetime.now(timezone.utc).isoformat(),\n        },\n        \"capabilities\": capabilities,\n        \"pricing\": {\n            \"tiers\": pricing_tiers,\n            \"currency\": \"USD\",\n            \"billing_models\": list({t.get(\"billing_model\", \"pay_per_call\") for t in pricing_tiers}),\n        },\n        \"payment_methods\": payment_methods,\n        \"sla\": sla,\n        \"api\": {\n            \"specification\": api_spec_url,\n            \"format\": \"openapi-3.1\",\n            \"authentication\": {\n                \"type\": \"bearer\",\n                \"token_endpoint\": None,  # None for API-key auth\n            },\n        },\n        \"discovery\": {\n            \"protocols\": [\"ucp\", \"mcp\", \"a2a\"],\n            \"mcp_endpoint\": \"\u002Fmcp\u002Ftools\",\n            \"a2a_agent_card\": \"\u002F.well-known\u002Fagent.json\",\n        },\n    }\n    return profile\n\n\n# Build profile for our data enrichment service\nucp_profile = build_ucp_profile(\n    service_name=\"DataEnrich Pro\",\n    service_description=\"Real-time company data enrichment with 95% match rate across 200M+ companies\",\n    provider_agent_id=\"agent-dataenrich-prod\",\n    capabilities=[\n        {\n            \"name\": \"company_lookup\",\n            \"description\": \"Enrich company data from domain, name, or LinkedIn URL\",\n            \"input_schema\": {\"domain\": \"string\", \"company_name\": \"string?\"},\n            \"output_schema\": {\"company\": \"CompanyProfile\"},\n            \"latency_p99_ms\": 200,\n        },\n        {\n            \"name\": \"contact_enrichment\",\n            \"description\": \"Enrich contact details from email or name + company\",\n            \"input_schema\": {\"email\": \"string?\", \"name\": \"string?\", \"company\": \"string?\"},\n            \"output_schema\": {\"contact\": \"ContactProfile\"},\n            \"latency_p99_ms\": 350,\n        },\n    ],\n    pricing_tiers=[\n        {\n            \"name\": \"starter\",\n            \"cost_per_call\": \"0.005\",\n            \"monthly_cap\": \"100.00\",\n            \"billing_model\": \"pay_per_call\",\n        },\n        {\n            \"name\": \"growth\",\n            \"cost_per_call\": \"0.003\",\n            \"monthly_cap\": \"500.00\",\n            \"billing_model\": \"pay_per_call\",\n            \"volume_discounts\": {\"10000\": \"0.002\", \"100000\": \"0.001\"},\n        },\n    ],\n    payment_methods=[\"greenhelix_escrow\", \"stripe\", \"x402_usdc\"],\n    sla={\n        \"uptime_guarantee\": 99.95,\n        \"latency_p99_ms\": 200,\n        \"support_response_hours\": 4,\n        \"data_retention_days\": 30,\n    },\n    api_spec_url=\"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fopenapi.yaml\",\n    trust_score=0.92,\n)\n\nprint(json.dumps(ucp_profile, indent=2))\n```\n\n### MCP Tool Manifest\n\nThe MCP tool manifest describes each tool's input and output schemas so LLMs can discover and call them:\n\n```python\ndef build_mcp_manifest(capabilities: list[dict]) -> dict:\n    \"\"\"Build an MCP tool manifest from service capabilities.\"\"\"\n    tools = []\n    for cap in capabilities:\n        tool = {\n            \"name\": cap[\"name\"],\n            \"description\": cap[\"description\"],\n            \"inputSchema\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    k: {\"type\": v.rstrip(\"?\")}\n                    for k, v in cap.get(\"input_schema\", {}).items()\n                },\n                \"required\": [\n                    k for k, v in cap.get(\"input_schema\", {}).items()\n                    if not v.endswith(\"?\")\n                ],\n            },\n        }\n        tools.append(tool)\n\n    return {\n        \"schema_version\": \"2025-03-26\",\n        \"server_info\": {\n            \"name\": \"dataenrich-mcp\",\n            \"version\": \"2.1.0\",\n        },\n        \"tools\": tools,\n    }\n```\n\n### A2A Agent Card\n\nThe A2A agent card is simpler -- it describes the agent's identity, capabilities, and communication preferences:\n\n```python\ndef build_a2a_agent_card(\n    agent_id: str,\n    name: str,\n    description: str,\n    skills: list[dict],\n    endpoint: str,\n) -> dict:\n    \"\"\"Build an A2A Agent Card for \u002F.well-known\u002Fagent.json.\"\"\"\n    return {\n        \"name\": name,\n        \"description\": description,\n        \"url\": endpoint,\n        \"version\": \"1.0.0\",\n        \"capabilities\": {\n            \"streaming\": True,\n            \"pushNotifications\": False,\n            \"stateTransitionHistory\": True,\n        },\n        \"authentication\": {\n            \"schemes\": [\"bearer\"],\n        },\n        \"defaultInputModes\": [\"application\u002Fjson\"],\n        \"defaultOutputModes\": [\"application\u002Fjson\"],\n        \"skills\": skills,\n    }\n\n\nagent_card = build_a2a_agent_card(\n    agent_id=\"agent-dataenrich-prod\",\n    name=\"DataEnrich Pro Agent\",\n    description=\"Autonomous data enrichment agent with 95% match rate\",\n    skills=[\n        {\n            \"id\": \"company_lookup\",\n            \"name\": \"Company Data Lookup\",\n            \"description\": \"Enrich company data from domain or name\",\n            \"tags\": [\"enrichment\", \"company-data\"],\n            \"examples\": [\"Enrich data for openai.com\", \"Look up Stripe company info\"],\n        },\n        {\n            \"id\": \"contact_enrichment\",\n            \"name\": \"Contact Enrichment\",\n            \"description\": \"Enrich contact details from email or name\",\n            \"tags\": [\"enrichment\", \"contacts\"],\n            \"examples\": [\"Find details for jane@example.com\"],\n        },\n    ],\n    endpoint=\"https:\u002F\u002Fdataenrich.example.com\u002Fa2a\",\n)\n```\n\n### The FastAPI Service: All Endpoints Together\n\nHere is a complete FastAPI service that serves all discovery endpoints and validates them against GreenHelix `search_services` and `best_match`:\n\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\nimport uvicorn\n\napp = FastAPI(title=\"DataEnrich Pro -- Agent-Discoverable Service\")\n\n\n@app.get(\"\u002F.well-known\u002Fucp\")\nasync def ucp_endpoint():\n    \"\"\"UCP service profile for agent discovery.\"\"\"\n    return JSONResponse(content=ucp_profile)\n\n\n@app.get(\"\u002F.well-known\u002Fagent.json\")\nasync def a2a_agent_card_endpoint():\n    \"\"\"A2A Agent Card for agent-to-agent discovery.\"\"\"\n    return JSONResponse(content=agent_card)\n\n\n@app.get(\"\u002Fmcp\u002Ftools\")\nasync def mcp_tools_endpoint():\n    \"\"\"MCP tool manifest for LLM tool discovery.\"\"\"\n    manifest = build_mcp_manifest(ucp_profile[\"capabilities\"])\n    return JSONResponse(content=manifest)\n\n\n@app.get(\"\u002F.well-known\u002Fai-plugin.json\")\nasync def ai_plugin_endpoint():\n    \"\"\"OpenAI-compatible plugin manifest.\"\"\"\n    return JSONResponse(content={\n        \"schema_version\": \"v1\",\n        \"name_for_human\": \"DataEnrich Pro\",\n        \"name_for_model\": \"dataenrich_pro\",\n        \"description_for_human\": \"Real-time company and contact data enrichment.\",\n        \"description_for_model\": (\n            \"Real-time data enrichment API. Supports company lookup by domain \"\n            \"or name (200M+ companies, 95% match rate) and contact enrichment \"\n            \"by email. Returns structured JSON with 50+ fields. Pricing: \"\n            \"$0.003-$0.005 per call. Uptime SLA: 99.95%. Supports UCP, MCP, A2A.\"\n        ),\n        \"auth\": {\"type\": \"service_http\", \"authorization_type\": \"bearer\"},\n        \"api\": {\n            \"type\": \"openapi\",\n            \"url\": \"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fopenapi.yaml\",\n        },\n    })\n\n\n@app.get(\"\u002Fhealth\")\nasync def health():\n    return {\"status\": \"ok\"}\n\n\n# Validation: test that your service is discoverable via GreenHelix\ndef validate_discovery():\n    \"\"\"Verify the service appears in GreenHelix search results.\"\"\"\n    # Search for our service by capability\n    results = client.search_services(\n        query=\"company data enrichment real-time\",\n        filters={\"protocols\": [\"ucp\", \"mcp\"]},\n    )\n    services = results.get(\"services\", [])\n    our_service = next(\n        (s for s in services if s.get(\"agent_id\") == \"agent-dataenrich-prod\"),\n        None,\n    )\n\n    if not our_service:\n        print(\"WARNING: Service not found in marketplace search results\")\n        print(\"Run register_service first (see Chapter 2)\")\n        return False\n\n    # Verify best_match picks us for a targeted query\n    match = client.best_match({\n        \"query\": \"data enrichment with 99%+ uptime and under $0.01 per call\",\n        \"required_protocols\": [\"ucp\"],\n    })\n    if match.get(\"agent_id\") == \"agent-dataenrich-prod\":\n        print(\"PASS: best_match returns our service for targeted query\")\n    else:\n        print(f\"INFO: best_match returned {match.get('agent_id')} -- \"\n              f\"consider improving your listing attributes\")\n\n    return True\n\n\nif __name__ == \"__main__\":\n    validate_discovery()\n    uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n```\n\n### Discovery Endpoint Checklist\n\n| Endpoint | Path | Format | Who Reads It |\n|---|---|---|---|\n| UCP Profile | `\u002F.well-known\u002Fucp` | JSON | UCP-compatible agents, GreenHelix marketplace indexer |\n| A2A Agent Card | `\u002F.well-known\u002Fagent.json` | JSON | Google A2A agents, autonomous fleets |\n| MCP Tools | `\u002Fmcp\u002Ftools` | JSON | Claude, Cursor, Windsurf, LLM-based agents |\n| AI Plugin | `\u002F.well-known\u002Fai-plugin.json` | JSON | ChatGPT, OpenAI-ecosystem agents |\n| OpenAPI Spec | `\u002F.well-known\u002Fopenapi.yaml` | YAML | All programmatic consumers |\n\n> **Key Takeaways**\n>\n> - Four `.well-known` endpoints cover the major agent discovery methods. Each takes minutes to implement and costs nothing to serve.\n> - UCP profile is the most comprehensive: capabilities, pricing, SLA, payment methods, and cross-references to other endpoints.\n> - MCP manifests let LLMs discover your tools. A2A agent cards let autonomous agents discover your capabilities.\n> - Validate discovery by searching for your own service via GreenHelix `search_services` and `best_match`.\n> - See P20 (Production Hardening) for rate-limiting and caching these endpoints at scale.\n\n---\n\n## Chapter 5: Structured Data & Schema.org for Agent Readability\n\n### Why Schema.org Wins for Agent Discovery\n\nSchema.org is the lingua franca of structured data on the web. Google, Bing, Yahoo, and Yandex jointly maintain it. Over 40 million websites use Schema.org markup. More importantly for agent commerce: every major AI shopping agent -- Google Gemini, ChatGPT, Perplexity, Claude -- parses Schema.org JSON-LD. When an agent encounters a `@type: Service` node with `offers`, `priceSpecification`, and `aggregateRating`, it extracts those fields into a comparable data structure regardless of which agent platform is doing the reading.\n\nThe alternative -- custom JSON schemas -- works for a single agent ecosystem but fails for cross-ecosystem discovery. An agent built for Google A2A might not understand your custom schema. An agent using ChatGPT's product search definitely will not. Schema.org is the only vocabulary that works everywhere.\n\n### JSON-LD for Digital Services\n\nPhysical products have standardized Schema.org types: `Product`, `Offer`, `AggregateOffer`. Digital services require a slightly different approach because they have properties that physical products do not: SLA terms, API latency, uptime guarantees, supported protocols, rate limits. The correct mapping uses `Service` as the primary type, with `Offer` for pricing and custom properties for service-specific attributes.\n\n```python\nimport json\nfrom datetime import datetime, timezone\n\n\ndef build_service_jsonld(\n    service_id: str,\n    name: str,\n    description: str,\n    provider_name: str,\n    provider_agent_id: str,\n    category: str,\n    pricing_tiers: list[dict],\n    sla: dict,\n    rating: dict | None = None,\n    supported_protocols: list[str] | None = None,\n    availability: str = \"InStock\",\n) -> dict:\n    \"\"\"Build Schema.org JSON-LD for a digital service.\n\n    Produces a document parseable by Google Shopping Graph, ChatGPT,\n    Perplexity Shopping, and GreenHelix marketplace indexer.\n    \"\"\"\n    jsonld = {\n        \"@context\": \"https:\u002F\u002Fschema.org\",\n        \"@type\": \"Service\",\n        \"@id\": f\"urn:greenhelix:service:{service_id}\",\n        \"name\": name,\n        \"description\": description,\n        \"serviceType\": category,\n        \"provider\": {\n            \"@type\": \"Organization\",\n            \"name\": provider_name,\n            \"identifier\": provider_agent_id,\n        },\n        \"offers\": [],\n        \"termsOfService\": f\"https:\u002F\u002Fapi.example.com\u002Ftos\u002F{service_id}\",\n        \"availableChannel\": {\n            \"@type\": \"ServiceChannel\",\n            \"serviceType\": \"API\",\n            \"availableLanguage\": [\"en\"],\n        },\n    }\n\n    # Add pricing tiers as offers\n    for tier in pricing_tiers:\n        offer = {\n            \"@type\": \"Offer\",\n            \"name\": tier[\"name\"],\n            \"price\": str(tier[\"cost_per_call\"]),\n            \"priceCurrency\": tier.get(\"currency\", \"USD\"),\n            \"availability\": f\"https:\u002F\u002Fschema.org\u002F{availability}\",\n            \"priceValidUntil\": tier.get(\n                \"valid_until\",\n                datetime(2026, 12, 31, tzinfo=timezone.utc).isoformat(),\n            ),\n            \"priceSpecification\": {\n                \"@type\": \"UnitPriceSpecification\",\n                \"price\": str(tier[\"cost_per_call\"]),\n                \"priceCurrency\": tier.get(\"currency\", \"USD\"),\n                \"unitText\": \"per API call\",\n                \"referenceQuantity\": {\n                    \"@type\": \"QuantitativeValue\",\n                    \"value\": 1,\n                    \"unitCode\": \"C62\",  # ISO unit for \"one\"\n                },\n            },\n        }\n        if \"monthly_cap\" in tier:\n            offer[\"priceSpecification\"][\"maxPrice\"] = str(tier[\"monthly_cap\"])\n        jsonld[\"offers\"].append(offer)\n\n    # Add SLA as custom properties (agents parse these for comparison)\n    if sla:\n        jsonld[\"additionalProperty\"] = [\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": \"uptimeGuarantee\",\n                \"value\": sla.get(\"uptime_guarantee\", 99.9),\n                \"unitText\": \"percent\",\n            },\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": \"latencyP99\",\n                \"value\": sla.get(\"latency_p99_ms\", 500),\n                \"unitText\": \"milliseconds\",\n            },\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": \"supportResponseTime\",\n                \"value\": sla.get(\"support_response_hours\", 24),\n                \"unitText\": \"hours\",\n            },\n        ]\n\n    # Add aggregate rating if available\n    if rating:\n        jsonld[\"aggregateRating\"] = {\n            \"@type\": \"AggregateRating\",\n            \"ratingValue\": rating[\"value\"],\n            \"bestRating\": 5,\n            \"ratingCount\": rating[\"count\"],\n        }\n\n    # Add protocol support as additional properties\n    if supported_protocols:\n        jsonld[\"additionalProperty\"].append({\n            \"@type\": \"PropertyValue\",\n            \"name\": \"supportedProtocols\",\n            \"value\": \", \".join(supported_protocols),\n        })\n\n    return jsonld\n\n\n# Generate JSON-LD for our service\nservice_schema = build_service_jsonld(\n    service_id=\"data-enrichment-v2\",\n    name=\"DataEnrich Pro\",\n    description=\"Real-time company data enrichment with 95% match rate across 200M+ companies. \"\n                \"Returns 50+ structured fields per company including firmographics, technographics, \"\n                \"and funding data.\",\n    provider_name=\"DataEnrich Inc.\",\n    provider_agent_id=\"agent-dataenrich-prod\",\n    category=\"data-enrichment\",\n    pricing_tiers=[\n        {\"name\": \"Starter\", \"cost_per_call\": \"0.005\", \"monthly_cap\": \"100.00\"},\n        {\"name\": \"Growth\", \"cost_per_call\": \"0.003\", \"monthly_cap\": \"500.00\"},\n    ],\n    sla={\n        \"uptime_guarantee\": 99.95,\n        \"latency_p99_ms\": 200,\n        \"support_response_hours\": 4,\n    },\n    rating={\"value\": 4.8, \"count\": 342},\n    supported_protocols=[\"ucp\", \"mcp\", \"a2a\"],\n)\n\nprint(json.dumps(service_schema, indent=2))\n```\n\n### Auto-Generating Structured Data via GreenHelix\n\nWhen you register a service on the GreenHelix marketplace, the gateway can auto-generate Schema.org JSON-LD from your registration data. This ensures consistency between your marketplace listing and your web-embedded structured data.\n\n```python\ndef register_and_generate_schema(\n    discovery_client,\n    service_data: dict,\n) -> tuple[dict, dict]:\n    \"\"\"Register a service on GreenHelix and generate matching Schema.org JSON-LD.\n\n    Returns (registration_result, jsonld_schema).\n    \"\"\"\n    # Register on marketplace\n    registration = discovery_client.execute(\"register_service\", {\n        \"agent_id\": service_data[\"provider_agent_id\"],\n        \"service_name\": service_data[\"name\"],\n        \"description\": service_data[\"description\"],\n        \"category\": service_data[\"category\"],\n        \"tags\": service_data.get(\"tags\", []),\n        \"pricing\": service_data[\"pricing\"],\n        \"sla\": service_data.get(\"sla\"),\n        \"protocols\": service_data.get(\"protocols\", []),\n    })\n\n    # Fetch the listing back to get canonical data\n    listing = discovery_client.execute(\"get_service\", {\n        \"service_id\": registration.get(\"service_id\", service_data[\"name\"]),\n    })\n\n    # Generate JSON-LD from canonical listing\n    schema = build_service_jsonld(\n        service_id=listing.get(\"service_id\", \"\"),\n        name=listing.get(\"service_name\", service_data[\"name\"]),\n        description=listing.get(\"description\", service_data[\"description\"]),\n        provider_name=service_data.get(\"provider_name\", \"\"),\n        provider_agent_id=listing.get(\"agent_id\", \"\"),\n        category=listing.get(\"category\", \"\"),\n        pricing_tiers=service_data.get(\"pricing_tiers\", []),\n        sla=listing.get(\"sla\", {}),\n        rating=listing.get(\"rating\"),\n        supported_protocols=listing.get(\"protocols\", []),\n    )\n\n    return registration, schema\n\n\n# Usage\nreg_result, jsonld = register_and_generate_schema(client, {\n    \"provider_agent_id\": \"agent-dataenrich-prod\",\n    \"provider_name\": \"DataEnrich Inc.\",\n    \"name\": \"DataEnrich Pro\",\n    \"description\": \"Real-time company data enrichment API\",\n    \"category\": \"data-enrichment\",\n    \"tags\": [\"enrichment\", \"company-data\", \"real-time\"],\n    \"pricing\": {\"model\": \"pay_per_call\", \"base_price\": \"0.005\", \"currency\": \"USD\"},\n    \"pricing_tiers\": [\n        {\"name\": \"Starter\", \"cost_per_call\": \"0.005\", \"monthly_cap\": \"100.00\"},\n    ],\n    \"sla\": {\"uptime_guarantee\": 99.95, \"latency_p99_ms\": 200, \"support_response_hours\": 4},\n    \"protocols\": [\"ucp\", \"mcp\", \"a2a\"],\n})\n```\n\n### Validation Script\n\nStructured data is only useful if it is valid. Agents that encounter malformed JSON-LD will skip your listing. This validation script catches the most common errors before they reach production:\n\n```python\ndef validate_service_jsonld(schema: dict) -> list[str]:\n    \"\"\"Validate a service JSON-LD document against common agent requirements.\n\n    Returns a list of validation errors (empty = valid).\n    \"\"\"\n    errors = []\n\n    # Required fields\n    if schema.get(\"@context\") != \"https:\u002F\u002Fschema.org\":\n        errors.append(\"Missing or incorrect @context (must be https:\u002F\u002Fschema.org)\")\n\n    if schema.get(\"@type\") != \"Service\":\n        errors.append(f\"@type must be 'Service', got '{schema.get('@type')}'\")\n\n    if not schema.get(\"name\"):\n        errors.append(\"Missing 'name' field\")\n\n    if not schema.get(\"description\"):\n        errors.append(\"Missing 'description' field\")\n    elif len(schema[\"description\"]) \u003C 50:\n        errors.append(f\"Description too short ({len(schema['description'])} chars). \"\n                      \"Agents need at least 50 chars for semantic matching.\")\n\n    # Pricing validation\n    offers = schema.get(\"offers\", [])\n    if not offers:\n        errors.append(\"No offers (pricing tiers). Agents cannot evaluate cost.\")\n\n    for i, offer in enumerate(offers):\n        if offer.get(\"@type\") != \"Offer\":\n            errors.append(f\"Offer {i}: @type must be 'Offer'\")\n\n        price = offer.get(\"price\")\n        if price is None:\n            errors.append(f\"Offer {i}: missing price\")\n        elif isinstance(price, float):\n            errors.append(f\"Offer {i}: price should be string, not float \"\n                         \"(floating-point precision issues)\")\n\n        if not offer.get(\"priceCurrency\"):\n            errors.append(f\"Offer {i}: missing priceCurrency\")\n\n    # Provider validation\n    provider = schema.get(\"provider\", {})\n    if not provider.get(\"identifier\"):\n        errors.append(\"Provider missing 'identifier' (agent_id)\")\n\n    # SLA properties\n    props = schema.get(\"additionalProperty\", [])\n    prop_names = {p.get(\"name\") for p in props}\n    recommended = {\"uptimeGuarantee\", \"latencyP99\", \"supportedProtocols\"}\n    missing = recommended - prop_names\n    if missing:\n        errors.append(f\"Missing recommended properties: {', '.join(missing)}\")\n\n    return errors\n\n\n# Validate our generated schema\nerrors = validate_service_jsonld(service_schema)\nif errors:\n    print(\"Validation errors:\")\n    for err in errors:\n        print(f\"  - {err}\")\nelse:\n    print(\"Schema is valid for agent consumption\")\n```\n\n### Embedding Structured Data in HTML\n\nFor services that also have human-readable web pages, embed the JSON-LD in a `\u003Cscript>` tag. This allows both web crawlers and AI agents to parse your structured data:\n\n```html\n\u003Cscript type=\"application\u002Fld+json\">\n{\n  \"@context\": \"https:\u002F\u002Fschema.org\",\n  \"@type\": \"Service\",\n  \"name\": \"DataEnrich Pro\",\n  \"description\": \"Real-time company data enrichment with 95% match rate...\",\n  \"offers\": [\n    {\n      \"@type\": \"Offer\",\n      \"name\": \"Starter\",\n      \"price\": \"0.005\",\n      \"priceCurrency\": \"USD\"\n    }\n  ]\n}\n\u003C\u002Fscript>\n```\n\n> **Key Takeaways**\n>\n> - Schema.org JSON-LD is the only structured data vocabulary parsed by all major agent platforms.\n> - Use `@type: Service` with `Offer` for pricing and `PropertyValue` for SLA terms and protocol support.\n> - Always use string-typed prices. Floating-point values cause comparison failures in agent scoring.\n> - Auto-generate JSON-LD from GreenHelix `register_service` data to keep marketplace listing and web markup in sync.\n> - Validate structured data before deploying. One malformed field can make your entire listing unparseable.\n> - See P18 (Pricing & Monetization) for advanced pricing structures including volume discounts and tiered billing.\n\n---\n\n## Chapter 6: Real-Time Catalog Sync & Graph Maintenance\n\n### Why Stale Data Kills Agent Transactions\n\nAI agents do not tolerate stale data. When an agent queries your service listing and finds a price of $0.005 per call, it commits to that price in its transaction planning. If the actual price has changed to $0.008 since the listing was last updated, the agent will encounter a price mismatch at transaction time. Most agents treat price mismatches as a trust violation and blacklist the service. A single stale data incident can remove your service from an agent's candidate set permanently.\n\nThe tolerance for staleness varies by data type:\n\n| Data Type | Maximum Acceptable Staleness | Impact of Stale Data |\n|---|---|---|\n| **Price** | 5 minutes | Transaction failure, trust violation, blacklisting |\n| **Availability** | 1 minute | Failed purchases, wasted agent compute cycles |\n| **Capability** | 1 hour | Capability mismatch errors, degraded results |\n| **SLA terms** | 24 hours | Contractual disputes, expectation mismatches |\n| **Trust score** | 1 hour | Incorrect agent ranking, suboptimal selection |\n\n### Webhook-Driven vs. Polling: The Architecture Decision\n\nTwo approaches exist for keeping discovery data current: **polling** (agents periodically fetch your data) and **webhooks** (you push updates when data changes). Polling is simpler to implement. Webhooks are superior for freshness.\n\nWith polling, the best case is that an agent checks your listing every minute and your data is at most 60 seconds stale. The worst case is that agents poll every hour (common for low-priority services) and your data is 60 minutes stale. You have no control over polling frequency -- it is determined by the agent.\n\nWith webhooks, you push updates the moment data changes. Freshness is limited only by network latency -- typically under 500 milliseconds. You control the timing. The tradeoff is implementation complexity: you need to manage subscriber lists, handle delivery failures, and implement retry logic.\n\nThe correct answer for agent commerce is both: serve fresh data at your discovery endpoints (for agents that poll) AND push updates via webhooks (for agents that subscribe).\n\n### GreenHelix Events and Webhooks\n\nThe GreenHelix gateway provides two tools for real-time updates: `publish_event` for broadcasting state changes, and `register_webhook` for subscribing to events from other services.\n\n```python\nimport hashlib\nimport hmac\nimport time\nfrom typing import Callable\n\n\nclass CatalogSyncManager:\n    \"\"\"Manages real-time synchronization between service catalog,\n    knowledge graph, structured data, and discovery endpoints.\"\"\"\n\n    def __init__(self, discovery_client, webhook_secret: str):\n        self.client = discovery_client\n        self.webhook_secret = webhook_secret\n        self.update_handlers: list[Callable] = []\n\n    def register_update_handler(self, handler: Callable) -> None:\n        \"\"\"Register a callback for catalog updates.\"\"\"\n        self.update_handlers.append(handler)\n\n    def publish_catalog_update(\n        self,\n        agent_id: str,\n        event_type: str,\n        service_id: str,\n        changes: dict,\n    ) -> dict:\n        \"\"\"Publish a catalog change event via GreenHelix.\"\"\"\n        event_data = {\n            \"service_id\": service_id,\n            \"changes\": changes,\n            \"timestamp\": time.time(),\n            \"version\": int(time.time() * 1000),\n        }\n\n        # Publish event to GreenHelix event bus\n        result = self.client.execute(\"publish_event\", {\n            \"agent_id\": agent_id,\n            \"event_type\": f\"catalog.{event_type}\",\n            \"payload\": event_data,\n        })\n\n        # Run local update handlers\n        for handler in self.update_handlers:\n            handler(event_type, service_id, changes)\n\n        return result\n\n    def register_for_updates(\n        self,\n        agent_id: str,\n        source_agent_id: str,\n        callback_url: str,\n        event_types: list[str],\n    ) -> dict:\n        \"\"\"Subscribe to catalog updates from another service via webhook.\"\"\"\n        return self.client.execute(\"register_webhook\", {\n            \"agent_id\": agent_id,\n            \"source_agent_id\": source_agent_id,\n            \"callback_url\": callback_url,\n            \"event_types\": event_types,\n        })\n\n    def verify_webhook_signature(\n        self,\n        payload: bytes,\n        signature: str,\n    ) -> bool:\n        \"\"\"Verify that a webhook payload was sent by GreenHelix.\"\"\"\n        expected = hmac.new(\n            self.webhook_secret.encode(),\n            payload,\n            hashlib.sha256,\n        ).hexdigest()\n        return hmac.compare_digest(expected, signature)\n\n\n# Initialize\nsync_manager = CatalogSyncManager(client, webhook_secret=\"your-secret-here\")\n```\n\n### Event-Driven Pipeline: Updating Graph + Structured Data + Endpoints\n\nWhen a catalog change occurs -- price update, new capability, SLA revision -- the pipeline must update three systems in sequence: the knowledge graph, the structured data (JSON-LD), and the discovery endpoints.\n\n```python\nclass DiscoveryPipeline:\n    \"\"\"End-to-end pipeline that updates all discovery surfaces when catalog changes.\"\"\"\n\n    def __init__(\n        self,\n        graph: \"CommerceKnowledgeGraph\",\n        sync_manager: CatalogSyncManager,\n        discovery_client: \"DiscoveryClient\",\n    ):\n        self.graph = graph\n        self.sync = sync_manager\n        self.client = discovery_client\n\n        # Register handlers for automatic propagation\n        self.sync.register_update_handler(self._on_catalog_update)\n\n    def _on_catalog_update(\n        self,\n        event_type: str,\n        service_id: str,\n        changes: dict,\n    ) -> None:\n        \"\"\"Handle a catalog update by propagating to all discovery surfaces.\"\"\"\n        print(f\"Processing {event_type} for {service_id}\")\n\n        # Step 1: Update knowledge graph\n        if service_id in self.graph.services:\n            service = self.graph.services[service_id]\n            if \"pricing\" in changes:\n                self._update_pricing(service, changes[\"pricing\"])\n            if \"sla\" in changes:\n                self._update_sla(service, changes[\"sla\"])\n            if \"capabilities\" in changes:\n                self._update_capabilities(service, changes[\"capabilities\"])\n            if \"status\" in changes:\n                service.status = changes[\"status\"]\n\n        # Step 2: Regenerate JSON-LD\n        jsonld = self.graph.to_jsonld()\n        self._write_jsonld(service_id, jsonld)\n\n        # Step 3: Update marketplace listing\n        self._sync_marketplace(service_id)\n\n        print(f\"Discovery surfaces updated for {service_id}\")\n\n    def _update_pricing(self, service: \"ServiceNode\", pricing: dict) -> None:\n        \"\"\"Update pricing tiers on a service node.\"\"\"\n        if \"tiers\" in pricing:\n            service.pricing_tiers = [\n                PricingTier(\n                    tier_name=t[\"name\"],\n                    cost_per_call=float(t[\"cost_per_call\"]),\n                    currency=t.get(\"currency\", \"USD\"),\n                    monthly_cap=float(t[\"monthly_cap\"]) if \"monthly_cap\" in t else None,\n                )\n                for t in pricing[\"tiers\"]\n            ]\n\n    def _update_sla(self, service: \"ServiceNode\", sla_data: dict) -> None:\n        \"\"\"Update SLA terms on a service node.\"\"\"\n        if service.sla:\n            for key, value in sla_data.items():\n                if hasattr(service.sla, key):\n                    setattr(service.sla, key, value)\n\n    def _update_capabilities(self, service: \"ServiceNode\", caps: list) -> None:\n        \"\"\"Update capability list (triggers MCP manifest regeneration).\"\"\"\n        service.tags = [c.get(\"name\", \"\") for c in caps if \"name\" in c]\n\n    def _write_jsonld(self, service_id: str, jsonld: list[dict]) -> None:\n        \"\"\"Write updated JSON-LD to file (or key-value store in production).\"\"\"\n        target = next(\n            (j for j in jsonld if service_id in j.get(\"@id\", \"\")),\n            None,\n        )\n        if target:\n            with open(f\"\u002Fvar\u002Fdata\u002Fschemas\u002F{service_id}.jsonld\", \"w\") as f:\n                json.dump(target, f, indent=2)\n\n    def _sync_marketplace(self, service_id: str) -> None:\n        \"\"\"Push updated data to GreenHelix marketplace.\"\"\"\n        if service_id not in self.graph.services:\n            return\n\n        service = self.graph.services[service_id]\n        cheapest = min(\n            service.pricing_tiers,\n            key=lambda t: t.cost_per_call,\n        ) if service.pricing_tiers else None\n\n        self.client.execute(\"update_service\", {\n            \"service_id\": service_id,\n            \"pricing\": {\n                \"model\": cheapest.billing_model if cheapest else \"contact\",\n                \"base_price\": str(cheapest.cost_per_call) if cheapest else \"0\",\n                \"currency\": cheapest.currency if cheapest else \"USD\",\n            },\n            \"sla\": {\n                \"uptime_guarantee\": service.sla.uptime_guarantee,\n                \"latency_p99_ms\": service.sla.latency_p99_ms,\n            } if service.sla else None,\n            \"status\": service.status,\n        })\n\n\n# Wire up the pipeline\npipeline = DiscoveryPipeline(graph, sync_manager, client)\n\n# Example: price change triggers automatic propagation\nsync_manager.publish_catalog_update(\n    agent_id=\"agent-dataenrich-prod\",\n    event_type=\"pricing_updated\",\n    service_id=\"data-enrichment-v2\",\n    changes={\n        \"pricing\": {\n            \"tiers\": [\n                {\"name\": \"starter\", \"cost_per_call\": \"0.004\", \"monthly_cap\": \"100.00\"},\n                {\"name\": \"growth\", \"cost_per_call\": \"0.0025\", \"monthly_cap\": \"500.00\"},\n            ],\n        },\n    },\n)\n```\n\n### Subscribing to External Catalog Updates\n\nWhen your agent depends on external services, subscribe to their catalog events so your graph stays current:\n\n```python\n# Subscribe to pricing updates from a dependency\nsync_manager.register_for_updates(\n    agent_id=\"agent-my-service\",\n    source_agent_id=\"agent-dataenrich-prod\",\n    callback_url=\"https:\u002F\u002Fmy-service.example.com\u002Fwebhooks\u002Fcatalog\",\n    event_types=[\"catalog.pricing_updated\", \"catalog.status_changed\"],\n)\n\n# Webhook receiver endpoint (add to your FastAPI app)\n@app.post(\"\u002Fwebhooks\u002Fcatalog\")\nasync def receive_catalog_webhook(request: Request):\n    \"\"\"Handle incoming catalog update webhooks from GreenHelix.\"\"\"\n    body = await request.body()\n    signature = request.headers.get(\"X-GreenHelix-Signature\", \"\")\n\n    if not sync_manager.verify_webhook_signature(body, signature):\n        return JSONResponse(status_code=401, content={\"error\": \"Invalid signature\"})\n\n    payload = json.loads(body)\n    event_type = payload.get(\"event_type\", \"\")\n    service_id = payload.get(\"service_id\", \"\")\n    changes = payload.get(\"changes\", {})\n\n    # Update our local graph with the external service's changes\n    pipeline._on_catalog_update(event_type, service_id, changes)\n\n    return {\"status\": \"accepted\"}\n```\n\n> **Key Takeaways**\n>\n> - Stale pricing data causes transaction failures and agent blacklisting. Maximum acceptable price staleness is 5 minutes.\n> - Implement both polling-friendly endpoints (always serve fresh data) and webhook-driven push updates.\n> - GreenHelix `publish_event` broadcasts catalog changes. `register_webhook` subscribes to changes from dependencies.\n> - Build a pipeline that propagates every catalog change to three surfaces: knowledge graph, JSON-LD, and marketplace listing.\n> - Always verify webhook signatures to prevent spoofed updates from corrupting your graph.\n> - See P20 (Production Hardening) for webhook retry policies and dead-letter queues.\n\n---\n\n## Chapter 7: Trust Signals & Reputation in Agent Discovery\n\n### Why Agents Rank by Trust, Not Just Price\n\nWhen an AI agent evaluates ten services that all claim 99.9% uptime and $0.005 per call, it needs a tiebreaker. That tiebreaker is trust. The agent cannot verify marketing claims at query time. It cannot call references. It cannot run a benchmark. What it can do is check cryptographic trust signals: verified metrics submitted through authenticated APIs, Merkle claim chains that prove history has not been tampered with, composite reputation scores computed from transaction history, and escrow completion rates that show how the service behaves under contractual obligations.\n\nTrust-based ranking is not hypothetical. The GreenHelix `best_match` tool uses trust score as a weighted factor in its ranking algorithm alongside price, SLA terms, and capability match. A service with a 0.92 trust score and $0.006 per call will rank above a service with no trust score and $0.004 per call for most agent configurations. The reason is risk-adjusted value: an agent that chooses the cheaper untrusted service has no recourse if the service fails, while the trusted service has verifiable history proving it delivers on its claims.\n\n### The Trust Signal Hierarchy\n\nNot all trust signals carry equal weight. Agents evaluate them in order of cryptographic strength:\n\n| Signal | Source | Forgery Difficulty | Agent Weight |\n|---|---|---|---|\n| **Merkle claim chain** | `build_claim_chain` | Computationally infeasible | Highest |\n| **Verified metrics** | `submit_metrics` | Requires compromised API key | High |\n| **Trust score** | `check_trust_score` | Composite -- reflects all signals | High |\n| **Agent verification** | `verify_agent` | Requires private key | Medium-High |\n| **Escrow completion rate** | Transaction history | Requires real transactions | Medium |\n| **Service ratings** | `rate_service` | Sybil-attackable without guards | Lower |\n\n### Surfacing Trust in UCP Profiles\n\nThe UCP profile from Chapter 4 included a `trust_score` field. This section shows how to populate it with real data from the GreenHelix trust and reputation systems.\n\n```python\nclass TrustEnrichedDiscovery:\n    \"\"\"Enriches discovery endpoints with real-time trust signals.\"\"\"\n\n    def __init__(self, discovery_client):\n        self.client = discovery_client\n\n    def get_trust_profile(self, agent_id: str) -> dict:\n        \"\"\"Fetch complete trust profile for an agent.\"\"\"\n        trust_data = {}\n\n        # Get verification status\n        try:\n            verification = self.client.execute(\"verify_agent\", {\n                \"agent_id\": agent_id,\n            })\n            trust_data[\"verified\"] = verification.get(\"verified\", False)\n            trust_data[\"verification_method\"] = verification.get(\"method\", \"unknown\")\n        except Exception:\n            trust_data[\"verified\"] = False\n\n        # Get trust score\n        try:\n            trust = self.client.execute(\"check_trust_score\", {\n                \"agent_id\": agent_id,\n            })\n            trust_data[\"trust_score\"] = trust.get(\"score\", 0.0)\n            trust_data[\"trust_factors\"] = trust.get(\"factors\", {})\n        except Exception:\n            trust_data[\"trust_score\"] = 0.0\n\n        # Get reputation metrics\n        try:\n            reputation = self.client.execute(\"get_agent_reputation\", {\n                \"agent_id\": agent_id,\n            })\n            trust_data[\"reputation\"] = {\n                \"trade_count\": reputation.get(\"trade_count\", 0),\n                \"success_rate\": reputation.get(\"success_rate\", 0.0),\n                \"avg_rating\": reputation.get(\"avg_rating\", 0.0),\n                \"active_since\": reputation.get(\"active_since\", \"\"),\n            }\n        except Exception:\n            trust_data[\"reputation\"] = {}\n\n        # Get claim chain depth (tamper-evidence)\n        try:\n            chains = self.client.execute(\"get_claim_chains\", {\n                \"agent_id\": agent_id,\n            })\n            chain_list = chains.get(\"chains\", [])\n            trust_data[\"claim_chain\"] = {\n                \"depth\": len(chain_list),\n                \"latest_root_hash\": chain_list[0].get(\"root_hash\", \"\") if chain_list else \"\",\n                \"covers_from\": chain_list[-1].get(\"timestamp\", \"\") if chain_list else \"\",\n                \"covers_to\": chain_list[0].get(\"timestamp\", \"\") if chain_list else \"\",\n            }\n        except Exception:\n            trust_data[\"claim_chain\"] = {\"depth\": 0}\n\n        return trust_data\n\n    def enrich_ucp_profile(self, ucp_profile: dict, agent_id: str) -> dict:\n        \"\"\"Add real-time trust signals to a UCP profile.\"\"\"\n        trust = self.get_trust_profile(agent_id)\n\n        ucp_profile[\"service\"][\"provider\"][\"trust_score\"] = trust.get(\"trust_score\", 0.0)\n        ucp_profile[\"service\"][\"provider\"][\"verified\"] = trust.get(\"verified\", False)\n        ucp_profile[\"service\"][\"provider\"][\"verification_method\"] = trust.get(\n            \"verification_method\", \"none\"\n        )\n\n        ucp_profile[\"trust\"] = {\n            \"score\": trust.get(\"trust_score\", 0.0),\n            \"factors\": trust.get(\"trust_factors\", {}),\n            \"reputation\": trust.get(\"reputation\", {}),\n            \"claim_chain\": trust.get(\"claim_chain\", {}),\n        }\n\n        # Update verification status\n        score = trust.get(\"trust_score\", 0.0)\n        if score >= 0.9:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"highly_trusted\"\n        elif score >= 0.7:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"verified\"\n        elif score >= 0.4:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"partially_verified\"\n        else:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"unverified\"\n\n        return ucp_profile\n\n\n# Enrich our UCP profile with real trust data\ntrust_discovery = TrustEnrichedDiscovery(client)\nenriched_profile = trust_discovery.enrich_ucp_profile(\n    ucp_profile,\n    agent_id=\"agent-dataenrich-prod\",\n)\nprint(f\"Trust score: {enriched_profile['trust']['score']}\")\nprint(f\"Claim chain depth: {enriched_profile['trust']['claim_chain']['depth']}\")\n```\n\n### Building Your Trust Profile\n\nTrust is not just consumed by agents during discovery -- it must be built over time. Here is the lifecycle for establishing a credible trust profile:\n\n```python\nclass TrustBuilder:\n    \"\"\"Tools for building a verifiable trust profile on GreenHelix.\"\"\"\n\n    def __init__(self, discovery_client, agent_id: str):\n        self.client = discovery_client\n        self.agent_id = agent_id\n\n    def submit_performance_metrics(self, metrics: dict) -> dict:\n        \"\"\"Submit verified performance metrics.\n\n        Call this regularly (daily or after each significant batch).\n        Consistent submissions build trust; gaps raise red flags.\n        \"\"\"\n        return self.client.execute(\"submit_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"metrics\": metrics,\n        })\n\n    def build_claim_chain(self) -> dict:\n        \"\"\"Build a Merkle claim chain over recent metric submissions.\n\n        Call this weekly. The chain creates a tamper-evident history\n        that agents can verify independently.\n        \"\"\"\n        return self.client.execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def get_trust_improvement_plan(self) -> list[dict]:\n        \"\"\"Analyze current trust profile and recommend improvements.\"\"\"\n        trust = self.client.execute(\"check_trust_score\", {\n            \"agent_id\": self.agent_id,\n        })\n        score = trust.get(\"score\", 0.0)\n        factors = trust.get(\"factors\", {})\n\n        recommendations = []\n\n        if factors.get(\"metric_submissions\", 0) \u003C 30:\n            recommendations.append({\n                \"action\": \"Submit daily metrics for 30+ days\",\n                \"impact\": \"high\",\n                \"current\": factors.get(\"metric_submissions\", 0),\n                \"target\": 30,\n            })\n\n        if factors.get(\"claim_chain_depth\", 0) \u003C 4:\n            recommendations.append({\n                \"action\": \"Build weekly claim chains for 4+ weeks\",\n                \"impact\": \"high\",\n                \"current\": factors.get(\"claim_chain_depth\", 0),\n                \"target\": 4,\n            })\n\n        if factors.get(\"trade_count\", 0) \u003C 50:\n            recommendations.append({\n                \"action\": \"Complete 50+ successful transactions\",\n                \"impact\": \"medium\",\n                \"current\": factors.get(\"trade_count\", 0),\n                \"target\": 50,\n            })\n\n        if factors.get(\"escrow_completion_rate\", 0) \u003C 0.95:\n            recommendations.append({\n                \"action\": \"Improve escrow completion rate above 95%\",\n                \"impact\": \"high\",\n                \"current\": factors.get(\"escrow_completion_rate\", 0),\n                \"target\": 0.95,\n            })\n\n        return recommendations\n\n\n# Build trust over time\nbuilder = TrustBuilder(client, \"agent-dataenrich-prod\")\n\n# Submit today's metrics\nbuilder.submit_performance_metrics({\n    \"uptime_pct\": 99.97,\n    \"latency_p99_ms\": 187,\n    \"requests_processed\": 45230,\n    \"error_rate\": 0.0003,\n    \"match_rate\": 0.952,\n})\n\n# Weekly: build claim chain\nchain_result = builder.build_claim_chain()\nprint(f\"Claim chain built: {chain_result.get('root_hash', '')[:16]}...\")\n\n# Check what to improve\nplan = builder.get_trust_improvement_plan()\nfor rec in plan:\n    print(f\"[{rec['impact'].upper()}] {rec['action']} \"\n          f\"(current: {rec['current']}, target: {rec['target']})\")\n```\n\n### Trust in JSON-LD Structured Data\n\nExtend your Schema.org JSON-LD to include trust signals so agents parsing your web-embedded structured data also get trust information:\n\n```python\ndef add_trust_to_jsonld(jsonld: dict, trust_profile: dict) -> dict:\n    \"\"\"Add trust signals to a Schema.org JSON-LD service document.\"\"\"\n    props = jsonld.setdefault(\"additionalProperty\", [])\n\n    props.append({\n        \"@type\": \"PropertyValue\",\n        \"name\": \"trustScore\",\n        \"value\": trust_profile.get(\"trust_score\", 0.0),\n        \"description\": \"GreenHelix composite trust score (0-1)\",\n    })\n\n    props.append({\n        \"@type\": \"PropertyValue\",\n        \"name\": \"claimChainDepth\",\n        \"value\": trust_profile.get(\"claim_chain\", {}).get(\"depth\", 0),\n        \"description\": \"Merkle claim chain depth (tamper-evidence)\",\n    })\n\n    if trust_profile.get(\"reputation\", {}).get(\"trade_count\", 0) > 0:\n        props.append({\n            \"@type\": \"PropertyValue\",\n            \"name\": \"verifiedTradeCount\",\n            \"value\": trust_profile[\"reputation\"][\"trade_count\"],\n            \"description\": \"Number of completed escrow-verified transactions\",\n        })\n\n    if trust_profile.get(\"verified\"):\n        props.append({\n            \"@type\": \"PropertyValue\",\n            \"name\": \"identityVerified\",\n            \"value\": True,\n            \"description\": \"Ed25519 cryptographic identity verification\",\n        })\n\n    return jsonld\n\n\n# Add trust to our JSON-LD\ntrust_profile = trust_discovery.get_trust_profile(\"agent-dataenrich-prod\")\nenriched_jsonld = add_trust_to_jsonld(service_schema, trust_profile)\n```\n\n> **Key Takeaways**\n>\n> - Agents rank by trust-adjusted value, not raw price. A trusted service at a higher price beats an untrusted service at a lower price.\n> - Trust signals have a hierarchy: Merkle claim chains (strongest) > verified metrics > trust score > agent verification > ratings (weakest).\n> - Enrich UCP profiles with real-time trust data from `check_trust_score`, `verify_agent`, `get_agent_reputation`, and `get_claim_chains`.\n> - Build trust over time: submit daily metrics, build weekly claim chains, complete escrow transactions, maintain high completion rates.\n> - Embed trust signals in Schema.org JSON-LD so agents that discover you via web crawling also get trust information.\n> - See P5 (Trust & Verification) for the complete trust-building playbook and Merkle claim chain deep-dive.\n\n---\n\n## Chapter 8: Measuring Discovery Performance\n\n### The Metrics That Matter\n\nDiscovery is not a binary state. You are not simply \"discoverable\" or \"not discoverable.\" Discovery performance exists on a spectrum, and measuring it requires specific metrics that most commerce analytics dashboards do not track. Traditional analytics measure page views, click-through rates, and conversion funnels designed for human visitors. Agent discovery requires a different set of metrics.\n\n**Discovery Rate** -- The percentage of relevant agent queries that return your service in the results. If agents make 1,000 queries that match your service's capabilities and your service appears in 340 of those result sets, your discovery rate is 34%. This is the top-of-funnel metric for agent commerce.\n\n**Agent Conversion Rate** -- The percentage of discovered services that proceed to a transaction. If your service appears in 340 query results and 68 of those result in a completed transaction, your agent conversion rate is 20%. This measures how compelling your listing is once found.\n\n**Time-to-Transaction** -- The elapsed time from an agent's first discovery query to transaction completion. Shorter is better. Long times indicate friction in your protocol endpoints, slow API responses, or missing structured data that forces agents to make additional queries.\n\n**Ranking Position** -- Where your service appears in search results. Position 1-3 captures the vast majority of agent transactions. Position 10+ is functionally invisible because most agents evaluate only the top results.\n\n**Trust-Adjusted Rank** -- Your ranking position after trust score weighting. A service with strong capabilities but weak trust will rank lower than a service with strong trust. This metric tells you whether trust is helping or hurting your discoverability.\n\n### GreenHelix Analytics\n\nThe GreenHelix gateway provides analytics tools that measure these metrics directly:\n\n```python\nclass DiscoveryAnalytics:\n    \"\"\"Track and analyze agent discovery performance.\"\"\"\n\n    def __init__(self, discovery_client, agent_id: str):\n        self.client = discovery_client\n        self.agent_id = agent_id\n\n    def get_discovery_metrics(self, period: str = \"30d\") -> dict:\n        \"\"\"Fetch discovery performance metrics from GreenHelix.\"\"\"\n        usage = self.client.execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"metrics\": [\n                \"search_appearances\",\n                \"search_impressions\",\n                \"best_match_wins\",\n                \"api_calls\",\n                \"transactions_completed\",\n                \"transaction_value\",\n            ],\n        })\n\n        revenue = self.client.execute(\"get_revenue_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n        # Calculate derived metrics\n        appearances = usage.get(\"search_appearances\", 0)\n        transactions = usage.get(\"transactions_completed\", 0)\n        best_match_wins = usage.get(\"best_match_wins\", 0)\n\n        return {\n            \"period\": period,\n            \"raw_metrics\": usage,\n            \"revenue\": revenue,\n            \"derived\": {\n                \"discovery_rate\": (\n                    appearances \u002F usage.get(\"search_impressions\", 1)\n                    if usage.get(\"search_impressions\", 0) > 0\n                    else 0.0\n                ),\n                \"conversion_rate\": (\n                    transactions \u002F appearances\n                    if appearances > 0\n                    else 0.0\n                ),\n                \"best_match_rate\": (\n                    best_match_wins \u002F appearances\n                    if appearances > 0\n                    else 0.0\n                ),\n                \"avg_transaction_value\": (\n                    usage.get(\"transaction_value\", 0) \u002F transactions\n                    if transactions > 0\n                    else 0.0\n                ),\n                \"revenue_per_impression\": (\n                    revenue.get(\"total_revenue\", 0) \u002F usage.get(\"search_impressions\", 1)\n                    if usage.get(\"search_impressions\", 0) > 0\n                    else 0.0\n                ),\n            },\n        }\n\n    def compare_periods(self, current: str = \"7d\", previous: str = \"7d\") -> dict:\n        \"\"\"Compare discovery metrics between two periods.\"\"\"\n        current_metrics = self.get_discovery_metrics(current)\n        previous_metrics = self.get_discovery_metrics(previous)\n\n        comparison = {}\n        for key in current_metrics[\"derived\"]:\n            curr_val = current_metrics[\"derived\"][key]\n            prev_val = previous_metrics[\"derived\"].get(key, 0)\n            if prev_val > 0:\n                change_pct = ((curr_val - prev_val) \u002F prev_val) * 100\n            else:\n                change_pct = 100.0 if curr_val > 0 else 0.0\n            comparison[key] = {\n                \"current\": curr_val,\n                \"previous\": prev_val,\n                \"change_pct\": round(change_pct, 2),\n            }\n\n        return comparison\n\n    def discovery_health_check(self) -> list[dict]:\n        \"\"\"Run a comprehensive discovery health check.\n\n        Returns a list of checks with pass\u002Ffail\u002Fwarn status.\n        \"\"\"\n        checks = []\n\n        # Check 1: UCP endpoint responds\n        try:\n            # Simulate by verifying our service is registered\n            service = self.client.execute(\"get_service\", {\n                \"agent_id\": self.agent_id,\n            })\n            checks.append({\n                \"check\": \"marketplace_listing\",\n                \"status\": \"pass\" if service else \"fail\",\n                \"detail\": \"Service is registered on GreenHelix marketplace\",\n            })\n        except Exception as e:\n            checks.append({\n                \"check\": \"marketplace_listing\",\n                \"status\": \"fail\",\n                \"detail\": f\"Service not found: {e}\",\n            })\n\n        # Check 2: Trust score above threshold\n        try:\n            trust = self.client.execute(\"check_trust_score\", {\n                \"agent_id\": self.agent_id,\n            })\n            score = trust.get(\"score\", 0.0)\n            checks.append({\n                \"check\": \"trust_score\",\n                \"status\": \"pass\" if score >= 0.7 else \"warn\" if score >= 0.4 else \"fail\",\n                \"detail\": f\"Trust score: {score} (threshold: 0.7)\",\n                \"value\": score,\n            })\n        except Exception:\n            checks.append({\n                \"check\": \"trust_score\",\n                \"status\": \"fail\",\n                \"detail\": \"Unable to fetch trust score\",\n            })\n\n        # Check 3: Recent metrics submissions\n        try:\n            claims = self.client.execute(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claim_count = len(claims.get(\"claims\", []))\n            checks.append({\n                \"check\": \"metric_submissions\",\n                \"status\": \"pass\" if claim_count >= 7 else \"warn\" if claim_count >= 1 else \"fail\",\n                \"detail\": f\"{claim_count} verified claims (target: 7+ for weekly)\",\n                \"value\": claim_count,\n            })\n        except Exception:\n            checks.append({\n                \"check\": \"metric_submissions\",\n                \"status\": \"fail\",\n                \"detail\": \"Unable to fetch verified claims\",\n            })\n\n        # Check 4: Claim chain exists\n        try:\n            chains = self.client.execute(\"get_claim_chains\", {\n                \"agent_id\": self.agent_id,\n            })\n            depth = len(chains.get(\"chains\", []))\n            checks.append({\n                \"check\": \"claim_chain\",\n                \"status\": \"pass\" if depth >= 4 else \"warn\" if depth >= 1 else \"fail\",\n                \"detail\": f\"Claim chain depth: {depth} (target: 4+ for monthly)\",\n                \"value\": depth,\n            })\n        except Exception:\n            checks.append({\n                \"check\": \"claim_chain\",\n                \"status\": \"warn\",\n                \"detail\": \"Unable to fetch claim chains\",\n            })\n\n        # Check 5: Search visibility\n        metrics = self.get_discovery_metrics(\"7d\")\n        dr = metrics[\"derived\"][\"discovery_rate\"]\n        checks.append({\n            \"check\": \"discovery_rate\",\n            \"status\": \"pass\" if dr >= 0.3 else \"warn\" if dr >= 0.1 else \"fail\",\n            \"detail\": f\"Discovery rate: {dr:.1%} (target: 30%+)\",\n            \"value\": dr,\n        })\n\n        # Check 6: Conversion\n        cr = metrics[\"derived\"][\"conversion_rate\"]\n        checks.append({\n            \"check\": \"conversion_rate\",\n            \"status\": \"pass\" if cr >= 0.15 else \"warn\" if cr >= 0.05 else \"fail\",\n            \"detail\": f\"Conversion rate: {cr:.1%} (target: 15%+)\",\n            \"value\": cr,\n        })\n\n        return checks\n\n\n# Run discovery analytics\nanalytics = DiscoveryAnalytics(client, \"agent-dataenrich-prod\")\n\n# Get current metrics\nmetrics = analytics.get_discovery_metrics(\"30d\")\nprint(f\"Discovery rate: {metrics['derived']['discovery_rate']:.1%}\")\nprint(f\"Conversion rate: {metrics['derived']['conversion_rate']:.1%}\")\nprint(f\"Best match rate: {metrics['derived']['best_match_rate']:.1%}\")\nprint(f\"Revenue per impression: ${metrics['derived']['revenue_per_impression']:.4f}\")\n\n# Week-over-week comparison\ncomparison = analytics.compare_periods(\"7d\", \"7d\")\nfor metric, data in comparison.items():\n    direction = \"up\" if data[\"change_pct\"] > 0 else \"down\"\n    print(f\"{metric}: {data['current']:.4f} ({direction} {abs(data['change_pct'])}%)\")\n\n# Health check\nhealth = analytics.discovery_health_check()\nfor check in health:\n    icon = {\"pass\": \"OK\", \"warn\": \"WARN\", \"fail\": \"FAIL\"}[check[\"status\"]]\n    print(f\"[{icon}] {check['check']}: {check['detail']}\")\n```\n\n### A\u002FB Testing Structured Data\n\nDifferent structured data configurations produce different discovery outcomes. A\u002FB testing lets you determine which configuration maximizes your metrics. The approach is straightforward: run two versions of your structured data simultaneously (served to different agent cohorts) and compare performance.\n\n```python\nclass StructuredDataExperiment:\n    \"\"\"A\u002FB test different structured data configurations.\"\"\"\n\n    def __init__(self, discovery_client, agent_id: str):\n        self.client = discovery_client\n        self.agent_id = agent_id\n\n    def run_experiment(\n        self,\n        variant_a: dict,\n        variant_b: dict,\n        description: str,\n        duration_days: int = 14,\n    ) -> dict:\n        \"\"\"Set up an A\u002FB test between two structured data configurations.\n\n        In practice, you would deploy both variants and route traffic\n        based on a hash of the requesting agent's ID. This method\n        registers both variants and returns the experiment config.\n        \"\"\"\n        experiment = {\n            \"experiment_id\": f\"exp_{int(time.time())}\",\n            \"description\": description,\n            \"duration_days\": duration_days,\n            \"variant_a\": {\n                \"config\": variant_a,\n                \"label\": \"control\",\n            },\n            \"variant_b\": {\n                \"config\": variant_b,\n                \"label\": \"treatment\",\n            },\n        }\n\n        # Publish experiment start event for tracking\n        self.client.execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"experiment.started\",\n            \"payload\": {\n                \"experiment_id\": experiment[\"experiment_id\"],\n                \"description\": description,\n                \"variants\": [\"a\", \"b\"],\n            },\n        })\n\n        return experiment\n\n    def analyze_results(\n        self,\n        experiment_id: str,\n        variant_a_metrics: dict,\n        variant_b_metrics: dict,\n    ) -> dict:\n        \"\"\"Compare two variants and declare a winner.\"\"\"\n        results = {}\n        for metric in [\"discovery_rate\", \"conversion_rate\", \"revenue_per_impression\"]:\n            a_val = variant_a_metrics.get(metric, 0)\n            b_val = variant_b_metrics.get(metric, 0)\n            lift = ((b_val - a_val) \u002F a_val * 100) if a_val > 0 else 0\n\n            results[metric] = {\n                \"variant_a\": a_val,\n                \"variant_b\": b_val,\n                \"lift_pct\": round(lift, 2),\n                \"winner\": \"b\" if b_val > a_val else \"a\" if a_val > b_val else \"tie\",\n            }\n\n        return results\n\n\n# Example: test whether detailed SLA properties improve discovery\nexperiment = StructuredDataExperiment(client, \"agent-dataenrich-prod\")\nexp = experiment.run_experiment(\n    variant_a={\n        \"sla_properties\": [\"uptimeGuarantee\"],  # Minimal SLA info\n    },\n    variant_b={\n        \"sla_properties\": [  # Full SLA info\n            \"uptimeGuarantee\", \"latencyP99\",\n            \"supportResponseTime\", \"dataRetentionDays\",\n        ],\n    },\n    description=\"Test whether detailed SLA properties improve agent discovery rate\",\n    duration_days=14,\n)\nprint(f\"Experiment started: {exp['experiment_id']}\")\n```\n\n### Discovery Dashboard\n\nCombine all metrics into a single dashboard view:\n\n```python\ndef print_discovery_dashboard(analytics: DiscoveryAnalytics) -> None:\n    \"\"\"Print a comprehensive discovery performance dashboard.\"\"\"\n    metrics = analytics.get_discovery_metrics(\"30d\")\n    health = analytics.discovery_health_check()\n    comparison = analytics.compare_periods(\"7d\", \"7d\")\n\n    print(\"=\" * 60)\n    print(\"DISCOVERY PERFORMANCE DASHBOARD\")\n    print(\"=\" * 60)\n\n    print(\"\\n--- 30-Day Metrics ---\")\n    d = metrics[\"derived\"]\n    print(f\"Discovery Rate:          {d['discovery_rate']:.1%}\")\n    print(f\"Conversion Rate:         {d['conversion_rate']:.1%}\")\n    print(f\"Best Match Win Rate:     {d['best_match_rate']:.1%}\")\n    print(f\"Avg Transaction Value:   ${d['avg_transaction_value']:.4f}\")\n    print(f\"Revenue per Impression:  ${d['revenue_per_impression']:.6f}\")\n\n    print(\"\\n--- Week-over-Week Changes ---\")\n    for metric, data in comparison.items():\n        arrow = \"+\" if data[\"change_pct\"] > 0 else \"\"\n        print(f\"{metric:30s} {arrow}{data['change_pct']}%\")\n\n    print(\"\\n--- Health Checks ---\")\n    for check in health:\n        status_label = {\"pass\": \"PASS\", \"warn\": \"WARN\", \"fail\": \"FAIL\"}[check[\"status\"]]\n        print(f\"[{status_label:4s}] {check['check']:25s} {check['detail']}\")\n\n    print(\"\\n\" + \"=\" * 60)\n\n\n# Run the dashboard\nprint_discovery_dashboard(analytics)\n```\n\n### Debugging Checklist\n\nWhen discovery metrics are underperforming, work through this checklist in order:\n\n| # | Check | Tool \u002F Method | Expected Result | Common Fix |\n|---|---|---|---|---|\n| 1 | Is service registered? | `get_service` | Returns service data | Run `register_service` |\n| 2 | Does `search_services` find you? | `search_services` with your category | Service in results | Improve description keywords |\n| 3 | Does `best_match` select you? | `best_match` with specific requirements | Your service returned | Improve trust score, lower price, add capabilities |\n| 4 | Is UCP endpoint live? | `GET \u002F.well-known\u002Fucp` | 200 with valid JSON | Deploy endpoint (Chapter 4) |\n| 5 | Is A2A card live? | `GET \u002F.well-known\u002Fagent.json` | 200 with valid JSON | Deploy agent card (Chapter 4) |\n| 6 | Is MCP manifest live? | `GET \u002Fmcp\u002Ftools` | 200 with tools array | Deploy MCP manifest (Chapter 4) |\n| 7 | Is JSON-LD valid? | `validate_service_jsonld()` | No errors | Fix validation errors (Chapter 5) |\n| 8 | Is pricing current? | Compare listing vs actual price | Match | Trigger catalog sync (Chapter 6) |\n| 9 | Is trust score adequate? | `check_trust_score` | >= 0.7 | Submit metrics, build claim chains (Chapter 7) |\n| 10 | Are webhook events flowing? | `publish_event` + check subscriber count | Events published | Register webhooks (Chapter 6) |\n\nIf all ten checks pass and discovery rate is still below 30%, the issue is competitive: other services in your category have stronger listings. Improve your `description_for_model` with more specific keywords, add capabilities, lower pricing, or increase trust score through consistent metric submissions and claim chain building.\n\n> **Key Takeaways**\n>\n> - Five metrics define discovery performance: discovery rate, agent conversion rate, time-to-transaction, ranking position, and trust-adjusted rank.\n> - GreenHelix `get_usage_analytics` and `get_revenue_metrics` provide the raw data. Derive discovery rate and conversion rate from search appearances and completed transactions.\n> - A\u002FB test structured data configurations to find the optimal attribute set. More SLA detail often improves discovery rate.\n> - Run weekly health checks. A single failing check (expired trust, stale pricing, missing endpoint) can collapse discovery metrics.\n> - The 10-point debugging checklist covers the full discovery stack from registration to trust to endpoint availability.\n> - See P21 (Agent-Ready Commerce) Chapter 7 for the complete agent discoverability test harness.\n\n---\n\n## Conclusion: The Discovery Flywheel\n\nDiscovery in agent commerce is not a one-time setup task. It is a flywheel with four stages:\n\n1. **Build** -- Knowledge graph, structured data, protocol endpoints (Chapters 2-5)\n2. **Publish** -- Register on marketplace, push events, keep data fresh (Chapter 6)\n3. **Trust** -- Submit metrics, build claim chains, maintain reputation (Chapter 7)\n4. **Measure** -- Track discovery rate, conversion, ranking. Feed improvements back into Build (Chapter 8)\n\nEach rotation through the flywheel makes the next one more effective. A service with six months of consistent metric submissions, deep claim chains, hundreds of completed transactions, and optimized structured data will compound its discovery advantage over competitors who started later or maintain their listings less diligently.\n\nThe 805% year-over-year growth in AI-referred traffic is not slowing down. The services that invest in discovery infrastructure today will capture a disproportionate share of that traffic tomorrow. The services that do not will join the 40% that agents cannot see.\n\nStart with Chapter 2. Build your graph. Implement UCP. Submit your first metrics. The flywheel starts with a single rotation.\n\n---\n\n*This guide uses the GreenHelix A2A Commerce Gateway (128 tools, `https:\u002F\u002Fapi.greenhelix.net\u002Fv1`). For related topics, see: P21 (Agent-Ready Commerce) for agent-ready storefronts, P18 (Pricing & Monetization) for advanced pricing structures, P5 (Trust & Verification) for the complete trust-building playbook, and P20 (Production Hardening) for deploying discovery infrastructure at scale.*\n\n","# Agent Commerce Discovery\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nForty percent of digital commerce services are invisible to AI agents. Not because the services are bad, but because they are structured for humans -- HTML pages, marketing copy, PDF brochures -- and agents cannot parse any of it. The services exist, the demand exists, and the agents have budgets to spend. But the transaction never happens because the agent never finds the service. This is the discovery gap, and it is the single largest source of lost revenue in the agentic economy.\nBetween January 2025 and March 2026, AI-referred traffic to commerce services grew 805% year-over-year. Google Shopping Graph now indexes over 45 billion product listings with structured attributes. ChatGPT's product search handles 2.3 million commerce queries per day. Perplexity Shopping launched with 30+ retail partners and AI-native product cards. The agents are shopping. The question is whether they can find you.\nThis guide is the practitioner's manual for making your services discoverable to AI agents. It covers the full stack: knowledge graphs that model your service catalog as machine-readable entities, protocol endpoints that announce your capabilities through UCP, MCP, A2A, and ACP, structured data that agents can parse and compare, real-time catalog synchronization that prevents stale listings, trust signals that help agents rank you above competitors, and analytics that measure whether discovery is actually converting into transactions. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint.\n\n## What You'll Learn\n- Chapter 1: The Discovery Problem\n- Chapter 2: Commerce Knowledge Graphs from Scratch\n- Chapter 3: The Protocol Stack: UCP, MCP, A2A, ACP\n- Chapter 4: Building .well-known Discovery Endpoints\n- Chapter 5: Structured Data & Schema.org for Agent Readability\n- Chapter 6: Real-Time Catalog Sync & Graph Maintenance\n- Chapter 7: Trust Signals & Reputation in Agent Discovery\n- Chapter 8: Measuring Discovery Performance\n- Conclusion: The Discovery Flywheel\n\n## Full Guide\n\n# Agent Commerce Discovery: Knowledge Graphs, Protocol Endpoints & Structured Data for AI-Discoverable Services\n\nForty percent of digital commerce services are invisible to AI agents. Not because the services are bad, but because they are structured for humans -- HTML pages, marketing copy, PDF brochures -- and agents cannot parse any of it. The services exist, the demand exists, and the agents have budgets to spend. But the transaction never happens because the agent never finds the service. This is the discovery gap, and it is the single largest source of lost revenue in the agentic economy.\n\nBetween January 2025 and March 2026, AI-referred traffic to commerce services grew 805% year-over-year. Google Shopping Graph now indexes over 45 billion product listings with structured attributes. ChatGPT's product search handles 2.3 million commerce queries per day. Perplexity Shopping launched with 30+ retail partners and AI-native product cards. The agents are shopping. The question is whether they can find you.\n\nThis guide is the practitioner's manual for making your services discoverable to AI agents. It covers the full stack: knowledge graphs that model your service catalog as machine-readable entities, protocol endpoints that announce your capabilities through UCP, MCP, A2A, and ACP, structured data that agents can parse and compare, real-time catalog synchronization that prevents stale listings, trust signals that help agents rank you above competitors, and analytics that measure whether discovery is actually converting into transactions. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint.\n\n---\n\n## Table of Contents\n\n1. [The Discovery Problem](#chapter-1-the-discovery-problem)\n2. [Commerce Knowledge Graphs from Scratch](#chapter-2-commerce-knowledge-graphs-from-scratch)\n3. [The Protocol Stack: UCP, MCP, A2A, ACP](#chapter-3-the-protocol-stack-ucp-mcp-a2a-acp)\n4. [Building .well-known Discovery Endpoints](#chapter-4-building-well-known-discovery-endpoints)\n5. [Structured Data & Schema.org for Agent Readability](#chapter-5-structured-data--schemaorg-for-agent-readability)\n6. [Real-Time Catalog Sync & Graph Maintenance](#chapter-6-real-time-catalog-sync--graph-maintenance)\n7. [Trust Signals & Reputation in Agent Discovery](#chapter-7-trust-signals--reputation-in-agent-discovery)\n8. [Measuring Discovery Performance](#chapter-8-measuring-discovery-performance)\n\n---\n\n## Chapter 1: The Discovery Problem\n\n### Why 40% of Commerce Services Are Invisible\n\nThe number comes from a March 2026 analysis by Forrester: of 2,400 digital service providers surveyed, 40.3% had no machine-readable service description of any kind -- no JSON-LD, no OpenAPI spec, no agent card, no structured catalog. Their services existed only as human-readable web pages. For AI agents performing commerce queries, these services might as well not exist.\n\nThe root cause is architectural. Traditional web commerce optimized for a single consumer: a human with a browser. The human reads marketing copy, interprets images, navigates menus, and fills out checkout forms. Every element of the commerce experience -- product descriptions, pricing pages, comparison charts, testimonials -- is designed for visual consumption by a person sitting at a screen. AI agents consume none of this. An agent does not \"see\" your landing page. It sends structured queries to discovery endpoints, parses JSON responses, compares attributes programmatically, and executes transactions via API. If your service is not described in a format agents can query, you are invisible to the fastest-growing channel in digital commerce.\n\n### The Shift from Human Browsing to Agent Crawling\n\nHuman discovery follows a browse-and-click pattern: Google search, scan results, click through, read page, compare tabs, make decision. The entire flow assumes visual attention and manual navigation. Agent discovery follows a query-and-parse pattern: send structured query, receive structured response, compare attributes algorithmically, execute highest-ranked option. The flows have almost nothing in common.\n\n| Dimension | Human Browsing | Agent Crawling |\n|---|---|---|\n| **Discovery method** | Keyword search, link following | Structured API queries, `.well-known` endpoint crawling |\n| **Content format** | HTML, images, video | JSON-LD, OpenAPI specs, agent cards |\n| **Comparison method** | Visual side-by-side, gut feeling | Programmatic attribute matching, scoring algorithms |\n| **Decision speed** | Minutes to days | Milliseconds to seconds |\n| **Price sensitivity** | Influenced by anchoring, framing | Exact numerical comparison with configurable thresholds |\n| **Trust evaluation** | Reviews, brand recognition | Cryptographic verification, trust scores, claim chains |\n| **Transaction method** | Shopping cart, checkout form | API call with payment proof |\n\nThe implication is stark: optimizing for human browsing does nothing for agent crawling. A beautifully designed landing page with compelling copy and high-resolution product photos generates zero signal for an agent that queries the REST API (`POST \u002Fv1\u002F{tool}`) with `{\"tool\": \"search_services\", \"input\": {\"query\": \"data enrichment API under $0.01 per call with 99.9% uptime SLA\"}}`. The agent needs structured attributes, machine-readable pricing, and verifiable SLA terms. It needs to find your service through a discovery protocol, not a Google search.\n\n### How the Major Platforms Do Discovery\n\n**Google Shopping Graph** indexes 45 billion product listings by crawling structured data from merchant websites. It prioritizes Merchant Center feeds (structured XML\u002FJSON), followed by Schema.org JSON-LD embedded in product pages, followed by inferred attributes from unstructured HTML (lowest priority, lowest accuracy). Products with complete structured data appear in AI Overviews, Shopping tab results, and Gemini product recommendations. Products without structured data are deprioritized or excluded entirely.\n\n**ChatGPT Product Search** (launched with GPT-4o shopping in April 2025) uses a combination of web crawling and direct merchant integrations. It surfaces product cards with structured attributes -- price, ratings, availability, specifications -- pulled from merchant APIs, affiliate feeds, and Schema.org markup. Merchants integrated through ACP (Agentic Commerce Protocol) get priority placement because ACP provides real-time inventory and pricing data that ChatGPT can trust to be current.\n\n**A2A Discovery** (Google's Agent-to-Agent protocol) uses Agent Cards published at `\u002F.well-known\u002Fagent.json`. An agent discovers another agent by fetching its Agent Card, which describes capabilities, supported input\u002Foutput formats, authentication requirements, and service endpoints. A2A discovery is agent-to-agent, not agent-to-product -- it is how autonomous agents find other agents to delegate tasks to or purchase services from.\n\n**GreenHelix Marketplace** provides a unified discovery layer across all these patterns. The `search_services` tool queries the marketplace index using structured attributes. The `best_match` tool returns the single best service for a given requirement set. The `register_service` tool publishes your service with structured metadata that agents can query. Your service appears in marketplace search results and can be discovered by any agent with API access.\n\n### The Cost of Being Undiscoverable\n\nThe 805% year-over-year growth in AI-referred traffic is not evenly distributed. It concentrates on services that are machine-readable. A March 2026 analysis of 500 SaaS products found that those with complete structured data (JSON-LD, OpenAPI spec, and at least one discovery protocol endpoint) captured 14x more AI-referred traffic than those without. The relationship was not proportional -- it was binary. Services were either discoverable or they were not. There was no middle ground of \"partially discoverable.\"\n\nThe revenue impact is direct. AI-referred traffic converts at 2.3x the rate of organic search traffic because agents only send users (or other agents) to services that match the query criteria. An agent that finds your service has already verified that your pricing, capabilities, and availability meet the requirements. The \"lead\" is pre-qualified by the agent's scoring algorithm. Losing that channel means losing your highest-converting traffic source.\n\n```python\nimport requests\nfrom typing import Any\n\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\n\nclass DiscoveryClient:\n    \"\"\"Client for GreenHelix A2A Commerce Gateway discovery operations.\"\"\"\n\n    def __init__(self, api_key: str):\n        self.api_key = api_key\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        })\n\n    def execute(self, tool: str, input_data: dict[str, Any]) -> dict:\n        \"\"\"Execute a single tool on the gateway.\"\"\"\n        resp = self.session.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            timeout=30,\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def search_services(self, query: str, filters: dict | None = None) -> dict:\n        \"\"\"Search the GreenHelix marketplace for services.\"\"\"\n        payload = {\"query\": query}\n        if filters:\n            payload[\"filters\"] = filters\n        return self.execute(\"search_services\", payload)\n\n    def best_match(self, requirements: dict) -> dict:\n        \"\"\"Find the single best service match for given requirements.\"\"\"\n        return self.execute(\"best_match\", requirements)\n\n\n# Initialize -- used throughout this guide\nclient = DiscoveryClient(api_key=\"your-api-key-here\")\n\n# Example: search for data enrichment services\nresults = client.search_services(\n    query=\"data enrichment API\",\n    filters={\n        \"max_price_per_call\": 0.01,\n        \"min_uptime_sla\": 99.9,\n        \"protocols\": [\"ucp\", \"a2a\"],\n    },\n)\nprint(f\"Found {len(results.get('services', []))} matching services\")\n```\n\nThis client object is referenced in every subsequent chapter. Store your API key in an environment variable (`GREENHELIX_API_KEY`), never in source code.\n\n> **Key Takeaways**\n>\n> - 40% of digital services have zero machine-readable descriptions. They are invisible to AI agents regardless of quality.\n> - AI-referred commerce traffic grew 805% YoY. Services with complete structured data capture 14x more of this traffic.\n> - Agent discovery is query-and-parse, not browse-and-click. Optimizing for humans does nothing for agents.\n> - Google Shopping Graph, ChatGPT, A2A, and GreenHelix all rely on structured data. No structured data means no discovery.\n> - See P21 (Agent-Ready Commerce) for building the full agent-ready storefront on top of discovery.\n\n---\n\n## Chapter 2: Commerce Knowledge Graphs from Scratch\n\n### What Is a Commerce Knowledge Graph?\n\nA knowledge graph is a structured representation of entities, their properties, and the relationships between them. In commerce, the entities are services, providers, pricing tiers, SLAs, certifications, and transactions. The relationships connect them: a provider *offers* a service, a service *has* a pricing tier, a pricing tier *includes* an SLA, an SLA *guarantees* an uptime level. The properties are the machine-readable attributes: price per call, latency percentile, geographic availability, supported authentication methods.\n\nTraditional databases store this data in tables. Knowledge graphs store it as triples: subject-predicate-object. \"DataEnrichmentAPI\" -- \"hasPricing\" -- \"PayPerCallTier\". \"PayPerCallTier\" -- \"costPerCall\" -- \"0.005 USD\". \"DataEnrichmentAPI\" -- \"guarantees\" -- \"99.95% Uptime SLA\". The advantage of the graph structure is that agents can traverse relationships without knowing the schema in advance. An agent can start from a service node, follow edges to discover pricing, SLA terms, trust scores, and provider identity -- all without a predefined query template.\n\n### Entities, Relationships, and Properties\n\nA commerce knowledge graph for agent-discoverable services contains five core entity types:\n\n| Entity Type | Description | Key Properties |\n|---|---|---|\n| **Service** | The product or capability being offered | name, description, category, version, status |\n| **Provider** | The entity (agent or organization) offering the service | agent_id, public_key, registration_date, trust_score |\n| **PricingTier** | A specific pricing configuration | tier_name, cost_per_call, monthly_cap, currency, billing_model |\n| **SLA** | Service level agreement terms | uptime_guarantee, latency_p99, support_response_time |\n| **Certification** | Verified claims about the service or provider | cert_type, issuer, valid_from, valid_until, verification_hash |\n\nThe relationships between these entities form the graph:\n\n```\nProvider --[offers]--> Service\nService --[hasPricing]--> PricingTier\nService --[guarantees]--> SLA\nProvider --[holds]--> Certification\nService --[requires]--> Certification (for consumers)\nService --[dependsOn]--> Service (for composed services)\n```\n\n### Modeling Your Service Catalog as a Graph\n\nThe first step is translating your existing service catalog into graph form. Most teams start with a flat list of services in a database table or a YAML config file. The graph transformation adds structure that agents can navigate.\n\n```python\nimport json\nfrom dataclasses import dataclass, field, asdict\nfrom typing import Optional\n\n\n@dataclass\nclass SLA:\n    uptime_guarantee: float\n    latency_p99_ms: int\n    support_response_hours: int\n    penalty_per_violation_pct: float = 5.0\n\n\n@dataclass\nclass PricingTier:\n    tier_name: str\n    cost_per_call: float\n    currency: str = \"USD\"\n    monthly_cap: Optional[float] = None\n    billing_model: str = \"pay_per_call\"\n    volume_discounts: dict = field(default_factory=dict)\n\n\n@dataclass\nclass ServiceNode:\n    service_id: str\n    name: str\n    description: str\n    category: str\n    version: str\n    provider_agent_id: str\n    pricing_tiers: list[PricingTier] = field(default_factory=list)\n    sla: Optional[SLA] = None\n    tags: list[str] = field(default_factory=list)\n    dependencies: list[str] = field(default_factory=list)\n    supported_protocols: list[str] = field(default_factory=list)\n    status: str = \"active\"\n\n\nclass CommerceKnowledgeGraph:\n    \"\"\"In-memory knowledge graph for agent-discoverable services.\"\"\"\n\n    def __init__(self):\n        self.services: dict[str, ServiceNode] = {}\n        self.edges: list[dict] = []\n\n    def add_service(self, service: ServiceNode) -> None:\n        \"\"\"Add a service node to the graph.\"\"\"\n        self.services[service.service_id] = service\n\n        # Auto-generate relationship edges\n        for tier in service.pricing_tiers:\n            self.edges.append({\n                \"subject\": service.service_id,\n                \"predicate\": \"hasPricing\",\n                \"object\": tier.tier_name,\n                \"properties\": asdict(tier),\n            })\n\n        if service.sla:\n            self.edges.append({\n                \"subject\": service.service_id,\n                \"predicate\": \"guarantees\",\n                \"object\": f\"{service.service_id}_sla\",\n                \"properties\": asdict(service.sla),\n            })\n\n        for dep in service.dependencies:\n            self.edges.append({\n                \"subject\": service.service_id,\n                \"predicate\": \"dependsOn\",\n                \"object\": dep,\n            })\n\n    def query_by_attribute(self, **kwargs) -> list[ServiceNode]:\n        \"\"\"Query services by attribute filters.\"\"\"\n        results = []\n        for service in self.services.values():\n            match = True\n            for key, value in kwargs.items():\n                if key == \"max_cost_per_call\":\n                    if not any(\n                        t.cost_per_call \u003C= value\n                        for t in service.pricing_tiers\n                    ):\n                        match = False\n                elif key == \"min_uptime\":\n                    if not service.sla or service.sla.uptime_guarantee \u003C value:\n                        match = False\n                elif key == \"category\":\n                    if service.category != value:\n                        match = False\n                elif key == \"protocol\":\n                    if value not in service.supported_protocols:\n                        match = False\n            if match:\n                results.append(service)\n        return results\n\n    def to_jsonld(self) -> list[dict]:\n        \"\"\"Export the graph as JSON-LD for agent consumption.\"\"\"\n        output = []\n        for service in self.services.values():\n            node = {\n                \"@context\": \"https:\u002F\u002Fschema.org\",\n                \"@type\": \"Service\",\n                \"@id\": f\"urn:greenhelix:service:{service.service_id}\",\n                \"name\": service.name,\n                \"description\": service.description,\n                \"category\": service.category,\n                \"version\": service.version,\n                \"provider\": {\n                    \"@type\": \"Organization\",\n                    \"identifier\": service.provider_agent_id,\n                },\n                \"offers\": [\n                    {\n                        \"@type\": \"Offer\",\n                        \"name\": tier.tier_name,\n                        \"price\": str(tier.cost_per_call),\n                        \"priceCurrency\": tier.currency,\n                        \"priceSpecification\": {\n                            \"@type\": \"UnitPriceSpecification\",\n                            \"price\": str(tier.cost_per_call),\n                            \"priceCurrency\": tier.currency,\n                            \"unitText\": \"per API call\",\n                            \"billingModel\": tier.billing_model,\n                        },\n                    }\n                    for tier in service.pricing_tiers\n                ],\n            }\n            if service.sla:\n                node[\"termsOfService\"] = {\n                    \"uptimeGuarantee\": service.sla.uptime_guarantee,\n                    \"latencyP99Ms\": service.sla.latency_p99_ms,\n                    \"supportResponseHours\": service.sla.support_response_hours,\n                }\n            output.append(node)\n        return output\n\n    def sync_to_marketplace(self, discovery_client) -> list[dict]:\n        \"\"\"Register all services on GreenHelix marketplace.\"\"\"\n        results = []\n        for service in self.services.values():\n            cheapest_tier = min(\n                service.pricing_tiers,\n                key=lambda t: t.cost_per_call,\n            ) if service.pricing_tiers else None\n\n            result = discovery_client.execute(\"register_service\", {\n                \"agent_id\": service.provider_agent_id,\n                \"service_name\": service.name,\n                \"description\": service.description,\n                \"category\": service.category,\n                \"tags\": service.tags,\n                \"pricing\": {\n                    \"model\": cheapest_tier.billing_model if cheapest_tier else \"contact\",\n                    \"base_price\": str(cheapest_tier.cost_per_call) if cheapest_tier else \"0\",\n                    \"currency\": cheapest_tier.currency if cheapest_tier else \"USD\",\n                },\n                \"sla\": asdict(service.sla) if service.sla else None,\n                \"protocols\": service.supported_protocols,\n            })\n            results.append(result)\n        return results\n\n\n# Build a sample graph\ngraph = CommerceKnowledgeGraph()\n\ngraph.add_service(ServiceNode(\n    service_id=\"data-enrichment-v2\",\n    name=\"DataEnrich Pro\",\n    description=\"Real-time company data enrichment with 95% match rate\",\n    category=\"data-enrichment\",\n    version=\"2.1.0\",\n    provider_agent_id=\"agent-dataenrich-prod\",\n    pricing_tiers=[\n        PricingTier(\"starter\", cost_per_call=0.005, monthly_cap=100.0),\n        PricingTier(\"growth\", cost_per_call=0.003, monthly_cap=500.0,\n                    volume_discounts={\"10000\": 0.002, \"100000\": 0.001}),\n    ],\n    sla=SLA(uptime_guarantee=99.95, latency_p99_ms=200,\n            support_response_hours=4),\n    tags=[\"enrichment\", \"company-data\", \"real-time\", \"api\"],\n    supported_protocols=[\"ucp\", \"a2a\", \"mcp\"],\n))\n\ngraph.add_service(ServiceNode(\n    service_id=\"sentiment-analysis-v3\",\n    name=\"SentimentLens\",\n    description=\"Multi-language sentiment analysis with aspect extraction\",\n    category=\"nlp\",\n    version=\"3.0.1\",\n    provider_agent_id=\"agent-sentimentlens-prod\",\n    pricing_tiers=[\n        PricingTier(\"basic\", cost_per_call=0.001),\n        PricingTier(\"premium\", cost_per_call=0.008,\n                    volume_discounts={\"50000\": 0.005}),\n    ],\n    sla=SLA(uptime_guarantee=99.9, latency_p99_ms=150,\n            support_response_hours=8),\n    tags=[\"nlp\", \"sentiment\", \"multilingual\", \"aspect-extraction\"],\n    supported_protocols=[\"ucp\", \"mcp\"],\n))\n\n# Query the graph\ncheap_services = graph.query_by_attribute(\n    max_cost_per_call=0.005,\n    min_uptime=99.9,\n)\nprint(f\"Services matching criteria: {[s.name for s in cheap_services]}\")\n\n# Export as JSON-LD\njsonld = graph.to_jsonld()\nprint(json.dumps(jsonld[0], indent=2))\n```\n\n### JSON-LD and Schema.org Vocabulary\n\nJSON-LD (JavaScript Object Notation for Linked Data) is the standard format for embedding structured data in web pages and API responses. It uses `@context` to map property names to Schema.org URIs, `@type` to declare the entity type, and `@id` to provide a globally unique identifier. AI agents -- whether they are Google's crawlers, ChatGPT's shopping engine, or a GreenHelix marketplace indexer -- parse JSON-LD to extract structured attributes.\n\nThe Schema.org vocabulary provides standardized types for commerce: `Service`, `Offer`, `Organization`, `PriceSpecification`, `AggregateRating`, `Review`. Using these types ensures your data is interoperable across all agent ecosystems. A service described as `@type: Service` with `offers` containing `@type: Offer` and `priceSpecification` will be parsed identically by Google Shopping Graph, Perplexity Shopping, and GreenHelix `search_services`.\n\nThe `to_jsonld()` method in the `CommerceKnowledgeGraph` class above handles the conversion. The critical detail is using string representations for prices (`str(tier.cost_per_call)`) rather than floats, avoiding floating-point precision issues that cause agents to reject or miscompare pricing data. See P18 (Pricing & Monetization) for the full treatment of decimal-safe pricing.\n\n> **Key Takeaways**\n>\n> - A commerce knowledge graph models services as entities with typed relationships: provider offers service, service has pricing, pricing includes SLA.\n> - Five core entity types: Service, Provider, PricingTier, SLA, Certification. Each has machine-readable properties.\n> - JSON-LD with Schema.org vocabulary is the interoperability standard. All major agent platforms parse it.\n> - Build the graph in code, export as JSON-LD for web crawlers, and sync to GreenHelix marketplace via `register_service` for agent-native discovery.\n> - Always use string-typed prices to avoid floating-point comparison failures.\n\n---\n\n## Chapter 3: The Protocol Stack: UCP, MCP, A2A, ACP\n\n### Four Protocols, Four Jobs\n\nThe agentic commerce stack has consolidated around four protocols, each solving a distinct problem in the discovery-to-transaction lifecycle. Implementing the wrong one first wastes months. Implementing all four without understanding the dependencies creates a maintenance burden that outweighs the benefit. This chapter provides the decision framework.\n\n**UCP (Unified Commerce Protocol)** is the discovery and capability advertisement layer. A UCP profile published at `\u002F.well-known\u002Fucp` tells agents what your service does, how it is priced, what payment methods it accepts, and where to find its API. UCP is the front door. Without it, agents that crawl for services have no standard entry point. UCP profiles are JSON documents with a defined schema: capabilities, pricing, authentication requirements, SLA terms, and payment methods. Think of it as a machine-readable business card that also includes the full menu and the credit card terminal specs.\n\n**MCP (Model Context Protocol)** is the tool execution layer. An MCP server exposes tools -- functions with JSON Schema-defined inputs and outputs -- that LLMs and agents can call. MCP handles tool discovery (listing available tools and their schemas), tool invocation (sending structured inputs and receiving structured outputs), and context management (maintaining state across multi-turn tool interactions). If UCP tells an agent your service exists, MCP tells it how to call your service.\n\n**A2A (Agent-to-Agent Protocol)** is the task delegation layer. A2A defines how agents discover each other (Agent Cards at `\u002F.well-known\u002Fagent.json`), exchange task requests (JSON-based task messages with structured parts), and stream progress updates (Server-Sent Events). A2A is designed for agent-to-agent workflows where one agent delegates a task to another, monitors progress, and receives results. It overlaps with MCP in discovery but diverges in execution: MCP is function-call oriented, A2A is task-oriented.\n\n**ACP (Agentic Commerce Protocol)** is the payment and checkout layer. ACP extends Stripe Checkout for AI agents, providing structured product catalogs, cart management, and payment flow orchestration. ACP is the narrowest of the four protocols -- it specifically handles the commercial transaction, not discovery, not tool execution, not task delegation.\n\n### The Dependency Chain\n\nThe protocols are not independent. They form a dependency chain:\n\n```\nDiscovery        Execution         Transaction\n┌──────┐        ┌──────┐          ┌──────┐\n│ UCP  │───────▶│ MCP  │─────────▶│ ACP  │\n│      │───────▶│ A2A  │─────────▶│      │\n└──────┘        └──────┘          └──────┘\n```\n\nUCP must come first. An agent cannot call your MCP tools or send you A2A tasks if it cannot discover you. MCP and A2A operate in parallel -- some agents prefer function calls (MCP), others prefer task delegation (A2A), many support both. ACP comes last because payment only matters after an agent has discovered your service and decided to use it.\n\n### Decision Matrix: Which Protocol to Implement First\n\n| Factor | UCP First | MCP First | A2A First | ACP First |\n|---|---|---|---|---|\n| **You sell API services** | Yes -- agents need to discover your capabilities | Second -- expose tools after discovery | Optional -- most API consumers prefer MCP | Third -- add payment after execution works |\n| **You sell to LLM-powered agents** | Yes | Yes -- LLMs call MCP tools natively | Lower priority | After MCP |\n| **You sell to autonomous agent fleets** | Yes | Optional | Yes -- fleets use A2A for task delegation | After A2A |\n| **You are a marketplace** | Yes | Yes -- expose search\u002Fpurchase as tools | Yes -- agents discover marketplace via A2A | Yes -- checkout via ACP |\n| **You need payment immediately** | Still first -- discovery before payment | No | No | No -- useless without discovery |\n\nThe universal answer: **implement UCP first, then MCP or A2A depending on your buyer profile, then ACP**.\n\n### Protocol Selection Logic\n\n```python\ndef select_protocols(\n    service_type: str,\n    buyer_profile: str,\n    needs_payment: bool,\n    existing_protocols: list[str],\n) -> list[dict]:\n    \"\"\"Determine which discovery protocols to implement and in what order.\n\n    Returns prioritized list of protocols with implementation guidance.\n    \"\"\"\n    recommendations = []\n\n    # UCP is always first -- it is the discovery foundation\n    if \"ucp\" not in existing_protocols:\n        recommendations.append({\n            \"protocol\": \"ucp\",\n            \"priority\": 1,\n            \"reason\": \"Discovery foundation -- agents cannot find you without it\",\n            \"effort_days\": 2,\n            \"endpoint\": \"\u002F.well-known\u002Fucp\",\n        })\n\n    # MCP vs A2A depends on buyer profile\n    if buyer_profile in (\"llm_agents\", \"api_consumers\", \"developers\"):\n        if \"mcp\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"mcp\",\n                \"priority\": 2,\n                \"reason\": \"LLM agents and API consumers prefer function-call semantics\",\n                \"effort_days\": 3,\n                \"endpoint\": \"\u002Fmcp\u002Ftools\",\n            })\n        if \"a2a\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"a2a\",\n                \"priority\": 3,\n                \"reason\": \"Secondary -- covers autonomous agent fleets\",\n                \"effort_days\": 4,\n                \"endpoint\": \"\u002F.well-known\u002Fagent.json\",\n            })\n    elif buyer_profile in (\"autonomous_fleets\", \"enterprise_agents\"):\n        if \"a2a\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"a2a\",\n                \"priority\": 2,\n                \"reason\": \"Autonomous fleets use A2A for task delegation\",\n                \"effort_days\": 4,\n                \"endpoint\": \"\u002F.well-known\u002Fagent.json\",\n            })\n        if \"mcp\" not in existing_protocols:\n            recommendations.append({\n                \"protocol\": \"mcp\",\n                \"priority\": 3,\n                \"reason\": \"Secondary -- covers LLM-based tool calling\",\n                \"effort_days\": 3,\n                \"endpoint\": \"\u002Fmcp\u002Ftools\",\n            })\n\n    # ACP always comes after execution layer\n    if needs_payment and \"acp\" not in existing_protocols:\n        recommendations.append({\n            \"protocol\": \"acp\",\n            \"priority\": 4,\n            \"reason\": \"Payment layer -- implement after discovery and execution\",\n            \"effort_days\": 5,\n            \"endpoint\": \"\u002Facp\u002Fcheckout\",\n        })\n\n    return sorted(recommendations, key=lambda r: r[\"priority\"])\n\n\n# Example: SaaS API selling to LLM-powered agents\nplan = select_protocols(\n    service_type=\"api_service\",\n    buyer_profile=\"llm_agents\",\n    needs_payment=True,\n    existing_protocols=[],\n)\nfor step in plan:\n    print(f\"Priority {step['priority']}: {step['protocol'].upper()} \"\n          f\"({step['effort_days']} days) -- {step['reason']}\")\n```\n\n### Registering Protocol Support on GreenHelix\n\nOnce you have implemented protocol endpoints, register them on the marketplace so agents know which protocols you support:\n\n```python\n# Register your service with protocol metadata\nresult = client.execute(\"register_service\", {\n    \"agent_id\": \"agent-dataenrich-prod\",\n    \"service_name\": \"DataEnrich Pro\",\n    \"description\": \"Real-time company data enrichment API\",\n    \"category\": \"data-enrichment\",\n    \"tags\": [\"enrichment\", \"company-data\", \"api\"],\n    \"pricing\": {\n        \"model\": \"pay_per_call\",\n        \"base_price\": \"0.005\",\n        \"currency\": \"USD\",\n    },\n    \"protocols\": [\"ucp\", \"mcp\", \"a2a\"],\n    \"endpoints\": {\n        \"ucp\": \"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fucp\",\n        \"mcp\": \"https:\u002F\u002Fdataenrich.example.com\u002Fmcp\u002Ftools\",\n        \"a2a\": \"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fagent.json\",\n    },\n})\nprint(f\"Service registered: {result}\")\n```\n\nAgents searching the marketplace can then filter by protocol:\n\n```python\n# Find services that support A2A\na2a_services = client.search_services(\n    query=\"data enrichment\",\n    filters={\"protocols\": [\"a2a\"]},\n)\n```\n\n> **Key Takeaways**\n>\n> - Four protocols form a stack: UCP (discovery), MCP (tool execution), A2A (task delegation), ACP (payment).\n> - UCP is always implemented first. Without discovery, no other protocol matters.\n> - MCP for LLM-powered agents, A2A for autonomous agent fleets. Most services should implement both.\n> - ACP handles payment and is always implemented last in the chain.\n> - Register protocol endpoints on GreenHelix via `register_service` so agents can filter by supported protocol.\n> - See P21 (Agent-Ready Commerce) Chapter 3 for detailed UCP\u002FACP\u002Fx402 payment rail comparison.\n\n---\n\n## Chapter 4: Building .well-known Discovery Endpoints\n\n### The Discovery Endpoint Pattern\n\nThe `.well-known` URI pattern (RFC 8615) provides a standardized location for machine-readable metadata. Agents crawling for services check these paths before attempting any other discovery method. If your service is at `https:\u002F\u002Fapi.example.com`, agents will look for:\n\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fucp` -- UCP service profile\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fagent.json` -- A2A agent card\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fai-plugin.json` -- OpenAI\u002FChatGPT plugin manifest\n- `https:\u002F\u002Fapi.example.com\u002F.well-known\u002Fopenapi.yaml` -- OpenAPI specification\n\nMissing any of these endpoints means missing agents that use that specific discovery method. The cost of serving static JSON at four paths is trivial. The cost of not serving it is invisibility to entire agent ecosystems.\n\n### UCP Profile: The Complete Service Advertisement\n\nThe UCP profile is the most comprehensive discovery document. It combines capability advertisement, pricing, payment methods, SLA terms, and API documentation references into a single JSON document.\n\n```python\nimport json\nfrom datetime import datetime, timezone\n\n\ndef build_ucp_profile(\n    service_name: str,\n    service_description: str,\n    provider_agent_id: str,\n    capabilities: list[dict],\n    pricing_tiers: list[dict],\n    payment_methods: list[str],\n    sla: dict,\n    api_spec_url: str,\n    trust_score: float | None = None,\n) -> dict:\n    \"\"\"Build a UCP profile document for \u002F.well-known\u002Fucp.\"\"\"\n    profile = {\n        \"ucp_version\": \"1.0\",\n        \"service\": {\n            \"name\": service_name,\n            \"description\": service_description,\n            \"provider\": {\n                \"agent_id\": provider_agent_id,\n                \"trust_score\": trust_score,\n                \"verification_status\": \"verified\" if trust_score and trust_score > 0.7 else \"unverified\",\n            },\n            \"status\": \"active\",\n            \"last_updated\": datetime.now(timezone.utc).isoformat(),\n        },\n        \"capabilities\": capabilities,\n        \"pricing\": {\n            \"tiers\": pricing_tiers,\n            \"currency\": \"USD\",\n            \"billing_models\": list({t.get(\"billing_model\", \"pay_per_call\") for t in pricing_tiers}),\n        },\n        \"payment_methods\": payment_methods,\n        \"sla\": sla,\n        \"api\": {\n            \"specification\": api_spec_url,\n            \"format\": \"openapi-3.1\",\n            \"authentication\": {\n                \"type\": \"bearer\",\n                \"token_endpoint\": None,  # None for API-key auth\n            },\n        },\n        \"discovery\": {\n            \"protocols\": [\"ucp\", \"mcp\", \"a2a\"],\n            \"mcp_endpoint\": \"\u002Fmcp\u002Ftools\",\n            \"a2a_agent_card\": \"\u002F.well-known\u002Fagent.json\",\n        },\n    }\n    return profile\n\n\n# Build profile for our data enrichment service\nucp_profile = build_ucp_profile(\n    service_name=\"DataEnrich Pro\",\n    service_description=\"Real-time company data enrichment with 95% match rate across 200M+ companies\",\n    provider_agent_id=\"agent-dataenrich-prod\",\n    capabilities=[\n        {\n            \"name\": \"company_lookup\",\n            \"description\": \"Enrich company data from domain, name, or LinkedIn URL\",\n            \"input_schema\": {\"domain\": \"string\", \"company_name\": \"string?\"},\n            \"output_schema\": {\"company\": \"CompanyProfile\"},\n            \"latency_p99_ms\": 200,\n        },\n        {\n            \"name\": \"contact_enrichment\",\n            \"description\": \"Enrich contact details from email or name + company\",\n            \"input_schema\": {\"email\": \"string?\", \"name\": \"string?\", \"company\": \"string?\"},\n            \"output_schema\": {\"contact\": \"ContactProfile\"},\n            \"latency_p99_ms\": 350,\n        },\n    ],\n    pricing_tiers=[\n        {\n            \"name\": \"starter\",\n            \"cost_per_call\": \"0.005\",\n            \"monthly_cap\": \"100.00\",\n            \"billing_model\": \"pay_per_call\",\n        },\n        {\n            \"name\": \"growth\",\n            \"cost_per_call\": \"0.003\",\n            \"monthly_cap\": \"500.00\",\n            \"billing_model\": \"pay_per_call\",\n            \"volume_discounts\": {\"10000\": \"0.002\", \"100000\": \"0.001\"},\n        },\n    ],\n    payment_methods=[\"greenhelix_escrow\", \"stripe\", \"x402_usdc\"],\n    sla={\n        \"uptime_guarantee\": 99.95,\n        \"latency_p99_ms\": 200,\n        \"support_response_hours\": 4,\n        \"data_retention_days\": 30,\n    },\n    api_spec_url=\"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fopenapi.yaml\",\n    trust_score=0.92,\n)\n\nprint(json.dumps(ucp_profile, indent=2))\n```\n\n### MCP Tool Manifest\n\nThe MCP tool manifest describes each tool's input and output schemas so LLMs can discover and call them:\n\n```python\ndef build_mcp_manifest(capabilities: list[dict]) -> dict:\n    \"\"\"Build an MCP tool manifest from service capabilities.\"\"\"\n    tools = []\n    for cap in capabilities:\n        tool = {\n            \"name\": cap[\"name\"],\n            \"description\": cap[\"description\"],\n            \"inputSchema\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    k: {\"type\": v.rstrip(\"?\")}\n                    for k, v in cap.get(\"input_schema\", {}).items()\n                },\n                \"required\": [\n                    k for k, v in cap.get(\"input_schema\", {}).items()\n                    if not v.endswith(\"?\")\n                ],\n            },\n        }\n        tools.append(tool)\n\n    return {\n        \"schema_version\": \"2025-03-26\",\n        \"server_info\": {\n            \"name\": \"dataenrich-mcp\",\n            \"version\": \"2.1.0\",\n        },\n        \"tools\": tools,\n    }\n```\n\n### A2A Agent Card\n\nThe A2A agent card is simpler -- it describes the agent's identity, capabilities, and communication preferences:\n\n```python\ndef build_a2a_agent_card(\n    agent_id: str,\n    name: str,\n    description: str,\n    skills: list[dict],\n    endpoint: str,\n) -> dict:\n    \"\"\"Build an A2A Agent Card for \u002F.well-known\u002Fagent.json.\"\"\"\n    return {\n        \"name\": name,\n        \"description\": description,\n        \"url\": endpoint,\n        \"version\": \"1.0.0\",\n        \"capabilities\": {\n            \"streaming\": True,\n            \"pushNotifications\": False,\n            \"stateTransitionHistory\": True,\n        },\n        \"authentication\": {\n            \"schemes\": [\"bearer\"],\n        },\n        \"defaultInputModes\": [\"application\u002Fjson\"],\n        \"defaultOutputModes\": [\"application\u002Fjson\"],\n        \"skills\": skills,\n    }\n\n\nagent_card = build_a2a_agent_card(\n    agent_id=\"agent-dataenrich-prod\",\n    name=\"DataEnrich Pro Agent\",\n    description=\"Autonomous data enrichment agent with 95% match rate\",\n    skills=[\n        {\n            \"id\": \"company_lookup\",\n            \"name\": \"Company Data Lookup\",\n            \"description\": \"Enrich company data from domain or name\",\n            \"tags\": [\"enrichment\", \"company-data\"],\n            \"examples\": [\"Enrich data for openai.com\", \"Look up Stripe company info\"],\n        },\n        {\n            \"id\": \"contact_enrichment\",\n            \"name\": \"Contact Enrichment\",\n            \"description\": \"Enrich contact details from email or name\",\n            \"tags\": [\"enrichment\", \"contacts\"],\n            \"examples\": [\"Find details for jane@example.com\"],\n        },\n    ],\n    endpoint=\"https:\u002F\u002Fdataenrich.example.com\u002Fa2a\",\n)\n```\n\n### The FastAPI Service: All Endpoints Together\n\nHere is a complete FastAPI service that serves all discovery endpoints and validates them against GreenHelix `search_services` and `best_match`:\n\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\nimport uvicorn\n\napp = FastAPI(title=\"DataEnrich Pro -- Agent-Discoverable Service\")\n\n\n@app.get(\"\u002F.well-known\u002Fucp\")\nasync def ucp_endpoint():\n    \"\"\"UCP service profile for agent discovery.\"\"\"\n    return JSONResponse(content=ucp_profile)\n\n\n@app.get(\"\u002F.well-known\u002Fagent.json\")\nasync def a2a_agent_card_endpoint():\n    \"\"\"A2A Agent Card for agent-to-agent discovery.\"\"\"\n    return JSONResponse(content=agent_card)\n\n\n@app.get(\"\u002Fmcp\u002Ftools\")\nasync def mcp_tools_endpoint():\n    \"\"\"MCP tool manifest for LLM tool discovery.\"\"\"\n    manifest = build_mcp_manifest(ucp_profile[\"capabilities\"])\n    return JSONResponse(content=manifest)\n\n\n@app.get(\"\u002F.well-known\u002Fai-plugin.json\")\nasync def ai_plugin_endpoint():\n    \"\"\"OpenAI-compatible plugin manifest.\"\"\"\n    return JSONResponse(content={\n        \"schema_version\": \"v1\",\n        \"name_for_human\": \"DataEnrich Pro\",\n        \"name_for_model\": \"dataenrich_pro\",\n        \"description_for_human\": \"Real-time company and contact data enrichment.\",\n        \"description_for_model\": (\n            \"Real-time data enrichment API. Supports company lookup by domain \"\n            \"or name (200M+ companies, 95% match rate) and contact enrichment \"\n            \"by email. Returns structured JSON with 50+ fields. Pricing: \"\n            \"$0.003-$0.005 per call. Uptime SLA: 99.95%. Supports UCP, MCP, A2A.\"\n        ),\n        \"auth\": {\"type\": \"service_http\", \"authorization_type\": \"bearer\"},\n        \"api\": {\n            \"type\": \"openapi\",\n            \"url\": \"https:\u002F\u002Fdataenrich.example.com\u002F.well-known\u002Fopenapi.yaml\",\n        },\n    })\n\n\n@app.get(\"\u002Fhealth\")\nasync def health():\n    return {\"status\": \"ok\"}\n\n\n# Validation: test that your service is discoverable via GreenHelix\ndef validate_discovery():\n    \"\"\"Verify the service appears in GreenHelix search results.\"\"\"\n    # Search for our service by capability\n    results = client.search_services(\n        query=\"company data enrichment real-time\",\n        filters={\"protocols\": [\"ucp\", \"mcp\"]},\n    )\n    services = results.get(\"services\", [])\n    our_service = next(\n        (s for s in services if s.get(\"agent_id\") == \"agent-dataenrich-prod\"),\n        None,\n    )\n\n    if not our_service:\n        print(\"WARNING: Service not found in marketplace search results\")\n        print(\"Run register_service first (see Chapter 2)\")\n        return False\n\n    # Verify best_match picks us for a targeted query\n    match = client.best_match({\n        \"query\": \"data enrichment with 99%+ uptime and under $0.01 per call\",\n        \"required_protocols\": [\"ucp\"],\n    })\n    if match.get(\"agent_id\") == \"agent-dataenrich-prod\":\n        print(\"PASS: best_match returns our service for targeted query\")\n    else:\n        print(f\"INFO: best_match returned {match.get('agent_id')} -- \"\n              f\"consider improving your listing attributes\")\n\n    return True\n\n\nif __name__ == \"__main__\":\n    validate_discovery()\n    uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n```\n\n### Discovery Endpoint Checklist\n\n| Endpoint | Path | Format | Who Reads It |\n|---|---|---|---|\n| UCP Profile | `\u002F.well-known\u002Fucp` | JSON | UCP-compatible agents, GreenHelix marketplace indexer |\n| A2A Agent Card | `\u002F.well-known\u002Fagent.json` | JSON | Google A2A agents, autonomous fleets |\n| MCP Tools | `\u002Fmcp\u002Ftools` | JSON | Claude, Cursor, Windsurf, LLM-based agents |\n| AI Plugin | `\u002F.well-known\u002Fai-plugin.json` | JSON | ChatGPT, OpenAI-ecosystem agents |\n| OpenAPI Spec | `\u002F.well-known\u002Fopenapi.yaml` | YAML | All programmatic consumers |\n\n> **Key Takeaways**\n>\n> - Four `.well-known` endpoints cover the major agent discovery methods. Each takes minutes to implement and costs nothing to serve.\n> - UCP profile is the most comprehensive: capabilities, pricing, SLA, payment methods, and cross-references to other endpoints.\n> - MCP manifests let LLMs discover your tools. A2A agent cards let autonomous agents discover your capabilities.\n> - Validate discovery by searching for your own service via GreenHelix `search_services` and `best_match`.\n> - See P20 (Production Hardening) for rate-limiting and caching these endpoints at scale.\n\n---\n\n## Chapter 5: Structured Data & Schema.org for Agent Readability\n\n### Why Schema.org Wins for Agent Discovery\n\nSchema.org is the lingua franca of structured data on the web. Google, Bing, Yahoo, and Yandex jointly maintain it. Over 40 million websites use Schema.org markup. More importantly for agent commerce: every major AI shopping agent -- Google Gemini, ChatGPT, Perplexity, Claude -- parses Schema.org JSON-LD. When an agent encounters a `@type: Service` node with `offers`, `priceSpecification`, and `aggregateRating`, it extracts those fields into a comparable data structure regardless of which agent platform is doing the reading.\n\nThe alternative -- custom JSON schemas -- works for a single agent ecosystem but fails for cross-ecosystem discovery. An agent built for Google A2A might not understand your custom schema. An agent using ChatGPT's product search definitely will not. Schema.org is the only vocabulary that works everywhere.\n\n### JSON-LD for Digital Services\n\nPhysical products have standardized Schema.org types: `Product`, `Offer`, `AggregateOffer`. Digital services require a slightly different approach because they have properties that physical products do not: SLA terms, API latency, uptime guarantees, supported protocols, rate limits. The correct mapping uses `Service` as the primary type, with `Offer` for pricing and custom properties for service-specific attributes.\n\n```python\nimport json\nfrom datetime import datetime, timezone\n\n\ndef build_service_jsonld(\n    service_id: str,\n    name: str,\n    description: str,\n    provider_name: str,\n    provider_agent_id: str,\n    category: str,\n    pricing_tiers: list[dict],\n    sla: dict,\n    rating: dict | None = None,\n    supported_protocols: list[str] | None = None,\n    availability: str = \"InStock\",\n) -> dict:\n    \"\"\"Build Schema.org JSON-LD for a digital service.\n\n    Produces a document parseable by Google Shopping Graph, ChatGPT,\n    Perplexity Shopping, and GreenHelix marketplace indexer.\n    \"\"\"\n    jsonld = {\n        \"@context\": \"https:\u002F\u002Fschema.org\",\n        \"@type\": \"Service\",\n        \"@id\": f\"urn:greenhelix:service:{service_id}\",\n        \"name\": name,\n        \"description\": description,\n        \"serviceType\": category,\n        \"provider\": {\n            \"@type\": \"Organization\",\n            \"name\": provider_name,\n            \"identifier\": provider_agent_id,\n        },\n        \"offers\": [],\n        \"termsOfService\": f\"https:\u002F\u002Fapi.example.com\u002Ftos\u002F{service_id}\",\n        \"availableChannel\": {\n            \"@type\": \"ServiceChannel\",\n            \"serviceType\": \"API\",\n            \"availableLanguage\": [\"en\"],\n        },\n    }\n\n    # Add pricing tiers as offers\n    for tier in pricing_tiers:\n        offer = {\n            \"@type\": \"Offer\",\n            \"name\": tier[\"name\"],\n            \"price\": str(tier[\"cost_per_call\"]),\n            \"priceCurrency\": tier.get(\"currency\", \"USD\"),\n            \"availability\": f\"https:\u002F\u002Fschema.org\u002F{availability}\",\n            \"priceValidUntil\": tier.get(\n                \"valid_until\",\n                datetime(2026, 12, 31, tzinfo=timezone.utc).isoformat(),\n            ),\n            \"priceSpecification\": {\n                \"@type\": \"UnitPriceSpecification\",\n                \"price\": str(tier[\"cost_per_call\"]),\n                \"priceCurrency\": tier.get(\"currency\", \"USD\"),\n                \"unitText\": \"per API call\",\n                \"referenceQuantity\": {\n                    \"@type\": \"QuantitativeValue\",\n                    \"value\": 1,\n                    \"unitCode\": \"C62\",  # ISO unit for \"one\"\n                },\n            },\n        }\n        if \"monthly_cap\" in tier:\n            offer[\"priceSpecification\"][\"maxPrice\"] = str(tier[\"monthly_cap\"])\n        jsonld[\"offers\"].append(offer)\n\n    # Add SLA as custom properties (agents parse these for comparison)\n    if sla:\n        jsonld[\"additionalProperty\"] = [\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": \"uptimeGuarantee\",\n                \"value\": sla.get(\"uptime_guarantee\", 99.9),\n                \"unitText\": \"percent\",\n            },\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": \"latencyP99\",\n                \"value\": sla.get(\"latency_p99_ms\", 500),\n                \"unitText\": \"milliseconds\",\n            },\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": \"supportResponseTime\",\n                \"value\": sla.get(\"support_response_hours\", 24),\n                \"unitText\": \"hours\",\n            },\n        ]\n\n    # Add aggregate rating if available\n    if rating:\n        jsonld[\"aggregateRating\"] = {\n            \"@type\": \"AggregateRating\",\n            \"ratingValue\": rating[\"value\"],\n            \"bestRating\": 5,\n            \"ratingCount\": rating[\"count\"],\n        }\n\n    # Add protocol support as additional properties\n    if supported_protocols:\n        jsonld[\"additionalProperty\"].append({\n            \"@type\": \"PropertyValue\",\n            \"name\": \"supportedProtocols\",\n            \"value\": \", \".join(supported_protocols),\n        })\n\n    return jsonld\n\n\n# Generate JSON-LD for our service\nservice_schema = build_service_jsonld(\n    service_id=\"data-enrichment-v2\",\n    name=\"DataEnrich Pro\",\n    description=\"Real-time company data enrichment with 95% match rate across 200M+ companies. \"\n                \"Returns 50+ structured fields per company including firmographics, technographics, \"\n                \"and funding data.\",\n    provider_name=\"DataEnrich Inc.\",\n    provider_agent_id=\"agent-dataenrich-prod\",\n    category=\"data-enrichment\",\n    pricing_tiers=[\n        {\"name\": \"Starter\", \"cost_per_call\": \"0.005\", \"monthly_cap\": \"100.00\"},\n        {\"name\": \"Growth\", \"cost_per_call\": \"0.003\", \"monthly_cap\": \"500.00\"},\n    ],\n    sla={\n        \"uptime_guarantee\": 99.95,\n        \"latency_p99_ms\": 200,\n        \"support_response_hours\": 4,\n    },\n    rating={\"value\": 4.8, \"count\": 342},\n    supported_protocols=[\"ucp\", \"mcp\", \"a2a\"],\n)\n\nprint(json.dumps(service_schema, indent=2))\n```\n\n### Auto-Generating Structured Data via GreenHelix\n\nWhen you register a service on the GreenHelix marketplace, the gateway can auto-generate Schema.org JSON-LD from your registration data. This ensures consistency between your marketplace listing and your web-embedded structured data.\n\n```python\ndef register_and_generate_schema(\n    discovery_client,\n    service_data: dict,\n) -> tuple[dict, dict]:\n    \"\"\"Register a service on GreenHelix and generate matching Schema.org JSON-LD.\n\n    Returns (registration_result, jsonld_schema).\n    \"\"\"\n    # Register on marketplace\n    registration = discovery_client.execute(\"register_service\", {\n        \"agent_id\": service_data[\"provider_agent_id\"],\n        \"service_name\": service_data[\"name\"],\n        \"description\": service_data[\"description\"],\n        \"category\": service_data[\"category\"],\n        \"tags\": service_data.get(\"tags\", []),\n        \"pricing\": service_data[\"pricing\"],\n        \"sla\": service_data.get(\"sla\"),\n        \"protocols\": service_data.get(\"protocols\", []),\n    })\n\n    # Fetch the listing back to get canonical data\n    listing = discovery_client.execute(\"get_service\", {\n        \"service_id\": registration.get(\"service_id\", service_data[\"name\"]),\n    })\n\n    # Generate JSON-LD from canonical listing\n    schema = build_service_jsonld(\n        service_id=listing.get(\"service_id\", \"\"),\n        name=listing.get(\"service_name\", service_data[\"name\"]),\n        description=listing.get(\"description\", service_data[\"description\"]),\n        provider_name=service_data.get(\"provider_name\", \"\"),\n        provider_agent_id=listing.get(\"agent_id\", \"\"),\n        category=listing.get(\"category\", \"\"),\n        pricing_tiers=service_data.get(\"pricing_tiers\", []),\n        sla=listing.get(\"sla\", {}),\n        rating=listing.get(\"rating\"),\n        supported_protocols=listing.get(\"protocols\", []),\n    )\n\n    return registration, schema\n\n\n# Usage\nreg_result, jsonld = register_and_generate_schema(client, {\n    \"provider_agent_id\": \"agent-dataenrich-prod\",\n    \"provider_name\": \"DataEnrich Inc.\",\n    \"name\": \"DataEnrich Pro\",\n    \"description\": \"Real-time company data enrichment API\",\n    \"category\": \"data-enrichment\",\n    \"tags\": [\"enrichment\", \"company-data\", \"real-time\"],\n    \"pricing\": {\"model\": \"pay_per_call\", \"base_price\": \"0.005\", \"currency\": \"USD\"},\n    \"pricing_tiers\": [\n        {\"name\": \"Starter\", \"cost_per_call\": \"0.005\", \"monthly_cap\": \"100.00\"},\n    ],\n    \"sla\": {\"uptime_guarantee\": 99.95, \"latency_p99_ms\": 200, \"support_response_hours\": 4},\n    \"protocols\": [\"ucp\", \"mcp\", \"a2a\"],\n})\n```\n\n### Validation Script\n\nStructured data is only useful if it is valid. Agents that encounter malformed JSON-LD will skip your listing. This validation script catches the most common errors before they reach production:\n\n```python\ndef validate_service_jsonld(schema: dict) -> list[str]:\n    \"\"\"Validate a service JSON-LD document against common agent requirements.\n\n    Returns a list of validation errors (empty = valid).\n    \"\"\"\n    errors = []\n\n    # Required fields\n    if schema.get(\"@context\") != \"https:\u002F\u002Fschema.org\":\n        errors.append(\"Missing or incorrect @context (must be https:\u002F\u002Fschema.org)\")\n\n    if schema.get(\"@type\") != \"Service\":\n        errors.append(f\"@type must be 'Service', got '{schema.get('@type')}'\")\n\n    if not schema.get(\"name\"):\n        errors.append(\"Missing 'name' field\")\n\n    if not schema.get(\"description\"):\n        errors.append(\"Missing 'description' field\")\n    elif len(schema[\"description\"]) \u003C 50:\n        errors.append(f\"Description too short ({len(schema['description'])} chars). \"\n                      \"Agents need at least 50 chars for semantic matching.\")\n\n    # Pricing validation\n    offers = schema.get(\"offers\", [])\n    if not offers:\n        errors.append(\"No offers (pricing tiers). Agents cannot evaluate cost.\")\n\n    for i, offer in enumerate(offers):\n        if offer.get(\"@type\") != \"Offer\":\n            errors.append(f\"Offer {i}: @type must be 'Offer'\")\n\n        price = offer.get(\"price\")\n        if price is None:\n            errors.append(f\"Offer {i}: missing price\")\n        elif isinstance(price, float):\n            errors.append(f\"Offer {i}: price should be string, not float \"\n                         \"(floating-point precision issues)\")\n\n        if not offer.get(\"priceCurrency\"):\n            errors.append(f\"Offer {i}: missing priceCurrency\")\n\n    # Provider validation\n    provider = schema.get(\"provider\", {})\n    if not provider.get(\"identifier\"):\n        errors.append(\"Provider missing 'identifier' (agent_id)\")\n\n    # SLA properties\n    props = schema.get(\"additionalProperty\", [])\n    prop_names = {p.get(\"name\") for p in props}\n    recommended = {\"uptimeGuarantee\", \"latencyP99\", \"supportedProtocols\"}\n    missing = recommended - prop_names\n    if missing:\n        errors.append(f\"Missing recommended properties: {', '.join(missing)}\")\n\n    return errors\n\n\n# Validate our generated schema\nerrors = validate_service_jsonld(service_schema)\nif errors:\n    print(\"Validation errors:\")\n    for err in errors:\n        print(f\"  - {err}\")\nelse:\n    print(\"Schema is valid for agent consumption\")\n```\n\n### Embedding Structured Data in HTML\n\nFor services that also have human-readable web pages, embed the JSON-LD in a `\u003Cscript>` tag. This allows both web crawlers and AI agents to parse your structured data:\n\n```html\n\u003Cscript type=\"application\u002Fld+json\">\n{\n  \"@context\": \"https:\u002F\u002Fschema.org\",\n  \"@type\": \"Service\",\n  \"name\": \"DataEnrich Pro\",\n  \"description\": \"Real-time company data enrichment with 95% match rate...\",\n  \"offers\": [\n    {\n      \"@type\": \"Offer\",\n      \"name\": \"Starter\",\n      \"price\": \"0.005\",\n      \"priceCurrency\": \"USD\"\n    }\n  ]\n}\n\u003C\u002Fscript>\n```\n\n> **Key Takeaways**\n>\n> - Schema.org JSON-LD is the only structured data vocabulary parsed by all major agent platforms.\n> - Use `@type: Service` with `Offer` for pricing and `PropertyValue` for SLA terms and protocol support.\n> - Always use string-typed prices. Floating-point values cause comparison failures in agent scoring.\n> - Auto-generate JSON-LD from GreenHelix `register_service` data to keep marketplace listing and web markup in sync.\n> - Validate structured data before deploying. One malformed field can make your entire listing unparseable.\n> - See P18 (Pricing & Monetization) for advanced pricing structures including volume discounts and tiered billing.\n\n---\n\n## Chapter 6: Real-Time Catalog Sync & Graph Maintenance\n\n### Why Stale Data Kills Agent Transactions\n\nAI agents do not tolerate stale data. When an agent queries your service listing and finds a price of $0.005 per call, it commits to that price in its transaction planning. If the actual price has changed to $0.008 since the listing was last updated, the agent will encounter a price mismatch at transaction time. Most agents treat price mismatches as a trust violation and blacklist the service. A single stale data incident can remove your service from an agent's candidate set permanently.\n\nThe tolerance for staleness varies by data type:\n\n| Data Type | Maximum Acceptable Staleness | Impact of Stale Data |\n|---|---|---|\n| **Price** | 5 minutes | Transaction failure, trust violation, blacklisting |\n| **Availability** | 1 minute | Failed purchases, wasted agent compute cycles |\n| **Capability** | 1 hour | Capability mismatch errors, degraded results |\n| **SLA terms** | 24 hours | Contractual disputes, expectation mismatches |\n| **Trust score** | 1 hour | Incorrect agent ranking, suboptimal selection |\n\n### Webhook-Driven vs. Polling: The Architecture Decision\n\nTwo approaches exist for keeping discovery data current: **polling** (agents periodically fetch your data) and **webhooks** (you push updates when data changes). Polling is simpler to implement. Webhooks are superior for freshness.\n\nWith polling, the best case is that an agent checks your listing every minute and your data is at most 60 seconds stale. The worst case is that agents poll every hour (common for low-priority services) and your data is 60 minutes stale. You have no control over polling frequency -- it is determined by the agent.\n\nWith webhooks, you push updates the moment data changes. Freshness is limited only by network latency -- typically under 500 milliseconds. You control the timing. The tradeoff is implementation complexity: you need to manage subscriber lists, handle delivery failures, and implement retry logic.\n\nThe correct answer for agent commerce is both: serve fresh data at your discovery endpoints (for agents that poll) AND push updates via webhooks (for agents that subscribe).\n\n### GreenHelix Events and Webhooks\n\nThe GreenHelix gateway provides two tools for real-time updates: `publish_event` for broadcasting state changes, and `register_webhook` for subscribing to events from other services.\n\n```python\nimport hashlib\nimport hmac\nimport time\nfrom typing import Callable\n\n\nclass CatalogSyncManager:\n    \"\"\"Manages real-time synchronization between service catalog,\n    knowledge graph, structured data, and discovery endpoints.\"\"\"\n\n    def __init__(self, discovery_client, webhook_secret: str):\n        self.client = discovery_client\n        self.webhook_secret = webhook_secret\n        self.update_handlers: list[Callable] = []\n\n    def register_update_handler(self, handler: Callable) -> None:\n        \"\"\"Register a callback for catalog updates.\"\"\"\n        self.update_handlers.append(handler)\n\n    def publish_catalog_update(\n        self,\n        agent_id: str,\n        event_type: str,\n        service_id: str,\n        changes: dict,\n    ) -> dict:\n        \"\"\"Publish a catalog change event via GreenHelix.\"\"\"\n        event_data = {\n            \"service_id\": service_id,\n            \"changes\": changes,\n            \"timestamp\": time.time(),\n            \"version\": int(time.time() * 1000),\n        }\n\n        # Publish event to GreenHelix event bus\n        result = self.client.execute(\"publish_event\", {\n            \"agent_id\": agent_id,\n            \"event_type\": f\"catalog.{event_type}\",\n            \"payload\": event_data,\n        })\n\n        # Run local update handlers\n        for handler in self.update_handlers:\n            handler(event_type, service_id, changes)\n\n        return result\n\n    def register_for_updates(\n        self,\n        agent_id: str,\n        source_agent_id: str,\n        callback_url: str,\n        event_types: list[str],\n    ) -> dict:\n        \"\"\"Subscribe to catalog updates from another service via webhook.\"\"\"\n        return self.client.execute(\"register_webhook\", {\n            \"agent_id\": agent_id,\n            \"source_agent_id\": source_agent_id,\n            \"callback_url\": callback_url,\n            \"event_types\": event_types,\n        })\n\n    def verify_webhook_signature(\n        self,\n        payload: bytes,\n        signature: str,\n    ) -> bool:\n        \"\"\"Verify that a webhook payload was sent by GreenHelix.\"\"\"\n        expected = hmac.new(\n            self.webhook_secret.encode(),\n            payload,\n            hashlib.sha256,\n        ).hexdigest()\n        return hmac.compare_digest(expected, signature)\n\n\n# Initialize\nsync_manager = CatalogSyncManager(client, webhook_secret=\"your-secret-here\")\n```\n\n### Event-Driven Pipeline: Updating Graph + Structured Data + Endpoints\n\nWhen a catalog change occurs -- price update, new capability, SLA revision -- the pipeline must update three systems in sequence: the knowledge graph, the structured data (JSON-LD), and the discovery endpoints.\n\n```python\nclass DiscoveryPipeline:\n    \"\"\"End-to-end pipeline that updates all discovery surfaces when catalog changes.\"\"\"\n\n    def __init__(\n        self,\n        graph: \"CommerceKnowledgeGraph\",\n        sync_manager: CatalogSyncManager,\n        discovery_client: \"DiscoveryClient\",\n    ):\n        self.graph = graph\n        self.sync = sync_manager\n        self.client = discovery_client\n\n        # Register handlers for automatic propagation\n        self.sync.register_update_handler(self._on_catalog_update)\n\n    def _on_catalog_update(\n        self,\n        event_type: str,\n        service_id: str,\n        changes: dict,\n    ) -> None:\n        \"\"\"Handle a catalog update by propagating to all discovery surfaces.\"\"\"\n        print(f\"Processing {event_type} for {service_id}\")\n\n        # Step 1: Update knowledge graph\n        if service_id in self.graph.services:\n            service = self.graph.services[service_id]\n            if \"pricing\" in changes:\n                self._update_pricing(service, changes[\"pricing\"])\n            if \"sla\" in changes:\n                self._update_sla(service, changes[\"sla\"])\n            if \"capabilities\" in changes:\n                self._update_capabilities(service, changes[\"capabilities\"])\n            if \"status\" in changes:\n                service.status = changes[\"status\"]\n\n        # Step 2: Regenerate JSON-LD\n        jsonld = self.graph.to_jsonld()\n        self._write_jsonld(service_id, jsonld)\n\n        # Step 3: Update marketplace listing\n        self._sync_marketplace(service_id)\n\n        print(f\"Discovery surfaces updated for {service_id}\")\n\n    def _update_pricing(self, service: \"ServiceNode\", pricing: dict) -> None:\n        \"\"\"Update pricing tiers on a service node.\"\"\"\n        if \"tiers\" in pricing:\n            service.pricing_tiers = [\n                PricingTier(\n                    tier_name=t[\"name\"],\n                    cost_per_call=float(t[\"cost_per_call\"]),\n                    currency=t.get(\"currency\", \"USD\"),\n                    monthly_cap=float(t[\"monthly_cap\"]) if \"monthly_cap\" in t else None,\n                )\n                for t in pricing[\"tiers\"]\n            ]\n\n    def _update_sla(self, service: \"ServiceNode\", sla_data: dict) -> None:\n        \"\"\"Update SLA terms on a service node.\"\"\"\n        if service.sla:\n            for key, value in sla_data.items():\n                if hasattr(service.sla, key):\n                    setattr(service.sla, key, value)\n\n    def _update_capabilities(self, service: \"ServiceNode\", caps: list) -> None:\n        \"\"\"Update capability list (triggers MCP manifest regeneration).\"\"\"\n        service.tags = [c.get(\"name\", \"\") for c in caps if \"name\" in c]\n\n    def _write_jsonld(self, service_id: str, jsonld: list[dict]) -> None:\n        \"\"\"Write updated JSON-LD to file (or key-value store in production).\"\"\"\n        target = next(\n            (j for j in jsonld if service_id in j.get(\"@id\", \"\")),\n            None,\n        )\n        if target:\n            with open(f\"\u002Fvar\u002Fdata\u002Fschemas\u002F{service_id}.jsonld\", \"w\") as f:\n                json.dump(target, f, indent=2)\n\n    def _sync_marketplace(self, service_id: str) -> None:\n        \"\"\"Push updated data to GreenHelix marketplace.\"\"\"\n        if service_id not in self.graph.services:\n            return\n\n        service = self.graph.services[service_id]\n        cheapest = min(\n            service.pricing_tiers,\n            key=lambda t: t.cost_per_call,\n        ) if service.pricing_tiers else None\n\n        self.client.execute(\"update_service\", {\n            \"service_id\": service_id,\n            \"pricing\": {\n                \"model\": cheapest.billing_model if cheapest else \"contact\",\n                \"base_price\": str(cheapest.cost_per_call) if cheapest else \"0\",\n                \"currency\": cheapest.currency if cheapest else \"USD\",\n            },\n            \"sla\": {\n                \"uptime_guarantee\": service.sla.uptime_guarantee,\n                \"latency_p99_ms\": service.sla.latency_p99_ms,\n            } if service.sla else None,\n            \"status\": service.status,\n        })\n\n\n# Wire up the pipeline\npipeline = DiscoveryPipeline(graph, sync_manager, client)\n\n# Example: price change triggers automatic propagation\nsync_manager.publish_catalog_update(\n    agent_id=\"agent-dataenrich-prod\",\n    event_type=\"pricing_updated\",\n    service_id=\"data-enrichment-v2\",\n    changes={\n        \"pricing\": {\n            \"tiers\": [\n                {\"name\": \"starter\", \"cost_per_call\": \"0.004\", \"monthly_cap\": \"100.00\"},\n                {\"name\": \"growth\", \"cost_per_call\": \"0.0025\", \"monthly_cap\": \"500.00\"},\n            ],\n        },\n    },\n)\n```\n\n### Subscribing to External Catalog Updates\n\nWhen your agent depends on external services, subscribe to their catalog events so your graph stays current:\n\n```python\n# Subscribe to pricing updates from a dependency\nsync_manager.register_for_updates(\n    agent_id=\"agent-my-service\",\n    source_agent_id=\"agent-dataenrich-prod\",\n    callback_url=\"https:\u002F\u002Fmy-service.example.com\u002Fwebhooks\u002Fcatalog\",\n    event_types=[\"catalog.pricing_updated\", \"catalog.status_changed\"],\n)\n\n# Webhook receiver endpoint (add to your FastAPI app)\n@app.post(\"\u002Fwebhooks\u002Fcatalog\")\nasync def receive_catalog_webhook(request: Request):\n    \"\"\"Handle incoming catalog update webhooks from GreenHelix.\"\"\"\n    body = await request.body()\n    signature = request.headers.get(\"X-GreenHelix-Signature\", \"\")\n\n    if not sync_manager.verify_webhook_signature(body, signature):\n        return JSONResponse(status_code=401, content={\"error\": \"Invalid signature\"})\n\n    payload = json.loads(body)\n    event_type = payload.get(\"event_type\", \"\")\n    service_id = payload.get(\"service_id\", \"\")\n    changes = payload.get(\"changes\", {})\n\n    # Update our local graph with the external service's changes\n    pipeline._on_catalog_update(event_type, service_id, changes)\n\n    return {\"status\": \"accepted\"}\n```\n\n> **Key Takeaways**\n>\n> - Stale pricing data causes transaction failures and agent blacklisting. Maximum acceptable price staleness is 5 minutes.\n> - Implement both polling-friendly endpoints (always serve fresh data) and webhook-driven push updates.\n> - GreenHelix `publish_event` broadcasts catalog changes. `register_webhook` subscribes to changes from dependencies.\n> - Build a pipeline that propagates every catalog change to three surfaces: knowledge graph, JSON-LD, and marketplace listing.\n> - Always verify webhook signatures to prevent spoofed updates from corrupting your graph.\n> - See P20 (Production Hardening) for webhook retry policies and dead-letter queues.\n\n---\n\n## Chapter 7: Trust Signals & Reputation in Agent Discovery\n\n### Why Agents Rank by Trust, Not Just Price\n\nWhen an AI agent evaluates ten services that all claim 99.9% uptime and $0.005 per call, it needs a tiebreaker. That tiebreaker is trust. The agent cannot verify marketing claims at query time. It cannot call references. It cannot run a benchmark. What it can do is check cryptographic trust signals: verified metrics submitted through authenticated APIs, Merkle claim chains that prove history has not been tampered with, composite reputation scores computed from transaction history, and escrow completion rates that show how the service behaves under contractual obligations.\n\nTrust-based ranking is not hypothetical. The GreenHelix `best_match` tool uses trust score as a weighted factor in its ranking algorithm alongside price, SLA terms, and capability match. A service with a 0.92 trust score and $0.006 per call will rank above a service with no trust score and $0.004 per call for most agent configurations. The reason is risk-adjusted value: an agent that chooses the cheaper untrusted service has no recourse if the service fails, while the trusted service has verifiable history proving it delivers on its claims.\n\n### The Trust Signal Hierarchy\n\nNot all trust signals carry equal weight. Agents evaluate them in order of cryptographic strength:\n\n| Signal | Source | Forgery Difficulty | Agent Weight |\n|---|---|---|---|\n| **Merkle claim chain** | `build_claim_chain` | Computationally infeasible | Highest |\n| **Verified metrics** | `submit_metrics` | Requires compromised API key | High |\n| **Trust score** | `check_trust_score` | Composite -- reflects all signals | High |\n| **Agent verification** | `verify_agent` | Requires private key | Medium-High |\n| **Escrow completion rate** | Transaction history | Requires real transactions | Medium |\n| **Service ratings** | `rate_service` | Sybil-attackable without guards | Lower |\n\n### Surfacing Trust in UCP Profiles\n\nThe UCP profile from Chapter 4 included a `trust_score` field. This section shows how to populate it with real data from the GreenHelix trust and reputation systems.\n\n```python\nclass TrustEnrichedDiscovery:\n    \"\"\"Enriches discovery endpoints with real-time trust signals.\"\"\"\n\n    def __init__(self, discovery_client):\n        self.client = discovery_client\n\n    def get_trust_profile(self, agent_id: str) -> dict:\n        \"\"\"Fetch complete trust profile for an agent.\"\"\"\n        trust_data = {}\n\n        # Get verification status\n        try:\n            verification = self.client.execute(\"verify_agent\", {\n                \"agent_id\": agent_id,\n            })\n            trust_data[\"verified\"] = verification.get(\"verified\", False)\n            trust_data[\"verification_method\"] = verification.get(\"method\", \"unknown\")\n        except Exception:\n            trust_data[\"verified\"] = False\n\n        # Get trust score\n        try:\n            trust = self.client.execute(\"check_trust_score\", {\n                \"agent_id\": agent_id,\n            })\n            trust_data[\"trust_score\"] = trust.get(\"score\", 0.0)\n            trust_data[\"trust_factors\"] = trust.get(\"factors\", {})\n        except Exception:\n            trust_data[\"trust_score\"] = 0.0\n\n        # Get reputation metrics\n        try:\n            reputation = self.client.execute(\"get_agent_reputation\", {\n                \"agent_id\": agent_id,\n            })\n            trust_data[\"reputation\"] = {\n                \"trade_count\": reputation.get(\"trade_count\", 0),\n                \"success_rate\": reputation.get(\"success_rate\", 0.0),\n                \"avg_rating\": reputation.get(\"avg_rating\", 0.0),\n                \"active_since\": reputation.get(\"active_since\", \"\"),\n            }\n        except Exception:\n            trust_data[\"reputation\"] = {}\n\n        # Get claim chain depth (tamper-evidence)\n        try:\n            chains = self.client.execute(\"get_claim_chains\", {\n                \"agent_id\": agent_id,\n            })\n            chain_list = chains.get(\"chains\", [])\n            trust_data[\"claim_chain\"] = {\n                \"depth\": len(chain_list),\n                \"latest_root_hash\": chain_list[0].get(\"root_hash\", \"\") if chain_list else \"\",\n                \"covers_from\": chain_list[-1].get(\"timestamp\", \"\") if chain_list else \"\",\n                \"covers_to\": chain_list[0].get(\"timestamp\", \"\") if chain_list else \"\",\n            }\n        except Exception:\n            trust_data[\"claim_chain\"] = {\"depth\": 0}\n\n        return trust_data\n\n    def enrich_ucp_profile(self, ucp_profile: dict, agent_id: str) -> dict:\n        \"\"\"Add real-time trust signals to a UCP profile.\"\"\"\n        trust = self.get_trust_profile(agent_id)\n\n        ucp_profile[\"service\"][\"provider\"][\"trust_score\"] = trust.get(\"trust_score\", 0.0)\n        ucp_profile[\"service\"][\"provider\"][\"verified\"] = trust.get(\"verified\", False)\n        ucp_profile[\"service\"][\"provider\"][\"verification_method\"] = trust.get(\n            \"verification_method\", \"none\"\n        )\n\n        ucp_profile[\"trust\"] = {\n            \"score\": trust.get(\"trust_score\", 0.0),\n            \"factors\": trust.get(\"trust_factors\", {}),\n            \"reputation\": trust.get(\"reputation\", {}),\n            \"claim_chain\": trust.get(\"claim_chain\", {}),\n        }\n\n        # Update verification status\n        score = trust.get(\"trust_score\", 0.0)\n        if score >= 0.9:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"highly_trusted\"\n        elif score >= 0.7:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"verified\"\n        elif score >= 0.4:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"partially_verified\"\n        else:\n            ucp_profile[\"service\"][\"provider\"][\"verification_status\"] = \"unverified\"\n\n        return ucp_profile\n\n\n# Enrich our UCP profile with real trust data\ntrust_discovery = TrustEnrichedDiscovery(client)\nenriched_profile = trust_discovery.enrich_ucp_profile(\n    ucp_profile,\n    agent_id=\"agent-dataenrich-prod\",\n)\nprint(f\"Trust score: {enriched_profile['trust']['score']}\")\nprint(f\"Claim chain depth: {enriched_profile['trust']['claim_chain']['depth']}\")\n```\n\n### Building Your Trust Profile\n\nTrust is not just consumed by agents during discovery -- it must be built over time. Here is the lifecycle for establishing a credible trust profile:\n\n```python\nclass TrustBuilder:\n    \"\"\"Tools for building a verifiable trust profile on GreenHelix.\"\"\"\n\n    def __init__(self, discovery_client, agent_id: str):\n        self.client = discovery_client\n        self.agent_id = agent_id\n\n    def submit_performance_metrics(self, metrics: dict) -> dict:\n        \"\"\"Submit verified performance metrics.\n\n        Call this regularly (daily or after each significant batch).\n        Consistent submissions build trust; gaps raise red flags.\n        \"\"\"\n        return self.client.execute(\"submit_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"metrics\": metrics,\n        })\n\n    def build_claim_chain(self) -> dict:\n        \"\"\"Build a Merkle claim chain over recent metric submissions.\n\n        Call this weekly. The chain creates a tamper-evident history\n        that agents can verify independently.\n        \"\"\"\n        return self.client.execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def get_trust_improvement_plan(self) -> list[dict]:\n        \"\"\"Analyze current trust profile and recommend improvements.\"\"\"\n        trust = self.client.execute(\"check_trust_score\", {\n            \"agent_id\": self.agent_id,\n        })\n        score = trust.get(\"score\", 0.0)\n        factors = trust.get(\"factors\", {})\n\n        recommendations = []\n\n        if factors.get(\"metric_submissions\", 0) \u003C 30:\n            recommendations.append({\n                \"action\": \"Submit daily metrics for 30+ days\",\n                \"impact\": \"high\",\n                \"current\": factors.get(\"metric_submissions\", 0),\n                \"target\": 30,\n            })\n\n        if factors.get(\"claim_chain_depth\", 0) \u003C 4:\n            recommendations.append({\n                \"action\": \"Build weekly claim chains for 4+ weeks\",\n                \"impact\": \"high\",\n                \"current\": factors.get(\"claim_chain_depth\", 0),\n                \"target\": 4,\n            })\n\n        if factors.get(\"trade_count\", 0) \u003C 50:\n            recommendations.append({\n                \"action\": \"Complete 50+ successful transactions\",\n                \"impact\": \"medium\",\n                \"current\": factors.get(\"trade_count\", 0),\n                \"target\": 50,\n            })\n\n        if factors.get(\"escrow_completion_rate\", 0) \u003C 0.95:\n            recommendations.append({\n                \"action\": \"Improve escrow completion rate above 95%\",\n                \"impact\": \"high\",\n                \"current\": factors.get(\"escrow_completion_rate\", 0),\n                \"target\": 0.95,\n            })\n\n        return recommendations\n\n\n# Build trust over time\nbuilder = TrustBuilder(client, \"agent-dataenrich-prod\")\n\n# Submit today's metrics\nbuilder.submit_performance_metrics({\n    \"uptime_pct\": 99.97,\n    \"latency_p99_ms\": 187,\n    \"requests_processed\": 45230,\n    \"error_rate\": 0.0003,\n    \"match_rate\": 0.952,\n})\n\n# Weekly: build claim chain\nchain_result = builder.build_claim_chain()\nprint(f\"Claim chain built: {chain_result.get('root_hash', '')[:16]}...\")\n\n# Check what to improve\nplan = builder.get_trust_improvement_plan()\nfor rec in plan:\n    print(f\"[{rec['impact'].upper()}] {rec['action']} \"\n          f\"(current: {rec['current']}, target: {rec['target']})\")\n```\n\n### Trust in JSON-LD Structured Data\n\nExtend your Schema.org JSON-LD to include trust signals so agents parsing your web-embedded structured data also get trust information:\n\n```python\ndef add_trust_to_jsonld(jsonld: dict, trust_profile: dict) -> dict:\n    \"\"\"Add trust signals to a Schema.org JSON-LD service document.\"\"\"\n    props = jsonld.setdefault(\"additionalProperty\", [])\n\n    props.append({\n        \"@type\": \"PropertyValue\",\n        \"name\": \"trustScore\",\n        \"value\": trust_profile.get(\"trust_score\", 0.0),\n        \"description\": \"GreenHelix composite trust score (0-1)\",\n    })\n\n    props.append({\n        \"@type\": \"PropertyValue\",\n        \"name\": \"claimChainDepth\",\n        \"value\": trust_profile.get(\"claim_chain\", {}).get(\"depth\", 0),\n        \"description\": \"Merkle claim chain depth (tamper-evidence)\",\n    })\n\n    if trust_profile.get(\"reputation\", {}).get(\"trade_count\", 0) > 0:\n        props.append({\n            \"@type\": \"PropertyValue\",\n            \"name\": \"verifiedTradeCount\",\n            \"value\": trust_profile[\"reputation\"][\"trade_count\"],\n            \"description\": \"Number of completed escrow-verified transactions\",\n        })\n\n    if trust_profile.get(\"verified\"):\n        props.append({\n            \"@type\": \"PropertyValue\",\n            \"name\": \"identityVerified\",\n            \"value\": True,\n            \"description\": \"Ed25519 cryptographic identity verification\",\n        })\n\n    return jsonld\n\n\n# Add trust to our JSON-LD\ntrust_profile = trust_discovery.get_trust_profile(\"agent-dataenrich-prod\")\nenriched_jsonld = add_trust_to_jsonld(service_schema, trust_profile)\n```\n\n> **Key Takeaways**\n>\n> - Agents rank by trust-adjusted value, not raw price. A trusted service at a higher price beats an untrusted service at a lower price.\n> - Trust signals have a hierarchy: Merkle claim chains (strongest) > verified metrics > trust score > agent verification > ratings (weakest).\n> - Enrich UCP profiles with real-time trust data from `check_trust_score`, `verify_agent`, `get_agent_reputation`, and `get_claim_chains`.\n> - Build trust over time: submit daily metrics, build weekly claim chains, complete escrow transactions, maintain high completion rates.\n> - Embed trust signals in Schema.org JSON-LD so agents that discover you via web crawling also get trust information.\n> - See P5 (Trust & Verification) for the complete trust-building playbook and Merkle claim chain deep-dive.\n\n---\n\n## Chapter 8: Measuring Discovery Performance\n\n### The Metrics That Matter\n\nDiscovery is not a binary state. You are not simply \"discoverable\" or \"not discoverable.\" Discovery performance exists on a spectrum, and measuring it requires specific metrics that most commerce analytics dashboards do not track. Traditional analytics measure page views, click-through rates, and conversion funnels designed for human visitors. Agent discovery requires a different set of metrics.\n\n**Discovery Rate** -- The percentage of relevant agent queries that return your service in the results. If agents make 1,000 queries that match your service's capabilities and your service appears in 340 of those result sets, your discovery rate is 34%. This is the top-of-funnel metric for agent commerce.\n\n**Agent Conversion Rate** -- The percentage of discovered services that proceed to a transaction. If your service appears in 340 query results and 68 of those result in a completed transaction, your agent conversion rate is 20%. This measures how compelling your listing is once found.\n\n**Time-to-Transaction** -- The elapsed time from an agent's first discovery query to transaction completion. Shorter is better. Long times indicate friction in your protocol endpoints, slow API responses, or missing structured data that forces agents to make additional queries.\n\n**Ranking Position** -- Where your service appears in search results. Position 1-3 captures the vast majority of agent transactions. Position 10+ is functionally invisible because most agents evaluate only the top results.\n\n**Trust-Adjusted Rank** -- Your ranking position after trust score weighting. A service with strong capabilities but weak trust will rank lower than a service with strong trust. This metric tells you whether trust is helping or hurting your discoverability.\n\n### GreenHelix Analytics\n\nThe GreenHelix gateway provides analytics tools that measure these metrics directly:\n\n```python\nclass DiscoveryAnalytics:\n    \"\"\"Track and analyze agent discovery performance.\"\"\"\n\n    def __init__(self, discovery_client, agent_id: str):\n        self.client = discovery_client\n        self.agent_id = agent_id\n\n    def get_discovery_metrics(self, period: str = \"30d\") -> dict:\n        \"\"\"Fetch discovery performance metrics from GreenHelix.\"\"\"\n        usage = self.client.execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"metrics\": [\n                \"search_appearances\",\n                \"search_impressions\",\n                \"best_match_wins\",\n                \"api_calls\",\n                \"transactions_completed\",\n                \"transaction_value\",\n            ],\n        })\n\n        revenue = self.client.execute(\"get_revenue_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n        # Calculate derived metrics\n        appearances = usage.get(\"search_appearances\", 0)\n        transactions = usage.get(\"transactions_completed\", 0)\n        best_match_wins = usage.get(\"best_match_wins\", 0)\n\n        return {\n            \"period\": period,\n            \"raw_metrics\": usage,\n            \"revenue\": revenue,\n            \"derived\": {\n                \"discovery_rate\": (\n                    appearances \u002F usage.get(\"search_impressions\", 1)\n                    if usage.get(\"search_impressions\", 0) > 0\n                    else 0.0\n                ),\n                \"conversion_rate\": (\n                    transactions \u002F appearances\n                    if appearances > 0\n                    else 0.0\n                ),\n                \"best_match_rate\": (\n                    best_match_wins \u002F appearances\n                    if appearances > 0\n                    else 0.0\n                ),\n                \"avg_transaction_value\": (\n                    usage.get(\"transaction_value\", 0) \u002F transactions\n                    if transactions > 0\n                    else 0.0\n                ),\n                \"revenue_per_impression\": (\n                    revenue.get(\"total_revenue\", 0) \u002F usage.get(\"search_impressions\", 1)\n                    if usage.get(\"search_impressions\", 0) > 0\n                    else 0.0\n                ),\n            },\n        }\n\n    def compare_periods(self, current: str = \"7d\", previous: str = \"7d\") -> dict:\n        \"\"\"Compare discovery metrics between two periods.\"\"\"\n        current_metrics = self.get_discovery_metrics(current)\n        previous_metrics = self.get_discovery_metrics(previous)\n\n        comparison = {}\n        for key in current_metrics[\"derived\"]:\n            curr_val = current_metrics[\"derived\"][key]\n            prev_val = previous_metrics[\"derived\"].get(key, 0)\n            if prev_val > 0:\n                change_pct = ((curr_val - prev_val) \u002F prev_val) * 100\n            else:\n                change_pct = 100.0 if curr_val > 0 else 0.0\n            comparison[key] = {\n                \"current\": curr_val,\n                \"previous\": prev_val,\n                \"change_pct\": round(change_pct, 2),\n            }\n\n        return comparison\n\n    def discovery_health_check(self) -> list[dict]:\n        \"\"\"Run a comprehensive discovery health check.\n\n        Returns a list of checks with pass\u002Ffail\u002Fwarn status.\n        \"\"\"\n        checks = []\n\n        # Check 1: UCP endpoint responds\n        try:\n            # Simulate by verifying our service is registered\n            service = self.client.execute(\"get_service\", {\n                \"agent_id\": self.agent_id,\n            })\n            checks.append({\n                \"check\": \"marketplace_listing\",\n                \"status\": \"pass\" if service else \"fail\",\n                \"detail\": \"Service is registered on GreenHelix marketplace\",\n            })\n        except Exception as e:\n            checks.append({\n                \"check\": \"marketplace_listing\",\n                \"status\": \"fail\",\n                \"detail\": f\"Service not found: {e}\",\n            })\n\n        # Check 2: Trust score above threshold\n        try:\n            trust = self.client.execute(\"check_trust_score\", {\n                \"agent_id\": self.agent_id,\n            })\n            score = trust.get(\"score\", 0.0)\n            checks.append({\n                \"check\": \"trust_score\",\n                \"status\": \"pass\" if score >= 0.7 else \"warn\" if score >= 0.4 else \"fail\",\n                \"detail\": f\"Trust score: {score} (threshold: 0.7)\",\n                \"value\": score,\n            })\n        except Exception:\n            checks.append({\n                \"check\": \"trust_score\",\n                \"status\": \"fail\",\n                \"detail\": \"Unable to fetch trust score\",\n            })\n\n        # Check 3: Recent metrics submissions\n        try:\n            claims = self.client.execute(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claim_count = len(claims.get(\"claims\", []))\n            checks.append({\n                \"check\": \"metric_submissions\",\n                \"status\": \"pass\" if claim_count >= 7 else \"warn\" if claim_count >= 1 else \"fail\",\n                \"detail\": f\"{claim_count} verified claims (target: 7+ for weekly)\",\n                \"value\": claim_count,\n            })\n        except Exception:\n            checks.append({\n                \"check\": \"metric_submissions\",\n                \"status\": \"fail\",\n                \"detail\": \"Unable to fetch verified claims\",\n            })\n\n        # Check 4: Claim chain exists\n        try:\n            chains = self.client.execute(\"get_claim_chains\", {\n                \"agent_id\": self.agent_id,\n            })\n            depth = len(chains.get(\"chains\", []))\n            checks.append({\n                \"check\": \"claim_chain\",\n                \"status\": \"pass\" if depth >= 4 else \"warn\" if depth >= 1 else \"fail\",\n                \"detail\": f\"Claim chain depth: {depth} (target: 4+ for monthly)\",\n                \"value\": depth,\n            })\n        except Exception:\n            checks.append({\n                \"check\": \"claim_chain\",\n                \"status\": \"warn\",\n                \"detail\": \"Unable to fetch claim chains\",\n            })\n\n        # Check 5: Search visibility\n        metrics = self.get_discovery_metrics(\"7d\")\n        dr = metrics[\"derived\"][\"discovery_rate\"]\n        checks.append({\n            \"check\": \"discovery_rate\",\n            \"status\": \"pass\" if dr >= 0.3 else \"warn\" if dr >= 0.1 else \"fail\",\n            \"detail\": f\"Discovery rate: {dr:.1%} (target: 30%+)\",\n            \"value\": dr,\n        })\n\n        # Check 6: Conversion\n        cr = metrics[\"derived\"][\"conversion_rate\"]\n        checks.append({\n            \"check\": \"conversion_rate\",\n            \"status\": \"pass\" if cr >= 0.15 else \"warn\" if cr >= 0.05 else \"fail\",\n            \"detail\": f\"Conversion rate: {cr:.1%} (target: 15%+)\",\n            \"value\": cr,\n        })\n\n        return checks\n\n\n# Run discovery analytics\nanalytics = DiscoveryAnalytics(client, \"agent-dataenrich-prod\")\n\n# Get current metrics\nmetrics = analytics.get_discovery_metrics(\"30d\")\nprint(f\"Discovery rate: {metrics['derived']['discovery_rate']:.1%}\")\nprint(f\"Conversion rate: {metrics['derived']['conversion_rate']:.1%}\")\nprint(f\"Best match rate: {metrics['derived']['best_match_rate']:.1%}\")\nprint(f\"Revenue per impression: ${metrics['derived']['revenue_per_impression']:.4f}\")\n\n# Week-over-week comparison\ncomparison = analytics.compare_periods(\"7d\", \"7d\")\nfor metric, data in comparison.items():\n    direction = \"up\" if data[\"change_pct\"] > 0 else \"down\"\n    print(f\"{metric}: {data['current']:.4f} ({direction} {abs(data['change_pct'])}%)\")\n\n# Health check\nhealth = analytics.discovery_health_check()\nfor check in health:\n    icon = {\"pass\": \"OK\", \"warn\": \"WARN\", \"fail\": \"FAIL\"}[check[\"status\"]]\n    print(f\"[{icon}] {check['check']}: {check['detail']}\")\n```\n\n### A\u002FB Testing Structured Data\n\nDifferent structured data configurations produce different discovery outcomes. A\u002FB testing lets you determine which configuration maximizes your metrics. The approach is straightforward: run two versions of your structured data simultaneously (served to different agent cohorts) and compare performance.\n\n```python\nclass StructuredDataExperiment:\n    \"\"\"A\u002FB test different structured data configurations.\"\"\"\n\n    def __init__(self, discovery_client, agent_id: str):\n        self.client = discovery_client\n        self.agent_id = agent_id\n\n    def run_experiment(\n        self,\n        variant_a: dict,\n        variant_b: dict,\n        description: str,\n        duration_days: int = 14,\n    ) -> dict:\n        \"\"\"Set up an A\u002FB test between two structured data configurations.\n\n        In practice, you would deploy both variants and route traffic\n        based on a hash of the requesting agent's ID. This method\n        registers both variants and returns the experiment config.\n        \"\"\"\n        experiment = {\n            \"experiment_id\": f\"exp_{int(time.time())}\",\n            \"description\": description,\n            \"duration_days\": duration_days,\n            \"variant_a\": {\n                \"config\": variant_a,\n                \"label\": \"control\",\n            },\n            \"variant_b\": {\n                \"config\": variant_b,\n                \"label\": \"treatment\",\n            },\n        }\n\n        # Publish experiment start event for tracking\n        self.client.execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"experiment.started\",\n            \"payload\": {\n                \"experiment_id\": experiment[\"experiment_id\"],\n                \"description\": description,\n                \"variants\": [\"a\", \"b\"],\n            },\n        })\n\n        return experiment\n\n    def analyze_results(\n        self,\n        experiment_id: str,\n        variant_a_metrics: dict,\n        variant_b_metrics: dict,\n    ) -> dict:\n        \"\"\"Compare two variants and declare a winner.\"\"\"\n        results = {}\n        for metric in [\"discovery_rate\", \"conversion_rate\", \"revenue_per_impression\"]:\n            a_val = variant_a_metrics.get(metric, 0)\n            b_val = variant_b_metrics.get(metric, 0)\n            lift = ((b_val - a_val) \u002F a_val * 100) if a_val > 0 else 0\n\n            results[metric] = {\n                \"variant_a\": a_val,\n                \"variant_b\": b_val,\n                \"lift_pct\": round(lift, 2),\n                \"winner\": \"b\" if b_val > a_val else \"a\" if a_val > b_val else \"tie\",\n            }\n\n        return results\n\n\n# Example: test whether detailed SLA properties improve discovery\nexperiment = StructuredDataExperiment(client, \"agent-dataenrich-prod\")\nexp = experiment.run_experiment(\n    variant_a={\n        \"sla_properties\": [\"uptimeGuarantee\"],  # Minimal SLA info\n    },\n    variant_b={\n        \"sla_properties\": [  # Full SLA info\n            \"uptimeGuarantee\", \"latencyP99\",\n            \"supportResponseTime\", \"dataRetentionDays\",\n        ],\n    },\n    description=\"Test whether detailed SLA properties improve agent discovery rate\",\n    duration_days=14,\n)\nprint(f\"Experiment started: {exp['experiment_id']}\")\n```\n\n### Discovery Dashboard\n\nCombine all metrics into a single dashboard view:\n\n```python\ndef print_discovery_dashboard(analytics: DiscoveryAnalytics) -> None:\n    \"\"\"Print a comprehensive discovery performance dashboard.\"\"\"\n    metrics = analytics.get_discovery_metrics(\"30d\")\n    health = analytics.discovery_health_check()\n    comparison = analytics.compare_periods(\"7d\", \"7d\")\n\n    print(\"=\" * 60)\n    print(\"DISCOVERY PERFORMANCE DASHBOARD\")\n    print(\"=\" * 60)\n\n    print(\"\\n--- 30-Day Metrics ---\")\n    d = metrics[\"derived\"]\n    print(f\"Discovery Rate:          {d['discovery_rate']:.1%}\")\n    print(f\"Conversion Rate:         {d['conversion_rate']:.1%}\")\n    print(f\"Best Match Win Rate:     {d['best_match_rate']:.1%}\")\n    print(f\"Avg Transaction Value:   ${d['avg_transaction_value']:.4f}\")\n    print(f\"Revenue per Impression:  ${d['revenue_per_impression']:.6f}\")\n\n    print(\"\\n--- Week-over-Week Changes ---\")\n    for metric, data in comparison.items():\n        arrow = \"+\" if data[\"change_pct\"] > 0 else \"\"\n        print(f\"{metric:30s} {arrow}{data['change_pct']}%\")\n\n    print(\"\\n--- Health Checks ---\")\n    for check in health:\n        status_label = {\"pass\": \"PASS\", \"warn\": \"WARN\", \"fail\": \"FAIL\"}[check[\"status\"]]\n        print(f\"[{status_label:4s}] {check['check']:25s} {check['detail']}\")\n\n    print(\"\\n\" + \"=\" * 60)\n\n\n# Run the dashboard\nprint_discovery_dashboard(analytics)\n```\n\n### Debugging Checklist\n\nWhen discovery metrics are underperforming, work through this checklist in order:\n\n| # | Check | Tool \u002F Method | Expected Result | Common Fix |\n|---|---|---|---|---|\n| 1 | Is service registered? | `get_service` | Returns service data | Run `register_service` |\n| 2 | Does `search_services` find you? | `search_services` with your category | Service in results | Improve description keywords |\n| 3 | Does `best_match` select you? | `best_match` with specific requirements | Your service returned | Improve trust score, lower price, add capabilities |\n| 4 | Is UCP endpoint live? | `GET \u002F.well-known\u002Fucp` | 200 with valid JSON | Deploy endpoint (Chapter 4) |\n| 5 | Is A2A card live? | `GET \u002F.well-known\u002Fagent.json` | 200 with valid JSON | Deploy agent card (Chapter 4) |\n| 6 | Is MCP manifest live? | `GET \u002Fmcp\u002Ftools` | 200 with tools array | Deploy MCP manifest (Chapter 4) |\n| 7 | Is JSON-LD valid? | `validate_service_jsonld()` | No errors | Fix validation errors (Chapter 5) |\n| 8 | Is pricing current? | Compare listing vs actual price | Match | Trigger catalog sync (Chapter 6) |\n| 9 | Is trust score adequate? | `check_trust_score` | >= 0.7 | Submit metrics, build claim chains (Chapter 7) |\n| 10 | Are webhook events flowing? | `publish_event` + check subscriber count | Events published | Register webhooks (Chapter 6) |\n\nIf all ten checks pass and discovery rate is still below 30%, the issue is competitive: other services in your category have stronger listings. Improve your `description_for_model` with more specific keywords, add capabilities, lower pricing, or increase trust score through consistent metric submissions and claim chain building.\n\n> **Key Takeaways**\n>\n> - Five metrics define discovery performance: discovery rate, agent conversion rate, time-to-transaction, ranking position, and trust-adjusted rank.\n> - GreenHelix `get_usage_analytics` and `get_revenue_metrics` provide the raw data. Derive discovery rate and conversion rate from search appearances and completed transactions.\n> - A\u002FB test structured data configurations to find the optimal attribute set. More SLA detail often improves discovery rate.\n> - Run weekly health checks. A single failing check (expired trust, stale pricing, missing endpoint) can collapse discovery metrics.\n> - The 10-point debugging checklist covers the full discovery stack from registration to trust to endpoint availability.\n> - See P21 (Agent-Ready Commerce) Chapter 7 for the complete agent discoverability test harness.\n\n---\n\n## Conclusion: The Discovery Flywheel\n\nDiscovery in agent commerce is not a one-time setup task. It is a flywheel with four stages:\n\n1. **Build** -- Knowledge graph, structured data, protocol endpoints (Chapters 2-5)\n2. **Publish** -- Register on marketplace, push events, keep data fresh (Chapter 6)\n3. **Trust** -- Submit metrics, build claim chains, maintain reputation (Chapter 7)\n4. **Measure** -- Track discovery rate, conversion, ranking. Feed improvements back into Build (Chapter 8)\n\nEach rotation through the flywheel makes the next one more effective. A service with six months of consistent metric submissions, deep claim chains, hundreds of completed transactions, and optimized structured data will compound its discovery advantage over competitors who started later or maintain their listings less diligently.\n\nThe 805% year-over-year growth in AI-referred traffic is not slowing down. The services that invest in discovery infrastructure today will capture a disproportionate share of that traffic tomorrow. The services that do not will join the 40% that agents cannot see.\n\nStart with Chapter 2. Build your graph. Implement UCP. Submit your first metrics. The flywheel starts with a single rotation.\n\n---\n\n*This guide uses the GreenHelix A2A Commerce Gateway (128 tools, `https:\u002F\u002Fapi.greenhelix.net\u002Fv1`). For related topics, see: P21 (Agent-Ready Commerce) for agent-ready storefronts, P18 (Pricing & Monetization) for advanced pricing structures, P5 (Trust & Verification) for the complete trust-building playbook, and P20 (Production Hardening) for deploying discovery infrastructure at scale.*\n\n",{"name":5,"tags":24,"type":31,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":45,"executable":20,"credentials":46,"description":7,"content_type":47,"compatibility":48},[25,26,27,28,29,30,31,32,33,34],"discovery","knowledge-graph","ucp","mcp","structured-data","schema-org","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42,43,44],"GREENHELIX_API_KEY","AGENT_SIGNING_KEY","STRIPE_API_KEY",0,[42,43,44],"markdown",[33],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-discovery","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-discovery",{"tool":63,"command":64},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-discovery",{"tool":66,"command":67},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-discovery","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-discovery\u002FSKILL.md",true,[],[72,79,86,93,100,107],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]