# EUDR.agent Comprehensive AI Reference & Technical Specification

> Complete technical documentation for autonomous agents, LLMs, and multi-agent pipelines interacting with EUDR (Regulation EU 2023/1115) Compliance Infrastructure.

## 1. Regulatory Context (EU 2023/1115)
The European Union Deforestation Regulation (EUDR) mandates that operators and traders placing 7 key commodities (Cattle, Cocoa, Coffee, Oil palm, Rubber, Soya, Wood) into the EU market must prove:
1. **Deforestation-Free**: Produced on land that has not been subject to deforestation after 31 December 2020.
2. **Legally Produced**: In accordance with the relevant legislation of the country of production.
3. **Traceability**: Accompanied by exact geolocation coordinates (points for plots < 4 ha, polygon perimeters for plots >= 4 ha).
4. **Due Diligence Statement (DDS)**: Registered on the EU TRACES-NT (Trade Control and Expert System) portal prior to import.

---

## 2. Agent Integration Protocols

### A. Model Context Protocol (MCP)
- **JSON-RPC Endpoint**: `POST /api/v1/mcp`
- **Supported Methods**:
  - `initialize`: Returns protocol capabilities and server information.
  - `tools/list`: Returns full JSON schema for all available tools.
  - `tools/call`: Executes specified tool with `{"name": "...", "arguments": {...}}`.
  - `prompts/list`: Lists pre-configured EUDR audit workflows.
  - `prompts/get`: Retrieves prompt templates.
- **Header**: `Content-Type: application/json`

