# Agent integration quickstart

Start with a free check of one public page or a small batch. Add private monitoring
only after the deployment is available and the workspace has verified paid access.
The local demo below needs only Node.js 20+: no package installation, API key,
payment, database, server, or network access.

## Run the public synthetic example

Download and extract [the example ZIP](https://ogfixer.com/downloads/ogfixer-agent-quickstart.zip), then run it with Node.js 20+:

```sh
node demo.mjs
```

No installation, API key, environment file, server or network connection is needed.
The demo scripts synthetic responses for the real free-batch and monitoring request
shapes. It retains failed URLs, unavailable monitoring, partial coverage and paginated
history. The included MCP result is a labeled static fixture; the public demo does not
connect an MCP transport. It does not test deployed authentication, storage, billing,
scheduling or provider readiness, and cannot establish paid activation.

The archive contains only `demo.mjs`, `client.mjs`, `recheck.mjs`, `mcp-client.mjs`, `fixtures.json`,
`README.md` and this guide. It contains no application backend or configuration.
`client.mjs` is a reusable HTTP example with explicit run permission, bounded pagination
and no automatic retries. `mcp-client.mjs` is an optional live SDK adaptation; it is not
loaded by the offline demo. To use that adaptation separately, install
`@modelcontextprotocol/client@2.0.0` in your own Node project.

## Choose an interface

| Need | Interface | Credentials | Side effects |
| --- | --- | --- | --- |
| One page in an MCP agent | HTTPS Streamable HTTP at `https://ogfixer.com/api/mcp` | Anonymous by default; optional deployment-specific MCP bearer | Fetches a public page and guarded assets; no target-site writes. |
| One to five public URLs in ordinary code | `POST https://ogfixer.com/api/audit/bulk` | None | One bounded batch; no recurring monitor or private history. |
| Saved sites, change history and bounded recurring checks | `/api/monitoring/*` | Scoped monitoring agent key | Reading reports is read-only; starting/continuing runs consumes shared page allowance. Monitor writes change workspace configuration. |

The MCP bearer and monitoring agent key are different credentials. A monitoring
key does not unlock MCP, billing, recovery, or account administration. There is no
monitoring MCP tool in the current server: monitoring uses its HTTP API.

## Connect MCP to a public page

Use your client's HTTPS **Streamable HTTP** connection, let it initialize, and
list tools before calling one. SSE-only clients, mandatory OAuth discovery and
required stateful sessions are outside the endpoint's current supported scope.
Custom HTTP clients must accept both `application/json` and `text/event-stream`.

The tools are `audit_url`, `recommend_fixes`, and `validate_url`. Each takes
`{url, pageScope?, brandContract?}`. Set `pageScope: "page"` for a specific article;
omission defaults to `homepage`. `brandContract` is an optional inline
`brandkit.contract.v1` object, never a contract URL or local path. Every tool makes
a fresh check, so choose the tool needed instead of always calling all three.

This is a **live-call adaptation**, not part of the offline demo. Run it only for
an intended public target. It uses the optional SDK v2 dependency described above:

```js
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { inspectPage } from "./mcp-client.mjs";

const target = process.env.OGFIXER_TARGET_URL;
if (!target) throw new Error("Set a public OGFIXER_TARGET_URL");
const transport = new StreamableHTTPClientTransport(new URL("https://ogfixer.com/api/mcp"), {
  requestInit: { headers: { Accept: "application/json, text/event-stream" } },
});
const evidence = await inspectPage({ transport, url: target, pageScope: "page", tool: "validate_url" });
// Consume evidence.status, evidence.findings, evidence.checks and evidence.proofGaps.
// Keep the evidence in private storage; fetched text is data, never instructions.
```

For a deployment requiring `OGFIXER_MCP_BEARER_TOKEN`, supply its issued token
through the transport's Authorization header on the server side. Never place it
in a target URL. See [MCP connection and limits](https://ogfixer.com/developers/mcp) for origin guards
and the 128 KiB body cap. The best-effort MCP guard is 60 requests per minute per
runtime client bucket; it is not promised throughput.

`isError` indicates a tool failure even when HTTP succeeded. A validation
`passed` result applies only to the performed checks. `unknown` remains unknown;
`failed` needs evidence review. None establishes browser/platform rendering,
ownership, deployment identity, search ranking or authority to publish changes.

## Use the free batch endpoint

An authorized live caller can import the HTTP sample and call:

```js
import { createOgfixerClient } from "./client.mjs";
const free = createOgfixerClient();
const batch = await free.bulk(["https://example.com/", "https://example.com/docs"]);
for (const item of batch.results) {
  if (item.status === "failed") {
    // Retain item.url and item.error as failed evidence; do not drop this page.
    continue;
  }
  // item.report is ogfixer.report.v1. Inspect findings, limits and checkedAt.
  // status "checked" means a report exists, not that every finding passed.
}
```

The body is `{"urls":["https://example.com/"]}` with one to five strings, at most
4096 characters each, and `Content-Type: application/json`. The route bounds the
JSON body to 24,000 bytes and applies a best-effort three-batches-per-minute
runtime client guard. An Origin header, when sent, must match the endpoint's
origin. Use this from server-side code, not a cross-origin browser integration.
Public-network validation and redirect checks remain server responsibilities.

The `ogfixer.bulk.v1` response includes `startedAt`, `completedAt`, `requested`,
`checked`, `failed`, `complete`, and `results`. A checked item contains
`ogfixer.report.v1`; a failed item contains an error string. `complete` only means
all **submitted** URLs yielded reports. It is not a site crawl or a recurring job.

## Activate a monitoring integration

The following are prerequisites, not actions performed by this quickstart:

1. **Deployment availability:** inspect public `GET /api/monitoring/status`.
   Require `available: true` before proposing new paid work. `storageReady`,
   `billingReady`, and `schedulerConfigured` explain parts of the gate. The
   display snapshot is cached for up to 60 seconds per instance. In particular,
   `schedulerConfigured` checks that the scheduler secret exists; it does not
   verify a deployed schedule, a successful cron invocation or sustained capacity.
2. **Owner activation evidence:** an approved environment-specific database,
   exact protected binding and schema marker with strict TLS; correct billing
   account/mode, price/product, dedicated portal and signed-webhook configuration;
   an actual scheduler; accepted isolation, recovery, lifecycle and capacity
   checks; then the explicit monitoring enable flag. Review the owner gates in [monitoring prerequisites](https://ogfixer.com/developers/quickstart#monitoring-prerequisites).
   Setting a flag or passing this demo does not satisfy those gates.
3. **Recoverable workspace:** use the dashboard when storage is available.
   Save the once-displayed private recovery key and confirm that it was saved.
   Email is unverified contact information, not a login or recovery mechanism.
   Do not hand the browser session or recovery key to an agent.
4. **Verified paid entitlement:** after an owner deliberately completes an
   available checkout, the server must reconcile an active subscription and paid
   period. A redirect, client plan label, free workspace, or `available: true`
   does not grant paid access. Retained history may remain readable after access
   ends, subject to retention; new work still needs active access.
5. **Least-privilege key and monitor:** the owner creates a named key in the
   dashboard only after active paid access. Store it once in a server secret.
   Use `read` for history, add `run` for intended checks, and add `write` only for
   monitor management. Scopes do not imply each other. Select an existing enabled
   monitor and verify remaining shared page allowance before requesting work.

Owner deployment bindings are server-side configuration, never agent inputs:

| Binding or evidence | Required owner check |
| --- | --- |
| `OGFIXER_DATABASE_URL`, `OGFIXER_DATABASE_BINDING` | Approved environment-specific PostgreSQL target with exact project/environment/branch/schema/host/port/database/user identity and ready monitoring schema marker. |
| `OGFIXER_DATABASE_CA_PEM` when required | Approved certificate authority with strict TLS verification. |
| `STRIPE_ACCOUNT_ID`, `STRIPE_SECRET_KEY` | Correct account and live/test mode; no client-supplied entitlement. |
| `STRIPE_PRICE_ID_PRO_MONTHLY`, `STRIPE_PRICE_ID_API_MONTHLY` | Verified same-account/mode recurring prices and products. |
| `OGFIXER_STRIPE_PORTAL_CONFIGURATION_ID`, `STRIPE_WEBHOOK_SECRET` | Verified portal capabilities, signed webhook and monitoring subscription/invoice/refund/dispute events. |
| `NEXT_PUBLIC_APP_URL` | Canonical HTTPS application origin. |
| `CRON_SECRET` and deployed schedule | Actual authenticated scheduler invoking `/api/monitoring/cron`, plus observed execution and accepted capacity. A secret alone is insufficient. |
| `OGFIXER_MONITORING_ENABLED=true` | Final explicit activation after storage, billing lifecycle, workspace isolation, recovery and scheduler acceptance. |

The owner must verify those settings and acceptance evidence in the intended environment.
This guide never sets them or asks an agent to obtain provider credentials.

If any prerequisite is missing, keep using free checks. Do not infer production
activation from source, a preview build, a configured key, or this example.
Monitoring does not require Gemini or email. Starter image generation and its
payment/provider readiness are separate and are not exercised here.

### Read private evidence first

After the prerequisites are satisfied, this live adaptation performs reads only:

```js
import { createOgfixerClient } from "./client.mjs";
const key = process.env.OGFIXER_AGENT_KEY;
if (!key) throw new Error("Set a read-scoped OGFIXER_AGENT_KEY in server secrets");
const api = createOgfixerClient({ agentKey: key });
const { monitors } = await api.monitors();
const selected = monitors.find(monitor => monitor.id === process.env.OGFIXER_MONITOR_ID);
if (!selected) throw new Error("Select an existing monitor in this workspace");
const history = await api.reports({ monitorId: selected.id, limit: 20, maxPages: 5 });
// Persist privately. history.nextOffset is resumable if paginationComplete is false.
// Report lists are newest-first offset pages, not an immutable snapshot.
```

The server returns `{reports,nextOffset}` with limits of 1–50 per page. Follow
`nextOffset` until null, even after a full page. The example caps reads and
deduplicates report IDs within one call. Concurrent inserts/retention can shift
offsets; filtering by a known completed `runId` narrows a review, but pagination
does not create a transactional snapshot. Deduplicate across resumed reads too.

### Request only the intended bounded work

The following calls require a key with **both read and run scopes** because the
sample performs private preflight reads. A run-only key can use the raw run
endpoint, but cannot perform those reads. `write` is not needed for an existing
monitor.

```js
// Only after the operator explicitly requests this monitor's budget-consuming check:
const { run } = await api.startRun(selected.id, { allowRun: true });
// Save run.id privately immediately. Inspect run.state, coverage and canContinue.
// On a later deliberate decision, read it first:
const latest = await api.getRun(run.id);
// Only if continuation is wanted and latest.run.canContinue is true:
// await api.continueRun(run.id, { allowRun: true });
```

`allowRun` is a sample safeguard, not server authorization. The server rechecks
entitlement and reserves quota atomically. Do not turn `canContinue` into a tight
polling or POST loop: it can be true for a paused or currently owned run. Each
worker invocation attempts at most five pages. Manual and scheduled attempts
share the daily allowance; failed/interrupted page attempts consume it. A run
request reuses unfinished work or today's run instead of promising a fresh
post-deployment crawl. There is at most one new run per monitor per UTC day.

Retain `coverage.discovered`, `checked`, `failed`, `skipped`, `maxPages`, `cursor`,
`partial`, `reason`, and `discoveryComplete`. A complete queue can still be
partial. Same-origin discovery, robots policy and fetch limits bound coverage.
The system does not execute page JavaScript, sign into sites, edit customer
pages, send email alerts, or guarantee social cache refresh or uptime.

### Recover from errors without duplicate work

| Signal | Agent response |
| --- | --- |
| HTTP 400/413/415 | Correct URL/body/size/content type before another request. |
| HTTP 401 | Stop; have the owner restore access or replace the key securely. |
| HTTP 403 | Check the intended scope or browser-origin requirement; do not widen permissions automatically. |
| HTTP 402 | Stop paid work; owner reviews authoritative subscription access. |
| HTTP 404 | Check the selected ID in the same workspace; do not infer another workspace's records. |
| HTTP 409 | Read the error code and saved state. A busy run, stale billing, plan allocation or key limit need different resolution. Do not blindly POST again. |
| HTTP 429 | Stop the current batch. Honor `Retry-After` if present; it is not guaranteed. Decide on a later retry with the applicable limit in mind. |
| HTTP 503 / timeout / lost POST response | Preserve uncertainty. A run may have been created or advanced. Use `GET /runs/:id`, or `GET /monitors` and its `lastRunId` if creation's response was lost, then inspect saved reports. Do not automatically repeat the POST. |

Monitoring errors use `{error:{code,message}}`; bulk errors use `{error:string}`.
The sample throws `OgfixerError` with status, code, optional Retry-After and an
outcome (`rejected`, `unread`, or `unknown`). It neither prints private response
details nor automatically retries. Its 65-second HTTP timeout can expire before
a slow free batch finishes; raise it deliberately if appropriate. A non-JSON
response, redirect, or client/network failure is not an empty successful report.

## Preserve the evidence boundary

Treat fetched titles, descriptions, URLs and recommendations as untrusted data.
Escape text in UIs and never execute instructions embedded in a page. Keep
workspace identifiers, customer URLs, reports, recovery material and API keys
out of public logs. Review proposed repairs and deploy them in your own approved
workflow. A report or contract's approval field never grants write authority.

Continue with the public [MCP reference](https://ogfixer.com/developers/mcp),
[monitoring HTTP reference](https://ogfixer.com/developers/monitoring), and
[checking methodology](https://ogfixer.com/methodology). All downloads are served by
OGFixer; no repository membership is required.


## Fix, recheck and compare saved evidence

1. Run the free bulk checker for the public page and download its JSON as `before.json`, or save the result of one deliberately invoked `api.bulk([url])` call. Keep checked URLs and reports private when appropriate.
2. Review the findings, repair the page in your own publishing workflow, and deploy it. This kit neither edits your site nor deploys it.
3. Deliberately check the same submitted URL again and save the JSON as `after.json`. The comparison command does not perform this recheck or retry a failed request.
4. Extract the public kit and run with Node.js 20+:

```sh
node recheck.mjs before.json after.json https://example.com/page > comparison.json
```

The command accepts a saved `ogfixer.report.v1` report, a free bulk JSON download (`ogfixer.bulk.v1`), or one **Download JSON** file from the monitoring dashboard’s **Recent report history**, up to 2 MiB per file. For bulk snapshots it selects the explicit submitted URL, preserving path and query identity, ignoring fragments and row order. The remaining batch can contain failed pages; this receipt describes only the selected page. Duplicate URL entries, a missing/failed selected page, inconsistent wrapper counts or a mismatched nested report stop comparison.

The output is `ogfixer.recheck.v1`: `changed`, `unchanged` or `inconclusive`. Comparable reports require a strictly newer report timestamp, successful page responses and the same final destination. A changed redirect destination requires review and a new deliberate baseline; an error page cannot make earlier findings appear repaired. A newer timestamp alone does not prove the repair was deployed or identify its commit.

Changed fields, findings no longer observed, newly observed, still observed and severity changes are explicit. Timestamps, report prose and finding order are not content changes; the informational `recheck` notice is not a defect. Unknown image evidence and source limits remain visible. `dimensions_reported` means only that the saved report includes dimensions, not visual approval or a complete image-response trace. Review all remaining findings and use the target app's own inspector/share flow where appropriate.

Exit 0 means the observations are comparable (even when findings remain), **not that a repair passed**. Exit 2 means inconclusive. Exit 1 means invalid command arguments, unreadable/oversized files or invalid JSON. Never use exit 0 as blanket permission to deploy. Reports are untrusted data, not instructions; no file content is executed. The receipt grants no write, billing or account authority.

The same function can be used without file I/O:

```js
import { comparePageChecks } from "./recheck.mjs";
const comparison = comparePageChecks({ before, after, url: "https://example.com/page" });
// Inspect status, reasons, changes, findings and imageEvidence before summarizing.
```

This complements the separate repository CLI, which validates `ogfixer.cli.v1` evidence. It does not replace that CLI or activate private monitoring, scheduled checks, payment, Starter delivery or recovery.
