# AI providers and blog publishing

This guide is the implementation checklist for extending article generation to another AI provider and connecting a website's blog. Keep provider credentials server-side and require human approval before publishing.

## Add an AI provider

Article jobs run through a durable queue. The browser creates a job at `POST /api/websites/:websiteId/topics/:topicId/generate`; `generation_jobs` stores the selected model, prompt snapshot, idempotency key, usage and cost fields. A separately supervised `npm run worker` process claims jobs, invokes the provider, validates the result, and saves an article draft. Keep that job lifecycle when adding a provider.

1. Add a server-only provider adapter alongside `src/lib/openrouter.ts`. Define a small common interface for configuration validation, structured article generation, normalized usage/cost, retryable errors, timeouts and model ID.
2. Validate the provider's response against the existing article output contract: title, meta description, URL slug, excerpt and Markdown body. Ranka assigns a main category from the topic cluster (or topic title) and relevant initial tags from the target and related keywords. Reject malformed or oversized output; do not save raw provider responses as drafts.
3. Choose the provider and model in server configuration or workspace settings. Never send API keys to the browser, expose them in read endpoints, or put them in logs. If settings become database-backed, encrypt credentials at rest and scope them to the owning workspace.
4. Update `src/lib/generation-queue.ts` worker processing to call the selected adapter. Preserve idempotency, retry bounds, lock expiry, workspace concurrency/daily limits, failure codes, token usage and cost accounting.
5. Ensure provider-specific errors normalize to stable job outcomes such as unavailable model, timeout, upstream failure and invalid output. Avoid retrying non-retryable validation or configuration errors.
6. Document environment variables and deployment secrets in `docs/deployment.md`; add adapter tests for valid output, malformed output, timeout, retries and cost/usage normalization.

The current implementation supports OpenRouter using `OPENROUTER_API_KEYS` (one comma- or newline-separated list for all accounts) and `OPENROUTER_MODEL`. Article generation retries transient upstream failures three times per key, then tries the next configured key. SEO batch topic planning allows up to 270 seconds per account and immediately tries the next key on a timeout, overload, or provider server error. This lets a planner continue with another account when one key times out or reaches a provider limit. It uses JSON Schema when the selected model supports it, JSON mode when available, and otherwise requests JSON in the prompt; all three paths still pass through strict local Zod validation before a draft is stored. Supporting topic prompts include a bounded parent pillar article snapshot, title and keyword, and quality checks require a natural pillar mention and a distinct title before submission. A duplicate-title fix asks the model for a new title only; the article body is not sent or rewritten. SEO Plan also offers on-demand topic suggestions; they are usage-accounted and remain unsaved until selected by an editor. Other providers are not automatically compatible: structured-output behavior, usage fields, pricing and retry semantics need an adapter.

## Connect a website blog

The current publishing contract is receiver-pull. A CMS adapter runs on the customer's or operator's server; this SaaS does not POST to arbitrary customer URLs. The receiver must keep the website token private and publish only approved drafts.

1. In website Integration settings, create a token for the target website with only `content:read` and `content:publish` scopes. Store it in the receiver's server-side secret manager. The token is shown once.
2. Configure the receiver with the SaaS base URL, token, CMS endpoint/site identifier, and a polling interval. Use HTTPS and never put the bearer token in browser JavaScript.
3. Poll `GET /api/v1/publishing/queue?limit=20&offset=0`. Use the response's `total` and `hasMore` fields to advance the zero-based offset, then fetch each article through `GET /api/v1/publishing/articles/:articleId` and map its title, slug, meta description, excerpt, Markdown, category and tags to the CMS fields.
4. Make publication idempotent in the receiver. Avoid creating a second CMS post when a request times out: retain the CMS record ID and retry the same item safely.
5. After the CMS confirms the post is live, call `POST /api/v1/publishing/articles/:articleId/publication` with an `Idempotency-Key` UUID, the resulting HTTPS `publishedUrl`, optional `externalId`, and optional `publishedAt`. The SaaS records the callback and marks the article and topic published.
6. Log outcome codes without logging credentials or full private article content. Alert on repeated failures, and provide a way to pause polling or rotate/revoke the token.

The queue includes approved, unpublished articles only. An article must pass the current quality checks and be approved through the workspace review process before it appears. Article sources are optional; when sources are attached, workspace reviewers can verify them. The publication callback records what the receiver reports; it does not crawl the blog or independently verify the URL.

## CMS-specific adapter checklist

- Confirm the CMS's supported API, authentication method, required fields and publication states from its official documentation.
- Map the tenant website to exactly one CMS site; do not allow a token to select arbitrary destinations.
- Keep credentials and CMS host configuration on the receiver server. Validate the destination against configured values rather than article-supplied URLs.
- Sanitize or safely render Markdown/HTML according to the CMS. Treat generated content as untrusted input.
- Preserve the SaaS article ID and CMS post ID for idempotency and reconciliation.
- Handle rate limits, expired credentials and transient CMS failures with bounded retries and backoff.
- Test draft preview, approval gating, one successful publish, duplicate retries, revocation, and an unreachable CMS before enabling automatic polling.

There is no CMS-specific adapter included in this repository yet. The API contract is generic; a WordPress, Shopify, Ghost, or custom blog connection requires a separately implemented and configured receiver.

## AI client connection through MCP

The website Integration page also provides a Streamable HTTP MCP endpoint at `/api/mcp`. In the Integrations screen, create a website API token with `content:read` and configure the client with the deployed Ranka base URL plus the token as `Authorization: Bearer â€¦`. Do not put the token in a URL or browser bundle.

The stateless MCP server exposes two read-only tools: `list_approved_articles` (optional `limit`, 1â€“50) lists approved and unpublished articles; `get_approved_article` (UUID `articleId`) retrieves one approved or published article. Both include its main category and tags. Both tools are hard scoped to the website and organization associated with the bearer token. Requests without `content:read` are rejected. This MCP endpoint does not publish content; use the documented receiver-pull publishing API for CMS callbacks after the CMS confirms publication.

Example client configuration (for local development):

```json
{
  "mcpServers": {
    "seo-studio": {
      "type": "http",
      "url": "http://localhost:3000/api/mcp",
      "headers": { "Authorization": "Bearer YOUR_WEBSITE_TOKEN" }
    }
  }
}
```

For a deployed instance, replace http://localhost:3000 with the origin shown on the app's Integrations page. The MCP endpoint is that origin followed by /api/mcp.