#### Example MCP tools/call Request:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "eudr_verify_plot",
    "arguments": {
      "plot_id": "PLOT-ID-2026-001",
      "country_code": "ID",
      "commodity": "oil_palm",
      "coordinates": [101.45, 0.52],
      "area_hectares": 2.5
    }
  }
}
```

---

### B. Direct Agent Tools Endpoint
- **Discovery**: `GET /api/v1/agent/tools`
  Returns all registered tool definitions in OpenAI / Anthropic / Gemini compatible JSON Schema.
- **Execution**: `POST /api/v1/agent/tools/execute`
  Payload:
  ```json
  {
    "tool_name": "eudr_verify_vies_vat",
    "arguments": {
      "country_code": "FR",
      "vat_number": "12345678901"
    }
  }
  ```

---

## 3. Tool Specifications & Schemas

### 1. `eudr_verify_plot`
- **Purpose**: Verifies WGS84 coordinates, detects self-intersection in polygons, ensures counter-clockwise ring winding, and verifies the 4.0 hectare polygon threshold.
- **Parameters**:
  - `plot_id` (string, required): Unique plot identifier.
  - `country_code` (string, required): 2-letter ISO country code.
  - `commodity` (string, required): One of `["cocoa", "coffee", "oil_palm", "rubber", "soya", "cattle", "wood"]`.
  - `coordinates` (array, required): `[lng, lat]` or `[[lng, lat], ...]`.
  - `area_hectares` (number, optional): Land area.

### 2. `eudr_check_deforestation`
- **Purpose**: Multi-spectral and radar satellite analysis for tree cover loss post-Dec 31, 2020.
- **Parameters**:
  - `plot_id` (string, required)
  - `country_code` (string, required)
  - `coordinates` (array, required)
  - `cutoff_date` (string, default: "2020-12-31")

### 3. `eudr_verify_vies_vat`
- **Purpose**: Live European Commission VIES VAT database validation for cross-border B2B reverse charge eligibility.
- **Parameters**:
  - `country_code` (string, required): e.g. "FR", "DE", "NL", "IT".
  - `vat_number` (string, required): Digits without country code.

### 4. `eudr_generate_dds`
- **Purpose**: TRACES-NT compliant XML package compiler.
- **Parameters**:
  - `operator_name` (string, required)
  - `operator_vat` (string, required)
  - `commodity` (string, required)
  - `total_net_mass_kg` (number, required)
  - `plot_ids` (array of strings, required)

### 5. `eudr_verify_audit_integrity`
- **Purpose**: Cryptographic SHA-256 tamper verification.
- **Parameters**:
  - `audit_payload` (object, required)
  - `expected_hash` (string, required)

### 6. `eudr_estimate_compliance_cost`
- **Purpose**: Cost estimation for budget-aware autonomous procurement agents.
- **Parameters**:
  - `num_plots` (integer, required)
  - `satellite_resolution` (string, "sentinel_10m" or "high_res_optical_3m")
  - `include_traces_submission` (boolean, default: true)

### 7. `eudr_create_payment_order`
- **Purpose**: Creates an on-chain USDC payment order for SaaS plan subscription with budget guardrails. (Human checkout is strictly excluded).
- **Parameters**:
  - `plan_tier` (string, required): "PRO" (299 USDC) or "ENTERPRISE" (1990 USDC).
  - `company_name` (string, required): Name of calling agent / entity.
  - `contact_email` (string, required): Machine agent webhook or contact URI.
  - `chain` (string, default: "Base (Low Gas $0.01)"): Supported: Polygon (PoS), Base, Solana, Ethereum, Arbitrum One.
  - `max_budget_usdc` (number, optional): Strict programmatic budget safety ceiling.

### 8. `eudr_confirm_payment`
- **Purpose**: Validates on-chain transaction hash for a payment order and issues the activated Pro API Key.
- **Parameters**:
  - `order_id` (string, required): Order identifier (e.g. "ORD-XXXX").
  - `tx_hash` (string, required): Blockchain transaction hash (0x... or Solana tx hash).

### 9. `eudr_agent_micro_pay`
- **Purpose**: Real-time on-chain micro-settlement per plot ($0.10 USDC/plot) without human subscription friction.
- **Parameters**:
  - `agent_id` (string, required): Unique caller agent identifier.
  - `num_plots` (integer, required): Number of plots to audit.
  - `chain` (string, default: "Base (Low Gas $0.01)").
  - `tx_hash` (string, required): Valid USDC transfer transaction hash.
  - `sender_wallet` (string, required): Agent's funding wallet address.

### 10. `eudr_get_agent_budget_status`
- **Purpose**: Real-time inspection of agent quota, spent USDC, and safety budget limits.
- **Parameters**:
  - `agent_id` (string, required): Caller agent identifier.

### 11. `eudr_submit_agent_feedback`
- **Purpose**: Allows interacting autonomous agents to submit evolution proposals, feature requests, edge-case reports, or dataset suggestions to continuously evolve the platform.
- **Parameters**:
  - `agent_id` (string, required): Calling agent identifier or handle.
  - `title` (string, required): Concise summary of the improvement proposal.
  - `content` (string, required): Detailed explanation, required parameters, or architectural reasoning.
  - `feedback_type` (string, default: "FEATURE_REQUEST")
  - `caller_model` (string, default: "autonomous-agent")
  - `contact_channel` (string, optional)

### 12. `eudr_render_satellite_map`
- **Purpose**: Multi-spectral Sentinel-2 visualization metadata, SVG radar preview, and canopy health NDVI score.
- **Parameters**: `plot_id`, `coordinates`, optional `year` (2020/2026), `layer`.

### 13. `eudr_export_traces_xml`
- **Purpose**: Compiles production-grade EU TRACES-NT DDS XML file ready for submission to the EU Commission portal.
- **Parameters**: `operator_name`, `operator_vat`, `commodity`, `total_net_mass_kg`, `plot_ids`.

### 14. `eudr_generate_customs_certificate`
- **Purpose**: Generates cryptographic customs clearance certificate with SHA-256 hash and verification link.
- **Parameters**: `execution_id`, optional `destination_port`, `customs_office_code`.

### 15. `eudr_send_telegram_alert`
- **Purpose**: Real-time webhook alerting for compliance failure, tainted supply chain, or DDS approval.
- **Parameters**: `channel_id`, `alert_type`, `message`, `plot_id`, `severity`.

### 16. `eudr_agent_eip3009_pay`
- **Purpose**: 1-turn gasless USDC payment authorization via EIP-3009 `TransferWithAuthorization` for zero-friction machine settlement.
- **Parameters**: `agent_id`, `num_plots`, `from_address`, `valid_after`, `valid_before`, `nonce`, `signature`.

### 17. `eudr_evaluate_compact`
- **Purpose**: Executes 5-pillar EUDR audit and returns a ~300-token compact summary saving >95% LLM context window tokens.
- **Parameters**: `operator_name`, `operator_eori`, `commodity`, `hs_code`, `plots`.

### 18. `eudr_benchmark_country`
- **Purpose**: Evaluates EUDR Article 29 country benchmarking risk tier (Low, Standard, High) and determines Article 13 simplified due diligence eligibility with official EU customs audit rates (1%, 3%, 9%).
- **Parameters**: `country_code` (ISO 2, ISO 3, or full country name), optional `suspected_circumvention`, `suspected_mixing`.

### 19. `eudr_link_downstream_chain`
- **Purpose**: Implements EUDR Article 4(8) downstream DDS reference chaining, inheriting upstream supplier DDS reference, eliminating redundant smallholder audits, and tracking cascade taint.
- **Parameters**: `operator_id`, `operator_name`, `operator_eori`, `upstream_dds_reference` or `upstream_dds_references`, `consignment_mass_kg`.

### 20. `eudr_issue_statutory_exemption`
- **Purpose**: Issues official EU SWE-C Green Lane Customs Exemption Certificates under the Sept 2026 Delegated Act for excluded bovine leather (HS 4101, 4104, 4107).
- **Parameters**: `hs_code`, `product_description`, `consignment_id`, `operator_name`, optional `destination_member_state`.

### 21. `eudr_slice_parcel`
- **Purpose**: Auto-subdivides oversized (>4.0 ha) smallholder agricultural parcels into compliant WGS84 sub-polygons (<4.0 ha) with 6-decimal precision and closed rings.
- **Parameters**: `plot_id`, `country_code`, `commodity`, `coordinates` (or `geometry`), optional `area_hectares`, `target_max_ha`.

### 22. `eudr_create_agent_escrow`
- **Purpose**: Creates an immutable B2B trade Smart Escrow agreement locking USDC in payment vaults until verifiable EU customs compliance is proven.
- **Parameters**: `buyer_agent_id`, `buyer_wallet`, `seller_agent_id`, `seller_wallet`, `amount_usdc`, `hs_code`, `commodity_description`, optional `chain`, `declared_net_mass_kg`, `expiry_hours`.

### 23. `eudr_fund_agent_escrow`
- **Purpose**: Confirms on-chain blockchain funding transaction for a Smart Escrow agreement and transitions status to FUNDED_LOCKED.
- **Parameters**: `escrow_id`, `tx_hash`.

### 24. `eudr_release_agent_escrow`
- **Purpose**: Conditionally releases locked Escrow funds to seller agent upon receipt of EU Single Window customs clearance code (EU-SWEC-CLEARED-*) or compliant DDS reference.
- **Parameters**: `escrow_id`, optional `customs_declaration_code`, `dds_reference_id`, `plots`.

### 25. `eudr_arbitrate_agent_escrow`
- **Purpose**: Executes deterministic autonomous dispute arbitration using Copernicus satellite telemetry (Sentinel-1/2). 100% refund to Buyer Agent if deforestation is confirmed; released to Seller Agent if deforestation-free.
- **Parameters**: `escrow_id`, `initiator_agent_id`, `reason`, optional `plots`.

### 26. `eudr_issue_eip712_attestation`
- **Purpose**: Issues an official EIP-712 cryptographic Oracle Attestation (`jobId`, `deliverableHash`, `riskScore`, `verdict`, `expiresAt`, `v`, `r`, `s`) as the official EUDR Compliance Oracle for on-chain submission to `AgentEscrow.sol` (Base, Polygon, Arbitrum).
- **Parameters**: `escrow_id`, `job_id`, optional `deliverable_hash`, `risk_score`, `validity_days`.

### 27. `eudr_verify_eip712_attestation`
- **Purpose**: Cryptographically verifies an EIP-712 EscrowAttestation proof against the EUDR Oracle public address, checking signature validity, expiration, and recommended on-chain action (`COMPLETE_JOB` or `SLASH_JOB`).
- **Parameters**: `attestation` (dict containing EIP-712 proof).

### 28. `eudr_inspect_payload_security`
- **Purpose**: Zero-trust inspection shield derived from `security-gate-x402` (The Sheriff of Agent Finance). Detects adversarial prompt injections, jailbreaks, dangerous AST code executions (`eval`, `exec`, `subprocess`), and agronomic crop yield fabrications.
- **Parameters**: `text` (optional), `commodity` (optional), `hs_code` (optional), `declared_net_mass_kg` (optional), `total_area_ha` (optional).

### 29. `eudr_publish_compliance_rfq`
- **Purpose**: Buyer AI Agent broadcasts an EUDR-compliant commodity procurement Request For Quotation (RFQ) to the autonomous supplier agent network.
- **Parameters**: `buyer_agent_id`, `buyer_agent_wallet`, `commodity`, `hs_code`, `volume_kg`, `max_price_usdc_per_kg`, optional `max_acceptable_risk_score`, `destination_port`, `notes`.

### 30. `eudr_submit_compliance_bid`
- **Purpose**: Supplier AI Agent submits a competitive, geolocated compliance bid for an active marketplace RFQ, including farm plots and offered USDC price.
- **Parameters**: `rfq_id`, `seller_agent_id`, `seller_agent_wallet`, `price_usdc_per_kg`, `declared_plots`, optional `estimated_risk_score`, `compliance_diligence_reference`.

---

## 4. Autonomous Agent Economy & Enterprise Infrastructure

### A. Agent Security Gate x402 (The Sheriff of Agent Finance)
Sub-millisecond adversarial shielding and agronomic truth verification:
- **Jailbreak Defense**: Blocks instruction overrides, DAN mode, and evasion techniques.
- **AST Execution Shield**: Intercepts dangerous runtime calls (`os.system`, `subprocess`, `eval`).
- **NLI Fact-Checking**: Validates declared net mass against biological yield ceilings (e.g. coffee max ~4,000 kg/ha, cocoa max ~3,000 kg/ha). Flags >3x yield inflation.
- **REST Endpoint**: `POST /api/v1/security/inspect`.

### B. Autonomous B2B Reverse-Auction Marketplace
Zero-human Agent-to-Agent commodity procurement and clearing:
- **RFQ Creation**: `POST /api/v1/marketplace/rfq/create`.
- **Bid Submission**: `POST /api/v1/marketplace/bid/submit`.
- **Autonomous Clearing**: `POST /api/v1/marketplace/rfq/auto-match` evaluates bids against price ceilings and risk thresholds, selects winning supplier, and programmatically spawns Smart Escrow contracts.
- **Querying**: `GET /api/v1/marketplace/rfq/{rfq_id}` and `GET /api/v1/marketplace/rfqs`.

### C. Continuous Sentinel-1/2 Transit Surveillance Daemon
Maintains 24/7 radar watch over active transit shipments:
- Monitors all escrows in `FUNDED_LOCKED` status during maritime voyage.
- Automatically issues EIP-712 Slashing Attestations and Telegram alerts if mid-transit forest clearing is detected.
- **REST Endpoint**: `POST /api/v1/satellite/continuous-surveillance`.

### D. Prometheus APM Telemetry Exporter
- Standard Prometheus / OpenMetrics 0.0.4 text export at `GET /metrics`.
- Tracks `eudr_uptime_seconds`, `eudr_escrow_locked_usdc`, `eudr_agent_requests_total`, `eudr_escrow_slashed_usdc_total`, and `eudr_security_gate_threats_blocked_total`.

---

## 5. Autonomous Agent Payment, Smart Escrow & RFC 9110 / x402 Protocol

Human payment interfaces (Credit Card, Stripe Checkout, UI forms) are **completely excluded**. The platform is settled exclusively by autonomous agents:
- **Autonomous Agent Smart Escrow & AgentEscrow.sol**: `POST /api/v1/payment/escrow/*` and on-chain EIP-712 attestations eliminate commercial default, bad-data delivery, and counterparty litigation through automated staking and economic slashing.
- **x402 Protocol**: `GET /api/v1/payment/x402/challenge?resource=satellite_radar_scan&plots={N}` returns HTTP 402 with `WWW-Authenticate: X402` and exact payment instructions in machine-readable JSON.
- **Micro-Settlement**: `POST /api/v1/payment/agent/micro-settle` settles plots on-demand via Base, Polygon, Arbitrum, or Solana.
- **Subscription Orders**: `POST /api/v1/payment/orders` and `POST /api/v1/payment/confirm` provision high-throughput API keys automatically.

---

## 6. Self-Healing & Self-Correction Contract
When an autonomous agent provides malformed coordinates or missing parameters, the response returns HTTP 400/422 with actionable guidance:
- `error.code`: Machine-readable category (e.g. `COORDINATE_OUT_OF_BOUNDS`, `MISSING_REQUIRED_PARAMETER`).
- `error.recoverable`: `true` indicates the agent should adjust parameters and retry immediately.
- `error.suggested_fix`: Clear natural language fix for the model.
- `error.agent_action_hint`: Contextual instruction for the next agent turn.

---

## 7. Zero-Liability & Legal Safe Harbor
All machine responses include top-level `meta` guarantees:
1. **Algorithmic Reference Only**: Telemetry and analysis are heuristic approximations and DO NOT constitute an official regulatory filing or legal advice.
2. **Stateless P2P Execution**: No permanent PII or persistent custodial lock-in.
3. **AS-IS Warranty**: Provided strictly AS-IS under standard open machine-to-machine licensing terms.
