<!-- Canonical: https://docs.smartepd.com/guides/agent-integration/ -->

# AI Agent Integration

This guide is for teams connecting an **AI agent** to Smart EPD — a coding agent (Claude Code, Cursor, Copilot Workspace), an internal assistant, or a custom LLM application that drafts and validates EPDs programmatically.

The Smart EPD v2 API is a good fit for agents: every EPD exposes its own field schema, validation is a separate read-only call you can loop on before submitting, and errors use one stable machine-readable envelope. This page tells you how to load the right context into your agent and which workflow to point it at.

:::tip TL;DR
1. Give your agent the [copy-paste context block](#ground-your-agent-copy-paste-context) below.
2. Point it at the sandbox (`https://sandbox.smartepd.xyz`) with an `sk_...` API key.
3. Have it follow the [draft → validate → submit loop](#the-draft--validate--submit-loop).
:::

## Machine-readable doc surfaces

Everything on this docs site is published in agent-friendly formats. Pick the surface that matches how much context your agent can hold:

| Surface | URL | Use it when |
|---|---|---|
| **Docs index** | [`/llms.txt`](https://docs.smartepd.com/llms.txt) | The front door. A curated map of every page with one-line descriptions, in [llms.txt](https://llmstxt.org/) format. Fetch this first and follow links on demand. |
| **Full corpus** | [`/llms-full.txt`](https://docs.smartepd.com/llms-full.txt) | Every hand-written docs page concatenated into one Markdown file. Load it whole into a large context window. (Generated endpoint-reference pages aren't included — the OpenAPI spec is their machine format.) |
| **Per-page Markdown** | append `.md` to any hand-written page's path | Every hand-written page has a raw-Markdown mirror — e.g. this page is served at [`/guides/agent-integration.md`](https://docs.smartepd.com/guides/agent-integration.md) — same content, none of the navigation chrome. Generated endpoint pages aren't mirrored; use the OpenAPI spec instead. |
| **OpenAPI spec** | [`/openapi/v2.json`](https://docs.smartepd.com/openapi/v2.json) | The source of truth for endpoints: paths, request/response schemas, and status codes for the public v2 API. Feed it to tool generators, OpenAPI-to-MCP bridges, or straight into context. |
| **Per-EPD field schema** | `GET /api/v2/epds/{epd_id}/schema/?view=summary` | Runtime discovery of the exact fields, types, and requirements a *specific* EPD must satisfy. Spec-dependent — always fetch it rather than assuming. See [EPD Schema (API)](/concepts/epd-schema). |

:::note Which to choose
For most integrations: `llms.txt` + the OpenAPI spec + the copy-paste block below. Reach for `llms-full.txt` only when the agent genuinely needs deep platform background (verification workflows, constraint design), since it is large.
:::

## Ground your agent (copy-paste context)

Drop this block into your agent's context — a `CLAUDE.md` / `AGENTS.md`, a Cursor rule, or a system prompt. It compresses the platform's non-negotiables into what an agent must know before its first request:

```markdown
# Smart EPD API — agent context

Smart EPD manages Environmental Product Declarations (EPDs): draft → validate →
verify → publish. Full docs index: https://docs.smartepd.com/llms.txt
OpenAPI spec: https://docs.smartepd.com/openapi/v2.json

## Connection
- Sandbox (develop here): https://sandbox.smartepd.xyz
- Production: https://app.smartepd.com
- Every request: `Authorization: Bearer $SMARTEPD_API_KEY` (keys start with `sk_`).
- API keys are scoped to ONE workspace. Resources in any other workspace
  return 404, not 403.

## Object model (top-down)
Organization → Workspace → Category (PCC; binds a PCR spec + LCA tool) →
Project → EPD (+ project-level LCA). Reference EPDs can spawn variant EPDs
that are auto-validated by constraints instead of manually reviewed.

## Golden rules
1. Discover fields before writing: GET /api/v2/epds/{id}/schema/?view=summary.
   Field IDs are hyphenated (`product-name`, `declared-unit`). Never invent
   field IDs — the schema endpoint is the source of truth per EPD.
2. PUT /api/v2/epds/{id}/document/ REPLACES the entire document. Always
   read-modify-write; never send a partial body.
3. Two validation gates, both required before submit — passing one does NOT
   imply the other: (a) SHAPE: after each PUT, read `constraint_violations`
   from GET /api/v2/epds/{id}/ (required fields/types; hard-rejected at
   submit as `shape_validation_error`); (b) REQUIREMENTS: loop the read-only
   POST /api/v2/epds/{id}/validate/ until `is_valid: true`. Then POST
   /api/v2/epds/{id}/submit/ (which also requires the lca_author_* fields).
4. Errors: non-2xx responses use {"error": {"code", "message", "details"?}}.
   Branch on `error.code`, never on message text. 404 means "missing OR not
   yours". Framework-level 422 (request-shape) and 401 (auth) responses skip
   the envelope — branch on HTTP status there.
5. List endpoints paginate by cursor: request `?limit=100&cursor=...`,
   response {"data", "next_cursor", "has_more"}. Loop until has_more=false.
6. Value formats: select fields take strings ("1 m3"), multiselects take
   string arrays (["a1","a2","a3"]), rich-text fields take HTML.
7. Write sequentially, not in parallel. On 429 or 5xx, retry with
   exponential backoff.
8. `force_status` / force-approve shortcuts exist for testing and are
   rejected in production with a 400.
```

Everything in the block is expanded elsewhere in these docs — [Errors](/api-reference/errors), [Pagination](/api-reference/pagination), [EPD Schema](/concepts/epd-schema), and the [API Quickstart](/guides/api-quickstart).

## Authentication for agents

Use an **API key**, not a JWT — keys are long-lived, while JWTs expire on a short cadence that mid-task agents handle badly. From [Authentication & Access](/getting-started/authentication):

- Keys are created in the web UI (account settings) and shown **once**.
- Each key is scoped to a single **workspace** and to `read_only` or `read_write`. Give a drafting agent `read_write`; give a reporting/query agent `read_only`.
- Develop against the **sandbox** first. The [verification-testing shortcuts](/guides/verification-testing) (`force_status`, `/force-approve/`) let an agent run the full lifecycle end-to-end without waiting on human verifiers — and are rejected in production, so promotion to prod fails safe.

:::caution Handle keys like secrets
Inject the key via environment variable (`SMARTEPD_API_KEY`) rather than pasting it into prompts or agent config files, and never let an agent echo it into logs, URLs, or code it writes.
:::

## The draft → validate → submit loop

This is the workflow to point an agent at. The full end-to-end setup (workspace → category → project) is covered in the [API Quickstart](/guides/api-quickstart); the loop below is the part an agent iterates on for every EPD.

```mermaid
flowchart TD
    A["GET /epds/{id}/schema/?view=summary<br/>discover fields + requirements"] --> B["Build document from source data<br/>(hyphenated field IDs)"]
    B --> C["PUT /epds/{id}/document/<br/>full replacement"]
    C --> D["Shape gate:<br/>constraint_violations on GET /epds/{id}/"]
    C --> E["Requirements gate:<br/>POST /epds/{id}/validate/ (read-only)"]
    D --> F{"Both gates clear?"}
    E --> F
    F -- "no — fix the document" --> B
    F -- yes --> G["POST /epds/{id}/submit/"]
    G --> H["Verification workflow<br/>(sandbox: force-approve)"]
```

**1. Discover the schema.** `GET /api/v2/epds/{epd_id}/schema/?view=summary` returns a flat `fields` list (`id`, `type`, `required`, `label`, options, constraints) plus the requirements the EPD will be checked against. Conditional fields carry rules describing when they apply — prune fields whose conditions aren't met rather than sending them as `null`.

**2. Write the document.** `PUT /api/v2/epds/{epd_id}/document/` with the complete `document` object. Saves are deliberately permissive — incomplete documents are accepted so drafts can be built up incrementally.

**3. Clear both validation gates.** Two independent checks stand between a draft and a successful submit, and **passing one says nothing about the other**:

- **Shape gate — required fields and types.** Every document save runs a soft shape check against the schema's field definitions. Violations don't block the save; they're stored and returned as `constraint_violations` on `GET /api/v2/epds/{epd_id}/`. Read that field after each save and fix what it reports — at submit time this same check turns hard.
- **Requirements gate — spec conformance.** `POST /api/v2/epds/{epd_id}/validate/` evaluates the document against the resolved spec's requirement checks **without changing any state**, so an agent can call it as often as it likes:

```json
{
  "is_valid": false,
  "no_image": false,
  "summary": {
    "compliant": 41,
    "non_compliant": 2,
    "ofi": 0,
    "na": 1,
    "errors": 0,
    "warnings": 1,
    "unevaluated": 0,
    "inconclusive": 0,
    "pending_verification": 3
  },
  "requirement_results": [ /* one entry per requirement, with verdicts */ ]
}
```

`is_valid` is true when there are no non-compliant requirements and no errored checks — **on this axis only; it does not check required fields**, which is why the shape gate must be cleared separately. Treat `requirement_results` as the fix list: repair the document, re-`PUT`, re-validate. `pending_verification` counts requirements that can only be satisfied by third-party verification — an agent cannot fix these and should not loop on them.

**4. Submit.** `POST /api/v2/epds/{epd_id}/submit/` enforces its own blockers, none of which `/validate/` covers: the LCA author attribution fields (`lca_author_name`, `lca_author_email`, `lca_author_company` — set them at create time), the hard version of the shape gate (error-severity violations reject with a `shape_validation_error` whose `details` list exactly what's wrong), and — for reference and variant EPDs — template constraints. An agent that cleared both gates in step 3 and set the author fields up front should submit cleanly.

**Variant EPDs** get the same treatment: `POST /api/v2/epds/{epd_id}/variants/{variant_id}/validate/` checks a variant against its reference template's constraints without changing state. See [Variant EPDs](/guides/variant-epds) and [Reference EPDs & Constraints](/guides/reference-epds-and-constraints).

## Guardrails

Beyond the golden rules in the context block:

- **The schema endpoint is per-EPD truth.** Field sets differ by PCR spec and template, and conditional rules add/remove required fields based on other answers (e.g. the renewable-electricity block). Re-fetch the schema when switching projects or specs instead of caching one field list globally.
- **Locked fields exist.** Reference EPDs can lock methodology fields; variants that try to change a locked field get a `400 validation_error` naming it. The correct agent response is to drop the change, not retry it.
- **Don't parse opaque values.** Cursors, IDs, and error messages are not contracts. `error.code`, field IDs, and documented response keys are.
- **Respect the 404 mask.** A 404 never proves an ID doesn't exist — the same status is returned for resources the key simply can't see. Don't have an agent "probe" IDs to map what exists.
- **Keep write concurrency at 1 per EPD.** `PUT /document/` is a full replacement, so two concurrent writers silently drop each other's fields.

## Using the OpenAPI spec with agent tooling

[`/openapi/v2.json`](https://docs.smartepd.com/openapi/v2.json) describes the full public API surface and regenerates with every docs deploy, so it tracks the live contract. Common ways to wire it in:

- **Direct context** — the spec is small enough to hand to a large-context model alongside `llms.txt`.
- **Typed clients** — generate a client with [OpenAPI Generator](https://openapi-generator.tech/) and give your agent the typed SDK instead of raw HTTP.
- **MCP / tool bridges** — generic OpenAPI-to-tool bridges (including OpenAPI-to-MCP servers) can expose each endpoint as a callable tool. Smart EPD doesn't ship a first-party MCP server today; the spec is designed so bring-your-own bridges work.

## Related pages

- [API Quickstart](/guides/api-quickstart) — the end-to-end curl walkthrough an agent's workflow mirrors
- [EPD Schema (API)](/concepts/epd-schema) — full decode of the schema endpoint both views
- [Errors](/api-reference/errors) — the error envelope and code table
- [Pagination](/api-reference/pagination) — the cursor model
- [Verification Testing Shortcuts](/guides/verification-testing) — sandbox-only force options for exercising the full lifecycle
