--- name: treg-integration description: Integrate treg into your own product — give your users 4,300+ external API tools without owning the keys, and bill each of your customers for what they used. Covers MCP, CLI and HTTP, per-customer attribution, spend limits, and invoicing. --- # Integrating treg into your product You are a coding agent. A human has pointed you at this file because they want **treg** inside their product. Read this whole file before writing code — the billing section changes how you write the plumbing, so writing the plumbing first means rewriting it. **What treg is:** one base URL and one token that reach 4,300+ external API endpoints (SEO, SERP, backlinks, social, enrichment, ads, scraping) across 140+ providers, plus whatever the team registered themselves. treg holds the provider credentials and injects them server-side; your caller makes the real upstream request and gets the provider's real response back. Calls served on treg's own key are metered per call from a prepaid balance at cost — **0% markup**. **What this file is for:** the case where *your product* is the customer of treg, and *your users* are customers of you. You pay treg; you bill them. --- ## 1. Pick an integration method Three doors, same token, same behaviour. Pick by where your code already lives. | Method | Use when | Shape | |---|---|---| | **HTTP** `POST https://treg.growwithfootprint.com/call/` | your backend already makes HTTP calls — **the default for a product** | you build the request, treg injects the credential and relays | | **MCP** `https://treg.growwithfootprint.com/mcp/` | your agent runtime speaks MCP and you want tool discovery for free | `catalog_search` → `catalog_get` → `call` | | **CLI** `treg` | scripts, CI, a devbox — not usually a product integration | thin client over the same API | ### HTTP — the one you probably want ```bash curl --get "https://treg.growwithfootprint.com/call/scrapecreators.x.v1-facebook-group" \ --data-urlencode "url=https://www.facebook.com/groups/366190054572553/about" \ -H "X-Treg-Token: $TREG_TOKEN" \ -H "X-Treg-Meta: customer=cust_8123" ``` Find endpoint ids and prices first — no auth needed: ``` GET https://treg.growwithfootprint.com/catalog/search?q=facebook+group # what exists, and what each costs GET https://treg.growwithfootprint.com/catalog/endpoints/ # params, method, example ``` Two response headers matter on every call: - **`X-Treg-Cost-Micro`** — what this call cost, in integer micro-USD (1e-6 USD). Present only on a metered call; absent means it ran on the team's own key and was not billed. An idempotent replay reports `0` and puts the first call's charge in `X-Treg-Original-Cost-Micro`. On a call that starts a slow job it is the amount treg reserved, and the final charge can be higher or lower: when the job is done, read `charged_micro` from `GET https://treg.growwithfootprint.com/calls/`. - **`X-Treg-Call-Id`** — a stable id for this call. **Store it on your side.** It is how you join treg's records to yours later, and it resolves via `GET https://treg.growwithfootprint.com/calls/`. `GET https://treg.growwithfootprint.com/calls//result` returns the stored response of a successful catalog call, so an answer your code threw away after paying for it can be recovered. Neither lives in the provider's body, which treg relays unchanged — including its errors. A 4xx/5xx from the provider costs nothing. One request header matters when you resell with a budget: - **`X-Treg-Route-Max-Cost: `** — a ceiling for this one call. If the reserve would exceed it treg answers **402** `error: route_max_cost` with `max_cost_micro` and `estimated_cost_micro`, and nothing is charged. Where the provider accepts a ceiling parameter, treg forwards the remaining ceiling upstream so settlement cannot exceed it; a refusal from that parameter is a non-2xx and costs nothing. For every other provider the header is a pre-reservation guard. The reservation is the price at the requested size rounded up to the provider's billing block (one billed per 25 results holds a whole block for 5 rows), plus treg's margin, so catalog price × limit can fall short; when a provider's hold does not fit, `_treg.tried` names the hold and the ceiling left. Direct calls have no default ceiling; only the header caps them. The catalog's `~$/call` figure is an estimate at the default page size: a `per_result` price with `unit: row` scales with your `limit`; with `unit: target` / `domain` / `keyword` it scales with how many of those the request names (one target is one unit). `X-Treg-Cost-Micro` is the settled truth. ### MCP Point your client at `https://treg.growwithfootprint.com/mcp/` with `Authorization: Bearer `. Tools: `catalog_search`, `catalog_get`, `call`, `balance`, `my_tools`. The `call` result carries `cost_usd`. ### Auth, and the one trap Tokens come in two kinds and the difference will cost you an afternoon: - **Org-scoped** (`treg org agent-new `) — belongs to one team, needs no `X-Treg-Org`: send it as `X-Treg-Token` (REST) or `Authorization: Bearer` (MCP). **Use this in a product.** - **Identity** (`treg login`) — belongs to a *person*, who may be in several teams. Recent versions pin it to the active team so it also works without `X-Treg-Org`; an older or unpinned one answers `400 choose an org (send X-Treg-Org)`. If you see that, either send `X-Treg-Org: ` or mint an org-scoped token instead. --- ## 2. Tag every call with your customer — this is the whole billing model **Send `X-Treg-Meta` from your backend on every call.** Up to 5 `key=value` pairs: ``` X-Treg-Meta: customer=cust_8123, workspace=ws_9, feature=lead-enrichment ``` Values may contain letters, digits and `. _ - :` only, ≤128 chars, and must not look like an email — these become storage keys in an append-only ledger, so treg refuses anything it cannot safely keep. A malformed bag is a `422` **before** anything is relayed, so it costs nothing. ### Set it in your code, never in a prompt Do **not** expose the tag as an argument your LLM fills in. A model will omit it somewhere in a long chain, and a number you cannot reconcile is worse than no number. Your backend already knows which user a request belongs to and already sets the `X-Treg-Token` header — set the tag at that same call site: ```ts // the ONE place your product talks to treg async function tregCall(path: string, ctx: { customerId: string; workspaceId?: string }) { const tags = [`customer=${ctx.customerId}`]; if (ctx.workspaceId) tags.push(`workspace=${ctx.workspaceId}`); const r = await fetch(`${TREG_BASE}/call/${path}`, { headers: { "X-Treg-Token": process.env.TREG_TOKEN!, "X-Treg-Meta": tags.join(", "), }, }); // Record what it cost against YOUR customer, keyed by the id treg returns. await db.usage.insert({ customerId: ctx.customerId, tregCallId: r.headers.get("X-Treg-Call-Id"), costMicro: Number(r.headers.get("X-Treg-Cost-Micro") ?? 0), }); return r; } ``` Route every treg call through one function like this. If two call sites can disagree about who gets tagged, eventually they will. --- ## 3. Limit what a customer can spend `PUT https://treg.growwithfootprint.com/orgs//budgets//` — admin token required. ```bash # cap one customer at $5/day curl -X PUT "https://treg.growwithfootprint.com/orgs/1/budgets/customer/cust_8123" \ -H "X-Treg-Token: $TREG_TOKEN" -H 'content-type: application/json' \ -d '{"daily_cap_micro": 5000000}' # a DEFAULT for every customer without an override (omit the value) curl -X PUT "https://treg.growwithfootprint.com/orgs/1/budgets/customer" ... -d '{"daily_cap_micro": 1000000}' # cut someone off; their caps survive the block curl -X PUT "https://treg.growwithfootprint.com/orgs/1/budgets/customer/cust_8123" ... -d '{"status":"blocked"}' ``` Unlimited until you set something. Setting the first limit on a key also **declares** it as a budget dimension — up to 3, because each one is checked on every call. **Limits stack.** A `workspace` ceiling and a `customer` ceiling both apply to a call carrying both, and the refusal names which one hit. ### The refusals your users may see These carry nothing about your treg account — no balance, no top-up link — so they are safe to surface: ```json 403 {"error":"tag_blocked","dim":"customer","val":"cust_8123","message":"…"} 429 {"error":"tag_spend_cap_reached","dim":"customer","val":"cust_8123", "spent_micro":5000000,"cap_micro":5000000,"period":"day","message":"…"} ``` **Never proxy a treg error body to your end user blindly.** The team-level ones (`402 insufficient_balance`, `429 platform_daily_cap_reached`, `403 funds_required`) contain *your* balance or a top-up URL. Handle those yourself. > **Per-customer caps are advisory, not exact.** They are checked against an aggregate, so concurrent > calls can overshoot by roughly one call's estimate per in-flight request. Your prepaid balance is > the hard limit. Do not sell these to your users as a precise cap. --- ## 4. Invoice your customers ``` GET https://treg.growwithfootprint.com/orgs//usage/by-tag?key=customer&days=30 ``` ```json {"key":"customer","days":30, "rows":[{"value":"cust_8123","charged_micro":41234,"charged_usd":0.041234,"calls":22}], "attributed_micro":41234, "unattributed_micro":1880, "total_micro":43114} ``` - **Money comes from the ledger**, not from the call log. Audit rows are fire-and-forget and are shed under load — exactly the traffic a growing product generates — so anything you bill from must come from here. `GET /calls` is for debugging, never for invoices. - **`attributed + unattributed == total`**, for every key. If it doesn't, stop and investigate rather than shipping the invoice. - **`unattributed_micro` is spend you could not attribute** — calls that carried no value for that key. Reconcile it to zero; anything left is a call site that forgot to tag. A call is credited **in full** to each of its tags, so grouping by `customer` and by `workspace` each reconcile to the same total on their own. Never add two groupings together. --- ## 5. Isolation, when a tag isn't enough A tag is a label your backend asserts — fine when the only budgets and reports it touches are yours. If a credential will run on *your customer's own machine*, mint a token pinned to them instead: ```bash treg org agent-new cust-8123-bot --pin customer=cust_8123 ``` That token can only ever bill `cust_8123`; naming another customer is a `403`. **Tag for counting, token for control.** Start everyone on tags and upgrade the few who need real separation. A pinned key cannot use Managed Auth (section 6): treg refuses it there. --- ## 6. Managed Auth A team can let its **end users** connect their own accounts, such as Google Search Console, through treg's apps, and then call tools as one of them. treg must turn this on for the team first, and chooses which providers it covers. **Connect.** The team's server asks for a one-time link and sends the end user to its `consent_url`: ```bash curl -X POST "https://treg.growwithfootprint.com/end-users/cust_8123/connect" \ -H "X-Treg-Token: $TREG_TOKEN" -H 'content-type: application/json' \ -d '{"provider": "google-search-console"}' ``` The link asks only to read, where the provider has that level. Send `"capability": "post"` (or `write`, `manage`) to ask for more. `GET /end-users/cust_8123` shows the levels granted (`capabilities`) and the chosen account's id (`account_id`). On Facebook, `me` as the `page_id` also names the chosen Page. Facebook asks for `business_management` at every level: treg needs it to find Pages that belong to a business or an agency. **Call.** `X-Treg-End-User` runs the call on that end user's account, never on the team's: ```bash curl "https://treg.growwithfootprint.com/call/google-search-console.sites" \ -H "X-Treg-Token: $TREG_TOKEN" \ -H "X-Treg-End-User: cust_8123" \ -H "X-Treg-Meta: customer=cust_8123" ``` - **Call from the team's server, with an unpinned key.** Pinned keys are refused, and an unpinned key reaches every end user, so it must never leave the server. - **Search and data tools work as usual**, on the team's own key first. Tools that work on the team's own account, such as Slack, are refused for an end user (`end_user_own_account`, `403`). - **Start and read a job as the same end user.** One end user cannot read a job that another one, or the team, started (`async_resource_not_owned`, `404`). - **Keep sending `X-Treg-Meta`.** `X-Treg-End-User` chooses the account; it does not tag the call. Without the tag, spend is unattributed and the tag limits of section 3 do not apply. **Limit.** A team admin sets what each end user may use per day (UTC) in Team > Managed Auth, or over the API: calls, and dollars from the team's balance (calls on treg's keys, and X calls on the end user's own account, which X charges for). Both are unlimited until set. One end user can have their own limits; `null` follows the team's, `-1` is no limit: ```bash curl -X PATCH "https://treg.growwithfootprint.com/orgs/1/settings" ... \ -d '{"end_user_calls_per_day": 500, "end_user_daily_cap_micro": 2000000}' curl -X PUT "https://treg.growwithfootprint.com/end-users/cust_8123/limits" ... -d '{"calls_per_day": 5000, "daily_cap_micro": -1}' ``` Past a limit the call is refused with `429` (`end_user_call_cap_reached`, `end_user_spend_cap_reached`) and `Retry-After`, the seconds until midnight UTC. treg reserves the most a call can cost before it runs, so the dollar limit can refuse a call a little before the limit is used up. The same settings hold `end_user_providers`, the platforms end users may connect, and `connect_return_hosts`, the domains a connect link may send them back to. --- ## 7. Before you ship - [ ] One function wraps every treg call, and it sets `X-Treg-Meta` from request context. - [ ] `X-Treg-Call-Id` is stored on your usage rows. - [ ] Your invoice reads `usage/by-tag`, and you assert `attributed + unattributed == total`. - [ ] `unattributed_micro` is zero — or you know which call site isn't tagging. - [ ] Team-level `402`/`429` bodies are handled by you, never forwarded to a user. - [ ] Auto top-up is on, or you monitor `GET /orgs//balance` — a flat balance fails every call. - [ ] Retries send `Idempotency-Key`; a replay returns the stored answer and charges nothing. **A provider's own error is relayed to you verbatim**, so a `4xx`/`5xx` may be theirs, not treg's. treg stamps **`X-Treg-Error: 1`** on its own refusals — branch on that header, not on the status code. `X-Treg-Error-Code` names the refusal in one word (`target_not_found`, `end_user_not_connected`). Failed upstream calls are not billed; a `per_call`-priced endpoint does bill a genuine `4xx` caused by your own bad input, but never one caused by a credential or quota problem.