# TeX402 — Complete LLM & Autonomous Agent Integration Guide > Hardened x402-monetized LaTeX compilation ($0.008 USDC) and <300ms linting ($0.002 USDC) API on Base This self-contained document provides everything an LLM coding agent, MCP host, or TypeScript/HTTP client needs to integrate with **TeX402** without external documentation lookups. --- ## 1. Service Configuration & x402 v2 Payment Protocol | Parameter | Value | | --- | --- | | Base URL | `https://tex.x.gl` | | Environment Mode | `mainnet` (Base Mainnet) | | CAIP-2 Network | `eip155:8453` | | Payment Scheme | `exact` (EIP-3009 `TransferWithAuthorization`) | | Payment Asset | USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`, 6 decimals) | | Seller `payTo` | `0x5e18Dfb04F64e1D0d3593178a004A251506c2e16` | | Facilitator URL | `https://api.cdp.coinbase.com/platform/v2/x402` | | `POST /v1/compile` Price | **$0.008 USDC** (`8000` atomic units) | | `POST /v1/lint` Price | **$0.002 USDC** (`2000` atomic units) | | Discovery & Health Endpoints | **Free** (`$0.00`) | ### How x402 v2 Gasless Settlement Works 1. **Unpaid Probe (`HTTP 402`)**: Sending `POST /v1/compile` or `POST /v1/lint` without a `PAYMENT-SIGNATURE` header returns `HTTP 402 Payment Required` with a base64-encoded JSON `PAYMENT-REQUIRED` header containing `x402Version: 2`, `accepts` (`scheme: "exact"`, `network`, `amount`, `asset`, `payTo`), and `@x402/extensions/bazaar` schemas. 2. **Off-Chain EIP-3009 Signature (`0 ETH` Gas)**: The buyer signs an EIP-712 `TransferWithAuthorization` message authorizing USDC transfer to `payTo`. **The buyer wallet needs only USDC (`0 ETH` required)** — the facilitator submits the on-chain settlement transaction. 3. **Paid Retry (`HTTP 200`)**: Retrying the request with the base64-encoded `PAYMENT-SIGNATURE` header executes the sandboxed TeX job, settles payment, and returns `HTTP 200` with a base64-encoded JSON `PAYMENT-RESPONSE` header (`{ success: true, payer, transaction, network }`). ### Recommended Agent Iteration Pattern 1. Call **`POST /v1/lint` (`$0.002` USDC)** while drafting or fixing LaTeX errors until `valid: true` (`<300ms` turnaround, 75% cheaper than full compile). 2. Call **`POST /v1/compile` (`$0.008` USDC)** with `include_page_previews: true` (and `bibliography: true` if using `.bib` citations) to produce the final PDF and visually inspect 150-DPI PNG page renders. --- ## 2. Endpoint Reference & Exact JSON Schemas ### 2.1 `POST /v1/compile` ($0.008 USDC / `8000` atomic units) Compiles a root `main_tex` document plus optional multi-file `files` inside an ephemeral, networkless `tex402-worker:latest` TeX Live container. #### Request JSON Schema (`Content-Type: application/json`) ```json { "type": "object", "required": [ "main_tex" ], "additionalProperties": false, "properties": { "main_tex": { "type": "string", "minLength": 1, "description": "Root LaTeX document source code written to /work/main.tex (UTF-8)." }, "files": { "type": "object", "description": "Optional map of safe relative paths (e.g. 'refs.bib', 'styles/custom.sty', 'sections/intro.tex', 'images/fig1.png') to UTF-8 strings or 'base64:' binary payloads.", "additionalProperties": { "type": "string" } }, "engine": { "type": "string", "enum": [ "pdflatex", "xelatex" ], "default": "pdflatex", "description": "TeX engine ('pdflatex' default; 'xelatex' for native UTF-8, fontspec, and CJK)." }, "bibliography": { "type": "boolean", "default": false, "description": "When true, automatically runs multi-pass 'biber' (if main.bcf exists from biblatex) or 'bibtex' (if \\citation/\\bibdata exists in main.aux) followed by LaTeX reruns." }, "include_page_previews": { "type": "boolean", "default": false, "description": "When true, renders every PDF page to a 150-DPI PNG via 'pdftoppm -png -r 150' and returns base64 strings in page_previews_base64." } } } ``` #### Response JSON Schema (`HTTP 200`) ```json { "type": "object", "required": [ "success", "pdf_base64", "page_count", "page_previews_base64", "compile_time_ms", "diagnostics" ], "properties": { "success": { "type": "boolean", "description": "true when the engine exited with code 0 and produced a non-empty PDF; false if LaTeX syntax/compilation errors occurred." }, "pdf_base64": { "type": [ "string", "null" ], "description": "Base64-encoded PDF binary (%PDF-1.x), or null when success is false." }, "page_count": { "type": "integer", "minimum": 0, "description": "Total PDF page count (0 on failure)." }, "page_previews_base64": { "type": "array", "items": { "type": "string" }, "description": "Ordered array (page 1..N) of raw base64-encoded 150-DPI PNG images when include_page_previews is true; [] otherwise." }, "compile_time_ms": { "type": "number", "minimum": 0, "description": "In-container execution duration in milliseconds." }, "diagnostics": { "type": "array", "items": { "type": "object", "required": [ "file", "line", "severity", "message", "context_snippet", "suggested_fix" ], "properties": { "file": { "type": "string", "description": "Relative file path (e.g. 'main.tex' or 'sections/intro.tex')." }, "line": { "type": [ "integer", "null" ], "description": "1-based line number, or null if file-wide." }, "severity": { "type": "string", "enum": [ "error", "warning", "info" ] }, "message": { "type": "string" }, "context_snippet": { "type": "string" }, "suggested_fix": { "type": "string" } } } }, "sandbox_metadata": { "type": "object", "required": [ "isolated", "timed_out", "files_in_workspace" ], "properties": { "isolated": { "type": "boolean" }, "timed_out": { "type": "boolean" }, "files_in_workspace": { "type": "array", "items": { "type": "string" } } } } } } ``` ### 2.2 `POST /v1/lint` ($0.002 USDC / `2000` atomic units) Runs `chktex` static style/syntax analysis concurrently with single-pass `pdflatex -draftmode` or `xelatex -draftmode` in `<300ms` without PDF rendering. #### Request JSON Schema (`Content-Type: application/json`) ```json { "type": "object", "required": [ "main_tex" ], "additionalProperties": false, "properties": { "main_tex": { "type": "string", "minLength": 1, "description": "Root LaTeX document source code to validate." }, "files": { "type": "object", "description": "Optional map of safe relative paths to UTF-8 text or 'base64:' binary contents.", "additionalProperties": { "type": "string" } }, "engine": { "type": "string", "enum": [ "pdflatex", "xelatex" ], "default": "pdflatex" } } } ``` #### Response JSON Schema (`HTTP 200`) ```json { "type": "object", "required": [ "success", "valid", "compile_time_ms", "diagnostics" ], "properties": { "success": { "type": "boolean", "description": "true when the lint runner completed without container timeout." }, "valid": { "type": "boolean", "description": "true when -draftmode exited with code 0 and zero error-severity diagnostics were emitted." }, "compile_time_ms": { "type": "number", "minimum": 0, "description": "Concurrent chktex + -draftmode duration in milliseconds (<300ms typical)." }, "diagnostics": { "type": "array", "description": "Deduplicated TeX engine errors/warnings plus '[ChkTeX #N]' static warnings with 1-based line numbers and suggested_fix.", "items": { "type": "object", "required": [ "file", "line", "severity", "message", "context_snippet", "suggested_fix" ], "properties": { "file": { "type": "string" }, "line": { "type": [ "integer", "null" ] }, "severity": { "type": "string", "enum": [ "error", "warning", "info" ] }, "message": { "type": "string" }, "context_snippet": { "type": "string" }, "suggested_fix": { "type": "string" } } } } } } ``` --- ## 3. Multi-File Projects, Engines, Bibliography & Previews ### 3.1 Multi-File `files` Map & `base64:` Binary Encoding - **Text files** (`.tex`, `.bib`, `.sty`, `.cls`, `.bst`, `.csv`, `.tikz`): Pass raw UTF-8 text strings. - **Binary files** (`.png`, `.jpg`, `.pdf` figures): Prefix the base64 payload with **`base64:`** (do **not** use `data:image/png;base64,...` data URLs). - Example: `"images/logo.png": "base64:iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="` - **Strict Path Validation**: Keys in `files` must be safe relative paths (e.g. `sections/intro.tex`, `styles/custom.sty`, `refs.bib`). Absolute paths (`/etc/passwd`), parent traversal (`../`), leading-dot hidden files (`.env`, `sub/.hidden`), NUL bytes, and overriding `main.tex` are rejected pre-settlement with `HTTP 400`. - **`TEXINPUTS`**: Set to `.:./styles:./include:` inside `/work`, so packages in `styles/` can be loaded via `\usepackage{styles/custom}` or `\usepackage{custom}`. ### 3.2 Engines (`pdflatex` vs `xelatex`) - **`pdflatex`** (default): Fastest engine (~200–450ms); preloaded with `amsmath`, `mathtools`, `siunitx`, `tikz`, `pgfplots`, `circuitikz`, `mhchem`, `algorithm2e`, `listings`, `forest`, `beamer`, `booktabs`, `longtable`, `hyperref`, `biblatex`. - **`xelatex`**: Native UTF-8 Unicode, OpenType (`\usepackage{fontspec}`), and CJK (`\usepackage{xeCJK}`). Pre-installed container fonts include `Liberation Serif`, `Liberation Sans`, `Liberation Mono`, `Noto Serif CJK SC`, and `Noto Sans CJK SC`. - **`luatex` / `lualatex`**: Intentionally disabled (`chmod 000`) to eliminate embedded Lua sandbox escape vectors. ### 3.3 Bibliography (`bibliography: true` — Biber & BibTeX) - Set `"bibliography": true` on `POST /v1/compile` whenever your document uses citations (`refs.bib` in `files`). - **BibLaTeX + Biber**: When `\usepackage[backend=biber]{biblatex}` + `\addbibresource{refs.bib}` generates `main.bcf`, TeX402 automatically runs `engine -> biber main -> engine -> engine`. - **Classic BibTeX**: When `\bibliographystyle{...}` + `\bibliography{refs}` writes `\citation`/`\bibdata` to `main.aux`, TeX402 automatically runs `engine -> bibtex main -> engine -> engine`. - **Automatic Reruns**: Even when `bibliography` is `false`, TeX402 automatically detects `.toc`, `.nav` (Beamer overlays), `longtable` column width changes, and `Rerun to get cross-references right` log notices and executes the needed extra passes. ### 3.4 150-DPI PNG Page Previews (`include_page_previews: true`) - When `"include_page_previews": true`, TeX402 runs `pdftoppm -png -r 150 main.pdf page_preview` inside the container and returns an ordered array of raw base64 PNG strings in `page_previews_base64` (`page_previews_base64[0]` is Page 1). - Ideal for multimodal agents checking equation overflow, table alignment, TikZ diagrams, and Beamer slide layouts. --- ## 4. Pre-Settlement HTTP Status Codes & Buyer Protection TeX402 runs input validation, rate limiting, and bounded worker queue checks **ahead of** `x402Middleware`. Malformed, throttled, or overflow requests are **never settled or charged**. | HTTP Status | Paid? | Meaning & Agent Action | | --- | --- | --- | | `200 OK` | Settled (`PAYMENT-RESPONSE` header) | Container job executed. Check `data.success` (`/v1/compile`) or `data.valid` (`/v1/lint`) and inspect `data.diagnostics` if `false`. | | `400 Bad Request` | **$0.00 (Pre-settlement)** | Malformed JSON, missing/empty `main_tex`, invalid `engine`, or unsafe path in `files`. Fix payload before retrying. | | `402 Payment Required` | **$0.00 (Challenge)** | Missing or invalid `PAYMENT-SIGNATURE` header. Decode base64 `PAYMENT-REQUIRED` header and sign EIP-3009 USDC authorization via `@x402/fetch`. | | `429 Too Many Requests` | **$0.00 (Pre-settlement)** | Per-IP rate limit exceeded (default `30` req/min). Respect the `Retry-After` response header (`retry_after_seconds` in JSON body). | | `503 Service Unavailable` | **$0.00 (Pre-settlement)** | Bounded Docker worker queue is temporarily full (`error: "queue_saturated"`). Respect `Retry-After: 5` header and retry with backoff. | | `500 Internal Server Error` | Unexpected error | Inspect `diagnostics[0].message` and retry if transient. | --- ## 5. Complete `@x402/fetch` TypeScript Client Example Install dependencies: ```bash npm install @x402/fetch @x402/evm viem ``` Copy-pasteable Node.js / TypeScript ESM script (`compile-paper.ts`): ```typescript import fs from "node:fs"; import { wrapFetchWithPayment, x402Client, decodePaymentResponseHeader } from "@x402/fetch"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; import { toClientEvmSigner } from "@x402/evm"; import { createPublicClient, http } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { base } from "viem/chains"; const BASE_URL = process.env.TEX402_BASE_URL ?? "https://tex.x.gl"; const PRIVATE_KEY = process.env.TEX402_PRIVATE_KEY as `0x${string}`; // Needs Base USDC only (0 ETH gas) const account = privateKeyToAccount(PRIVATE_KEY); const publicClient = createPublicClient({ chain: base, transport: http() }); const client = new x402Client(); registerExactEvmScheme(client, { signer: toClientEvmSigner(account, publicClient) }); const fetchWithPay = wrapFetchWithPayment(fetch, client); const mainTex = [ "\\documentclass[11pt]{article}", "\\usepackage{amsmath}", "\\usepackage[backend=biber,style=numeric]{biblatex}", "\\addbibresource{refs.bib}", "\\begin{document}", "\\section{Autonomous Paper Generation}", "Gaussian integral citing Knuth~\\cite{knuth1984}:", "\\[ \\int_{-\\infty}^{\\infty} e^{-x^2}\\,dx = \\sqrt{\\pi} \\]", "\\printbibliography", "\\end{document}" ].join("\n"); const files = { "refs.bib": "@article{knuth1984, author={Donald E. Knuth}, title={Literate Programming}, journaltitle={The Computer Journal}, year={1984}}" }; // Step 1: Fast <300ms lint ($0.002 USDC) const lintRes = await fetchWithPay(`${BASE_URL}/v1/lint`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engine: "pdflatex", main_tex: mainTex, files }) }); const lintData = await lintRes.json(); if (!lintData.valid) { console.error("Lint diagnostics:", lintData.diagnostics); process.exit(1); } // Step 2: Full PDF compilation + 150-DPI PNG preview ($0.008 USDC) const compileRes = await fetchWithPay(`${BASE_URL}/v1/compile`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engine: "pdflatex", bibliography: true, include_page_previews: true, main_tex: mainTex, files }) }); const paymentHeader = compileRes.headers.get("payment-response"); const receipt = paymentHeader ? decodePaymentResponseHeader(paymentHeader) : null; const compileData = await compileRes.json(); if (compileData.success && compileData.pdf_base64) { fs.writeFileSync("paper.pdf", Buffer.from(compileData.pdf_base64, "base64")); compileData.page_previews_base64.forEach((pngB64: string, idx: number) => { fs.writeFileSync(`page-${idx + 1}.png`, Buffer.from(pngB64, "base64")); }); console.log(`Saved paper.pdf (${compileData.page_count} pages, ${compileData.compile_time_ms}ms) — tx: ${receipt?.transaction}`); } else { console.error("Compilation failed:", compileData.diagnostics); } ``` --- ## 6. Model Context Protocol (`npx -y tex402-mcp`) Integration `tex402-mcp` (`v1.0.0` on npm) connects Claude Desktop, Claude Code, Cursor, Windsurf, OpenAI Codex, and Antigravity directly to TeX402 over stdio. ### 6.1 MCP Host Configuration (`claude_desktop_config.json` / `.cursor/mcp.json`) ```json { "mcpServers": { "tex402": { "command": "npx", "args": [ "-y", "tex402-mcp" ], "env": { "TEX402_PRIVATE_KEY": "0xYOUR_BASE_EVM_PRIVATE_KEY", "TEX402_BASE_URL": "https://tex.x.gl" } } } } ``` ### 6.2 Environment Variables - `TEX402_PRIVATE_KEY`: `0x`-prefixed 32-byte EVM private key funded with USDC on Base Mainnet (`eip155:8453`). Required for paid `tex402_lint` and `tex402_compile` calls; optional for `tex402_status`. - `TEX402_BASE_URL`: Optional server URL override (defaults to `https://tex.x.gl`; active server: `https://tex.x.gl`). ### 6.3 MCP Tools Provided by `tex402-mcp` 1. **`tex402_status`** (Free / `$0.00` USDC): - Queries `GET /health` and reports server readiness (`tex_worker_ready`), active x402 `mode`/`network`/`pay_to`, worker queue stats, and the local wallet's derived `buyer_address`. 2. **`tex402_lint`** (`$0.002` USDC): - Inputs: `{ main_tex: string, files?: Record, engine?: "pdflatex" | "xelatex" }`. - Runs `<300ms` concurrent `chktex` + `-draftmode` validation and returns `valid`, `compile_time_ms`, line-exact `diagnostics`, and the settled x402 `transaction` hash. 3. **`tex402_compile`** (`$0.008` USDC): - Inputs: `{ main_tex: string, output_pdf_path?: string, files?: Record, engine?: "pdflatex" | "xelatex", bibliography?: boolean, include_page_previews?: boolean }`. - Decodes `pdf_base64` directly to `output_pdf_path` on local disk (omitting raw PDF base64 from text output so the LLM context window stays clean!) and attaches 150-DPI PNG previews as native MCP `image/png` content blocks when `include_page_previews: true`. --- ## 7. Discovery Endpoints Summary - `GET https://tex.x.gl/` — Developer HTML landing page with JSON-LD `WebAPI` schema and RFC 8288 `Link` headers - `GET https://tex.x.gl/skill.md` — Installable Agent Skill file (`SKILL.md` with YAML frontmatter) for Claude Code, Cursor, Antigravity, Windsurf & AgentCash - `GET https://tex.x.gl/llms.txt` — Concise LLM index - `GET https://tex.x.gl/llms-full.txt` — Complete single-file LLM integration guide (this document) - `GET https://tex.x.gl/.well-known/x402` — x402 v2 service metadata & Bazaar discovery schemas - `GET https://tex.x.gl/.well-known/mcp.json` — MCP Server Card for `tex402-mcp` - `GET https://tex.x.gl/.well-known/api-catalog` — RFC 9727 / RFC 9264 `application/linkset+json` API catalog - `GET https://tex.x.gl/openapi.json` — OpenAPI 3.1.0 specification - `GET https://tex.x.gl/docs` — Interactive Swagger UI - `GET https://tex.x.gl/health` — Worker pool readiness & queue telemetry