# Audit log Source: https://docs.promptingcompany.com/api/audit-log Understand what TPC records for API write requests. # Audit log TPC writes an API audit log entry for non-GET requests that return a 2xx response and belong to an organization. ## What is logged Each audit row stores: | Field | Description | | - | - | | Organization ID | The organization resolved from your credential. | | User ID | The human user when the credential has one. | | API key ID | The API key ID for API-key callers. | | Principal ID | Service account ID, API key ID, session ID, or user ID. | | Route and method | The endpoint path and HTTP method. | | Status | The response status. | | Auth method | `session`, `bearer`, or `api_key`. | | Request ID | The `x-request-id` response header. | | Body hash | A SHA-256 hash of the request body. | | Expiration | The retention cutoff for the row. | ## What is not logged TPC does not store full request bodies in the audit table. It stores only the request body hash so you can prove which payload was used without copying customer content into the audit trail. ## Retention API audit log rows are retained for 180 days. ## Lookup There is not yet a public audit-log endpoint. To look up a request today, send support the `x-request-id`, approximate timestamp, and organization slug. # Authentication Source: https://docs.promptingcompany.com/api/authentication Choose between session cookies, OAuth bearer tokens, and API keys for the TPC API. # Authentication TPC resolves callers in a fixed order: API key, bearer token, then session cookie. If you send more than one credential, `x-api-key` wins. ## Choose your credential | Credential | Best for | Notes | | - | - | - | | Session cookie | First-party dashboard calls. | Browser-only. Session callers rely on route-level organization and product checks. | | OAuth bearer | CLI and OAuth clients. | `tpc auth login` uses a browser device flow, then the CLI sends bearer credentials. | | API key | Server-to-server integrations. | Organization-scoped, rotatable, and limited by explicit scopes. | ## Session cookie Session cookies are for The Prompting Company dashboard. The browser sends the `better-auth.session_token` cookie automatically. ```bash theme={null} curl "https://app.promptingco.com/api/v1/content?productId=product_123" \ -H "Cookie: better-auth.session_token=session_token_here" ``` ```ts theme={null} const response = await fetch("/api/v1/content?productId=product_123", { credentials: "include", }); ``` Use session cookies only for first-party browser flows. ## OAuth bearer The CLI authenticates with browser-based device flow: ```bash theme={null} tpc auth login ``` After login, the CLI stores a local token and sends it as a bearer credential: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content?productId=product_123" \ -H "Authorization: Bearer $TPC_ACCESS_TOKEN" ``` ```ts theme={null} const response = await fetch( "https://app.promptingco.com/api/v1/content?productId=product_123", { headers: { Authorization: `Bearer ${accessToken}`, }, }, ); ``` Bearer callers must include the scopes required by the route. ## API key API keys are the recommended credential for integrations. Create an organization API key from: ```text theme={null} https://app.promptingco.com/{orgSlug}/settings/api-keys ``` Then send it with `x-api-key`: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content?productId=product_123" \ -H "x-api-key: $TPC_API_KEY" ``` ```ts theme={null} const response = await fetch( "https://app.promptingco.com/api/v1/content?productId=product_123", { headers: { "x-api-key": process.env.TPC_API_KEY!, }, }, ); ``` ## Organization context An organization API key stays bound to the organization that issued it. Use a product ID or product slug belonging to that organization; sending a different organization header cannot move the key to another organization. Session and OAuth callers can select an organization they belong to with `x-organization-slug` or the `orgSlug` query parameter. ## Precedence `resolveCaller` checks credentials in this order: 1. `x-api-key` 2. `Authorization: Bearer ` 3. Session cookie That precedence makes server integrations deterministic. If a background job accidentally includes a browser cookie, the API key still identifies the integration. ## Rotation and revocation Rotate API keys when a teammate leaves, a secret may have leaked, or an integration boundary changes. 1. Create a new key with the same or narrower scopes. 2. Deploy the new secret to your integration. 3. Confirm requests are succeeding with the new key. 4. Revoke the old key from the API key settings page. Revoked keys fail with: ```json theme={null} { "ok": false, "code": "UNAUTHORIZED", "message": "invalid api key" } ``` # Content documents Source: https://docs.promptingcompany.com/api/content/documents Use TPC document endpoints for generated content and draft workflows. # Content documents Use `/api/v1/content` for product content, including manually supplied pages, generated content, review drafts, and published documents. The legacy `/api/v1/site/pages` surface is deprecated. You need `content:read` for reads and `content:write` for mutations. Set `TPC_API_KEY` and your product ID as described in the [quickstart](/api/quickstart). ## Read a document You need `content:read`. ```bash theme={null} curl "https://app.promptingco.com/api/v1/content/$DOCUMENT_ID" \ -H "x-api-key: $TPC_API_KEY" ``` ## Find a document by path Use path lookup when your source system knows the product path instead of the document ID: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content/by-path?brandId=$TPC_PRODUCT_ID&path=docs/install" \ -H "x-api-key: $TPC_API_KEY" ``` The query parameter is still named `brandId` for this legacy endpoint. Pass the product ID. ## Update a document You need `content:write`. ```bash theme={null} curl "https://app.promptingco.com/api/v1/content/$DOCUMENT_ID" \ -X PUT \ -H "content-type: application/json" \ -H "x-api-key: $TPC_API_KEY" \ -H "Idempotency-Key: document-update-$DOCUMENT_ID" \ --data '{ "title": "Install The Prompting Company", "content": "# Install The Prompting Company\n\nSet up TPC and publish content.", "metaTitle": "Install The Prompting Company", "metaDescription": "Set up TPC and publish content." }' ``` ## Update priority Use `PATCH` when you only need to change document priority: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content/$DOCUMENT_ID" \ -X PATCH \ -H "content-type: application/json" \ -H "x-api-key: $TPC_API_KEY" \ -H "Idempotency-Key: document-priority-$DOCUMENT_ID" \ --data '{ "priority": 80 }' ``` ## Review workflows Create review drafts with `POST /api/v1/content` (up to 25 pages per request) or request generated content with `POST /api/v1/content/generate`. For `POST /api/v1/content`, send one product selector: `productId` or `productSlug`. Each supplied page needs `slug`, `title`, and Markdown `content`; use `canonicalDomainId` for an optional publishing destination. List the review queue with: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content?productId=$TPC_PRODUCT_ID&status=pending_review" \ -H "x-api-key: $TPC_API_KEY" ``` Use the draft ID from `created[].id` or the review queue for draft actions: | Action | Endpoint | | - | - | | Approve or reject | `POST /api/v1/content/{draftId}/review` with `action: "approve"` or `action: "reject"` and optional `feedback` | | Submit edits or request an AI revision | `POST /api/v1/content/{draftId}/revision` | | Queue publishing of an approved draft | `POST /api/v1/content/{draftId}/publish` | | Unpublish and return to review | `POST /api/v1/content/{draftId}/revert` | | Cancel pending or generating content | `POST /api/v1/content/{draftId}/cancel` | Approval automatically queues publishable content for publishing. A successful approval response is not proof that publishing has finished. Unapproved drafts cannot be published; an explicit publish request returns `409`. To update a live document, use its document ID with the `PUT` and `PATCH` examples above. To edit a review draft, use `/revision`. ## Domains and archival Domain attachment is public: use `PATCH /api/v1/content/{documentId}/domains` with `attach`, `detach`, and optional `canonicalDomainId`. Domain IDs must be UUIDs. Use `DELETE /api/v1/content/{documentId}` to archive a live document, and `POST /api/v1/content/{documentId}/restore` to restore it. Deleting an unpublished review draft by its draft ID removes the draft directly; the restore endpoint is for archived live documents. See the [API reference](/api/reference) for request schemas and the endpoints available to your integration. Metadata suggestion routes remain internal. # Content API overview Source: https://docs.promptingcompany.com/api/content/overview Understand the TPC content API surfaces and common workflows. # Content API overview The Content API manages the content surfaces that TPC uses for retrieval, publishing, and public markdown delivery. ## Surfaces | Surface | Use it for | Primary scope | | - | - | - | | Content lifecycle (`/api/v1/content`) | Create, generate, review (approve/reject/revise), publish, and manage product content. | `content:read`, `content:write` | | Site pages (deprecated) | Legacy CRUD alias of the content surface; use `/api/v1/content` instead. | `content:read`, `content:write` | | Content documents and review drafts | Read and update content, metadata, domains, and review workflows through `/api/v1/content`. | `content:read`, `content:write` | | llms.txt | Read and manage generated llms.txt resources. | `content:read`, `content:write` | | Apps and app routes | Manage app configuration and route resources. | `content:read`, `content:write` | Start with `/api/v1/content` for product pages, docs pages, and marketing content. Created and generated pages land in a review queue (`GET /api/v1/content?productId=PRODUCT_ID&status=pending_review`) and publish only after approval (`POST /api/v1/content/{draftId}/review`). ## Common workflow 1. Create an API key with `content:read`. 2. List existing resources for a product. 3. Add `content:write` only when your integration needs mutations. 4. Send `Idempotency-Key` on writes so retries are safe. 5. Store `x-request-id` with your job logs. ## Related guides > [card] [Site pages migration](/api/content/site-pages) > > Move legacy site-page integrations to the content lifecycle API. > [card] [Content documents](/api/content/documents) > > Work with generated and reviewed content documents. # Site pages migration Source: https://docs.promptingcompany.com/api/content/site-pages Migrate deprecated TPC Site Pages API integrations to the content lifecycle API. # Site pages migration > [!WARNING] > > `/api/v1/site/pages` is deprecated. Use `/api/v1/content` for new integrations. The unified content API covers creation, generation, review, publishing, updates, and archival. You need `content:read` for reads and `content:write` for writes. ## Endpoint mapping | Legacy operation | Content API replacement | | - | - | | `GET /api/v1/site/pages` | `GET /api/v1/content` | | `POST /api/v1/site/pages` | `POST /api/v1/content` | | `PATCH /api/v1/site/pages` with a `pages` batch | `PUT /api/v1/content/{documentId}` for each live document | | `DELETE /api/v1/site/pages` with a `pageIds` batch | `DELETE /api/v1/content/{id}` for each item | For list and create requests, send one product selector: `productId` or `productSlug`. List requests default to published pages. Use `status=pending_review` to list drafts awaiting review; the items in that response have a draft shape rather than the live-page shape. ## Creation and publishing You can create up to 25 pages per request. Each page requires `slug`, `title`, and Markdown `content`. Use `canonicalDomainId` to choose a publishing destination; the unified create endpoint rejects unsupported page fields such as `domainIds`. Creation returns review drafts, not published pages. Save each `created[].id` as a draft ID and inspect `failedCount` and `failed` for per-page failures even when the response has `ok: true`. Approve a draft with `POST /api/v1/content/{draftId}/review` and `{"action":"approve"}`. Approval queues publishing for publishable content. Use `/revision` to edit a draft; use `PUT /api/v1/content/{documentId}` to update a live document. The unified `PUT` schema does not accept the legacy `status` field: use the review and publishing actions for lifecycle changes. ## Retry behavior Send a distinct `Idempotency-Key` for each write operation and retain it with the exact request body for retries. When converting a batch update or delete into individual requests, track the result of each item independently. Follow the [quickstart](/api/quickstart) for a complete create request and the [content documents guide](/api/content/documents) for review, update, domain, and archival operations. # Errors Source: https://docs.promptingcompany.com/api/errors Handle The Prompting Company API result envelopes, error codes, and request IDs. # Errors The Prompting Company's JSON endpoints return an `ApiResult` envelope for both success and failure. ## Result shape ```ts theme={null} type ApiSuccess = { ok: true; data: T; }; type ApiError = { ok: false; code: ApiErrorCode; message: string; details?: unknown; }; type ApiResult = ApiSuccess | ApiError; ``` Check `ok` before reading `data`: ```ts theme={null} const result = await response.json(); if (!result.ok) { console.error(result.code, result.message, result.details); return; } console.log(result.data); ``` ## Error codes | Code | Default status | | - | - | | `BAD_REQUEST` | 400 | | `UNAUTHORIZED` | 401 | | `PAYMENT_REQUIRED` | 402 | | `FORBIDDEN` | 403 | | `NOT_FOUND` | 404 | | `METHOD_NOT_ALLOWED` | 405 | | `NOT_ACCEPTABLE` | 406 | | `REQUEST_TIMEOUT` | 408 | | `CONFLICT` | 409 | | `GONE` | 410 | | `PAYLOAD_TOO_LARGE` | 413 | | `UNSUPPORTED_MEDIA_TYPE` | 415 | | `UNPROCESSABLE_ENTITY` | 422 | | `TOO_MANY_REQUESTS` | 429 | | `INTERNAL` | 500 | | `NOT_IMPLEMENTED` | 501 | | `BAD_GATEWAY` | 502 | | `SERVICE_UNAVAILABLE` | 503 | | `GATEWAY_TIMEOUT` | 504 | | `VALIDATION_ERROR` | 422 | | `BUSINESS_LOGIC_ERROR` | 422 | | `EXTERNAL_SERVICE_ERROR` | 502 | | `RATE_LIMITED` | 429 | | `MAINTENANCE_MODE` | 503 | | `LIVE_INDEX_NOT_FOUND` | 404 | | `SCOPE_INVALID` | 422 | ## Common messages | Message | Meaning | | - | - | | `authentication required` | No valid session, bearer token, or API key was found. | | `invalid api key` | The `x-api-key` value could not be verified. | | `public_api_only` | An API key attempted to call an internal route. | | `auth_method_not_allowed` | The endpoint does not accept the credential type you used. | | `insufficient_scope` | Your bearer token or API key is missing a required scope. | | `rate_limited` | You exceeded a route-level rate limit; use `Retry-After`. | | `rate limited` | API-key verification exceeded its rate limit (`RATE_LIMITED`); use backoff if `Retry-After` is absent. | ## Request IDs Every wrapper response includes: ```text theme={null} x-request-id: 6efaa25e-3ef6-4a34-91c1-7ff3e0fd4cc8 ``` You may also send your own `x-request-id` if it uses letters, numbers, `_`, `.`, `-`, or `:` and is at most 128 characters. TPC replaces unsafe values with a fresh ID. Share the request ID with support when you need help tracing a failed request. # Idempotency Source: https://docs.promptingcompany.com/api/idempotency Use Idempotency-Key for safe TPC API retries. # Idempotency Use `Idempotency-Key` on supported non-GET write requests when a network timeout could leave you unsure whether the request succeeded. Public routes enable idempotency by default unless they explicitly opt out, and the request must resolve to an organization. ## When to use it Send an idempotency key for create, update, and delete jobs that your system may retry automatically: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content" \ -X POST \ -H "content-type: application/json" \ -H "x-api-key: $TPC_API_KEY" \ -H "Idempotency-Key: content-sync-2026-04-30-pricing" \ --data '{"productId":"product_123","pages":[{"slug":"pricing","title":"Pricing","content":"# Pricing"}]}' ``` ## Replay behavior TPC keeps an idempotency reservation for 24 hours and caches successful (2xx) JSON responses within that window. Error responses and non-JSON responses are not cached. | Same key | Same route and method | Same body | Result | | - | - | - | - | | Yes | Yes | Yes | Cached response is replayed with `x-idempotent-replay: true`. | | Yes | Yes | No | API returns `409 CONFLICT`. | | Yes | Yes | Request still in progress | API returns `409 CONFLICT`. | | Yes | No | Any body | Treated as a separate operation. | Keys are scoped to the organization, URL pathname, and method. The raw request body is hashed and compared on reuse, so changing JSON whitespace or property order can cause a conflict. Query parameters are not part of the key: use a different key for a different operation, even if only its query string changes. Use a non-empty key of at most 255 characters after trimming. Keep the same key and exact body for retries of one operation; choose a new key for each new operation. ## Retry example Generate and persist a unique `key` for the operation before calling this helper. Reuse it if your job restarts. This example retries network failures; handle HTTP errors such as `429` separately using the [rate-limit guidance](/api/rate-limits). ```ts theme={null} async function createPageWithRetry(productId: string, apiKey: string, key: string) { const body = { productId, pages: [ { slug: "docs/retry-safe-page", title: "Retry-safe page", content: "# Retry-safe page", }, ], }; for (let attempt = 0; attempt < 3; attempt += 1) { try { const response = await fetch("https://app.promptingco.com/api/v1/content", { method: "POST", headers: { "content-type": "application/json", "x-api-key": apiKey, "Idempotency-Key": key, }, body: JSON.stringify(body), }); return await response.json(); } catch (error) { if (attempt === 2) throw error; } } } ``` # API overview Source: https://docs.promptingcompany.com/api/overview Start using the TPC API, authentication methods, scopes, and reference docs. # API overview > [!WARNING] > > The TPC API is in alpha development. If you're interested in using it for a > production use case, contact [support@promptingco.com](mailto:support@promptingco.com) > to discuss your requirements. The Prompting Company API lets you manage your content programmatically through the same `/api/v1` endpoints the dashboard uses, with the same `ApiResult` envelope and organization-scoped data model. Use the API when you need to sync site pages from a CMS, automate content operations, or build server-to-server workflows around your TPC workspace. ## Base URL ```text theme={null} https://app.promptingco.com ``` Local development uses: ```text theme={null} http://localhost:3000 ``` Every public endpoint lives under `/api/v1`. ## Authentication at a glance | Method | Use it when | How you send it | | - | - | - | | Session cookie | You are making first-party dashboard calls from the browser. | The dashboard sends the `better-auth.session_token` cookie. | | OAuth bearer | You are using the CLI or another OAuth client flow. | Send `Authorization: Bearer `. | | API key | You are building server-to-server integrations. | Send `x-api-key: `. | For integrations, create an organization API key from your dashboard settings and grant only the scopes your workflow needs. ## Scope catalog | Scope | Allows | | - | - | | `content:read` | Read site pages, markdown content, and llms.txt files | | `content:write` | Create, update, and delete site pages and content | | `prompts:read` | Read prompts, topics, Radar topics, prompt suggestions, and prompt analysis results | | `prompts:write` | Create, update, archive prompts and generate, edit, or review prompt suggestions | | `simulations:read` | Read agent-simulation tasks, runs, environments, and analytics | | `simulations:write` | Create and trigger simulation runs | | `logs:read` | Read AI-traffic logs and request-level audit events | | `analytics:read` | Read analytics aggregates, including rankings, mentions, sources, and SOV | | `analytics:write` | Write events to analytics | | `products:read` | Read product metadata and competitor data | | `products:write` | Update product settings and competitor lists | > [!NOTE] > > This table is intentionally copied from `apps/client/src/lib/api/scopes.ts`. > When that catalog changes, update this page in the same PR so the docs and > dashboard stay aligned. ## Where to go next > [card] [Quickstart](/api/quickstart) > > Create a scoped key, make your first request, and parse the response envelope. > [card] [Authentication](/api/authentication) > > Choose between session cookies, OAuth bearer tokens, and API keys. > [card] [Reference](/api/reference) > > Explore endpoint schemas generated from the checked-in OpenAPI document. # Quickstart Source: https://docs.promptingcompany.com/api/quickstart Make your first successful TPC API request with an API key. # Quickstart > [!WARNING] > > The TPC API is in alpha development. If you're interested in using it for a > production use case, contact [support@promptingco.com](mailto:support@promptingco.com) > to discuss your requirements. You can make your first content request in under five minutes if you already have access to a TPC organization. ## Step 1: Create an API key Open your organization API key settings: ```text theme={null} https://app.promptingco.com/{orgSlug}/settings/api-keys ``` Create a key with these scopes: ```text theme={null} content:read content:write ``` Copy the key immediately. TPC shows the secret once. > [!NOTE] > > Use a read-only key with only `content:read` until your integration needs to > create, update, or delete content. ## Step 2: Make your first request Export your key and product ID: ```bash theme={null} export TPC_API_KEY="tpc_api_key_here" export TPC_PRODUCT_ID="product_123" ``` List published content for the product: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content?productId=$TPC_PRODUCT_ID&page=1&pageSize=10" \ -H "x-api-key: $TPC_API_KEY" ``` A successful response returns `ok: true`. This example omits filter metadata and additional item fields: ```json theme={null} { "ok": true, "data": { "scope": { "product": { "id": "product_123", "name": "Example Product", "slug": "example" }, "organization": { "id": "org_123", "name": "Example Org", "slug": "example-org" } }, "page": 1, "pageSize": 10, "total": 1, "totalPages": 1, "items": [ { "id": "page_123", "kind": "document", "title": "Pricing", "filePath": "pricing", "sourceUrl": "/pricing", "status": "published", "type": "manual", "isManual": true, "metaTitle": "Pricing", "metaDescription": null, "publishedAt": "2026-04-30T00:00:00.000Z", "createdAt": "2026-04-30T00:00:00.000Z", "updatedAt": "2026-04-30T00:00:00.000Z", "domains": [] } ] } } ``` ## Step 3: Parse the envelope Every JSON endpoint returns an `ApiResult`: ```ts theme={null} type ApiResult = | { ok: true; data: T } | { ok: false; code: string; message: string; details?: unknown }; ``` Handle both branches explicitly: ```ts theme={null} const response = await fetch( `https://app.promptingco.com/api/v1/content?productId=${productId}`, { headers: { "x-api-key": process.env.TPC_API_KEY!, }, }, ); const result = await response.json(); if (!result.ok) { throw new Error(`${result.code}: ${result.message}`); } console.log(result.data.items); ``` ## Step 4: Add pagination and filters The content list endpoint accepts query-string filters: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content?productId=$TPC_PRODUCT_ID&query=pricing&status=published&page=1&pageSize=25&orderBy=updatedAt&orderByDirection=desc" \ -H "x-api-key: $TPC_API_KEY" ``` Common filters: | Query parameter | Purpose | | - | - | | `query` or `q` | Search page title and content metadata. | | `status` | `published` (default) or `draft` for live pages; `pending_review`, `generating`, `failed`, `rejected`, or `approved` for review-queue drafts. | | `pathPrefix` | Return pages under a path, such as `blog/`. | | `hasContent` | Return pages with or without stored content. | | `page` and `pageSize` | Page through up to 100 items per request. | ## Step 5: Create a page Create a page with `content:write`: ```bash theme={null} curl "https://app.promptingco.com/api/v1/content" \ -X POST \ -H "content-type: application/json" \ -H "x-api-key: $TPC_API_KEY" \ -H "Idempotency-Key: content-create-pricing-2026-04-30" \ --data '{ "productId": "'"$TPC_PRODUCT_ID"'", "pages": [ { "slug": "docs/api-quickstart", "title": "API quickstart", "content": "# API quickstart\n\nCreated from the TPC API." } ] }' ``` Example response (organization and product `scope` omitted): ```json theme={null} { "ok": true, "data": { "createdCount": 1, "failedCount": 0, "created": [ { "id": "page_456", "slug": "docs/api-quickstart", "title": "API quickstart", "sourceUrl": null, "status": "pending_review" } ], "failed": [] } } ``` Check `failedCount` and `failed` even when `ok` is `true`: a batch can contain per-page failures. The `id` in each `created` item is a draft ID. Created pages land in the review queue. Approve and publish them with `POST /api/v1/content/{draftId}/review` (`{"action": "approve"}`) — approval queues publishing automatically — or browse the queue with `GET /api/v1/content?productId=$TPC_PRODUCT_ID&status=pending_review`. ## Troubleshooting | Status | Error | What to check | | - | - | - | | `401` | `UNAUTHORIZED` | The key is missing, revoked, mistyped, or sent with the wrong header. | | `403` | `insufficient_scope` | Add the missing scope or use a key created for this workflow. | | `404` | `NOT_FOUND` | Confirm the product belongs to the organization that owns the key. | | `409` | `CONFLICT` | You reused an `Idempotency-Key` with a different request body. | | `429` | `RATE_LIMITED` or `TOO_MANY_REQUESTS` | Honor `Retry-After` when present; otherwise retry with backoff. | Every response includes `x-request-id`. Include that value when you contact support. # Rate limits Source: https://docs.promptingcompany.com/api/rate-limits Understand TPC API quotas, retry headers, and 429 handling. # Rate limits The Prompting Company rate limits protect each authenticated principal. API keys are limited globally by key, and route-level limits can also apply to individual endpoints. ## Current defaults | Caller | Default limit | Window | | - | - | - | | Organization API key | 300 requests | 60 seconds | | Session or OAuth bearer | No global wrapper limit unless the route opts in | Route-defined | API key rows can store a lower configured limit, but the platform cap remains 300 requests per 60 seconds. ## 429 response Both API-key verification and route-level throttling can return `429`, with different error bodies. When API-key verification rejects a request, it returns: ```json theme={null} { "ok": false, "code": "RATE_LIMITED", "message": "rate limited" } ``` This response does not include `Retry-After`; use backoff when the header is absent. When a route-level limit is exceeded, the response is: ```json theme={null} { "ok": false, "code": "TOO_MANY_REQUESTS", "message": "rate_limited", "details": { "limit": 300, "resetAt": "2026-04-30T00:01:00.000Z" } } ``` The route-level response includes: ```text theme={null} Retry-After: 12 x-request-id: 6efaa25e-3ef6-4a34-91c1-7ff3e0fd4cc8 ``` `Retry-After` is seconds until the current bucket resets. > [!NOTE] > > The wrapper currently emits `Retry-After` and `x-request-id`. It does not emit > `X-RateLimit-Limit`, `X-RateLimit-Remaining`, or `X-RateLimit-Reset`. ## Retry with backoff Use `Retry-After` when it is present, then add exponential backoff with jitter for repeated `429` responses. ```ts theme={null} async function fetchWithBackoff(url: string, init: RequestInit, attempts = 4) { for (let attempt = 0; attempt < attempts; attempt += 1) { const response = await fetch(url, init); if (response.status !== 429) { return response; } const header = response.headers.get("retry-after"); const retryAfter = header === null ? NaN : Number(header); const backoffMs = Math.min(1000 * 2 ** attempt, 10000); const delayMs = Number.isFinite(retryAfter) && retryAfter >= 0 ? Math.max(retryAfter * 1000, backoffMs) : backoffMs; const jitterMs = Math.floor(Math.random() * 250); await new Promise((resolve) => setTimeout(resolve, delayMs + jitterMs)); } throw new Error("Rate limit retries exhausted"); } ``` # API reference Source: https://docs.promptingcompany.com/api/reference OpenAPI-generated endpoint reference for the TPC API. # API reference > [!WARNING] > > The TPC API is in alpha development. If you're interested in using it for a > production use case, contact [support@promptingco.com](mailto:support@promptingco.com) > to discuss your requirements. Mintlify generates the endpoint reference from the checked-in `api-reference/openapi.json` snapshot configured in `docs.json`. You can download the published snapshot at: ```text theme={null} https://docs.promptingcompany.com/api-reference/openapi.json ``` Mintlify renders endpoint pages under `api/reference`, including the request parameters, response schemas, authentication requirements, and client snippets present in the snapshot. The snapshot must be regenerated and deployed with the docs when public route metadata changes. From the repository root, run `bun docs:openapi` and commit any changes to `apps/docs/api-reference/openapi.json`. A docs deployment does not fetch the live application spec automatically. The application serves a spec generated from its deployed public route metadata at: ```text theme={null} https://app.promptingco.com/api/v1/openapi.json ``` If you are running docs locally and need to test against a local client app, point the OpenAPI source at: ```text theme={null} http://localhost:3000/api/v1/openapi.json ``` # Get the authenticated user id Source: https://docs.promptingcompany.com/api/reference/account/get-the-authenticated-user-id /api-reference/openapi.json get /api/v1/user/identity Returns the better-auth user id behind the credential. Organization API keys resolve to the user who created the key. Service accounts have no user and are rejected. # Attach App resource Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/attach-app-resource /api-reference/openapi.json post /api/v1/apps/{appId}/resources # Auto-create App route for document Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/auto-create-app-route-for-document /api-reference/openapi.json post /api/v1/apps/{appId}/routes/auto # Create App Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/create-app /api-reference/openapi.json post /api/v1/apps # Create App domain Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/create-app-domain /api-reference/openapi.json post /api/v1/apps/{appId}/domains # Create App route Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/create-app-route /api-reference/openapi.json post /api/v1/apps/{appId}/routes # Create App routes in batch Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/create-app-routes-in-batch /api-reference/openapi.json post /api/v1/apps/{appId}/routes/batch # Delete App Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/delete-app /api-reference/openapi.json delete /api/v1/apps/{appId} # Delete App domain Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/delete-app-domain /api-reference/openapi.json delete /api/v1/apps/{appId}/domains/{domainId} # Delete App route Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/delete-app-route /api-reference/openapi.json delete /api/v1/apps/{appId}/routes/{routeId} # Detach App resource Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/detach-app-resource /api-reference/openapi.json delete /api/v1/apps/{appId}/resources # Generate App llms.txt Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/generate-app-llmstxt /api-reference/openapi.json get /api/v1/apps/{appId}/llms-txt # Get App Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/get-app /api-reference/openapi.json get /api/v1/apps/{appId} # Get App config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/get-app-config /api-reference/openapi.json get /api/v1/apps/{appId}/app-config # Get web-domain routing config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/get-web-domain-routing-config /api-reference/openapi.json get /api/v1/domain/{id}/routing Deprecated. Web-domain path routing was served by the Web Edge Router, which has been retired; publishing a config no longer affects request routing. These endpoints stop responding after 2026-12-15. # List App domains Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/list-app-domains /api-reference/openapi.json get /api/v1/apps/{appId}/domains # List App resources Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/list-app-resources /api-reference/openapi.json get /api/v1/apps/{appId}/resources # List App route candidates Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/list-app-route-candidates /api-reference/openapi.json get /api/v1/apps/{appId}/route-candidates # List App routes Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/list-app-routes /api-reference/openapi.json get /api/v1/apps/{appId}/routes # List Apps Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/list-apps /api-reference/openapi.json get /api/v1/apps # Preview App route import Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/preview-app-route-import /api-reference/openapi.json post /api/v1/apps/{appId}/routes/import-preview # Publish web-domain routing config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/publish-web-domain-routing-config /api-reference/openapi.json post /api/v1/domain/{id}/routing/publish Deprecated. Web-domain path routing was served by the Web Edge Router, which has been retired; publishing a config no longer affects request routing. These endpoints stop responding after 2026-12-15. # Reset web-domain routing config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/reset-web-domain-routing-config /api-reference/openapi.json delete /api/v1/domain/{id}/routing Deprecated. Web-domain path routing was served by the Web Edge Router, which has been retired; publishing a config no longer affects request routing. These endpoints stop responding after 2026-12-15. # Save and publish web-domain routing config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/save-and-publish-web-domain-routing-config /api-reference/openapi.json put /api/v1/domain/{id}/routing Deprecated. Web-domain path routing was served by the Web Edge Router, which has been retired; publishing a config no longer affects request routing. These endpoints stop responding after 2026-12-15. # Update App Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/update-app /api-reference/openapi.json patch /api/v1/apps/{appId} # Update App config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/update-app-config /api-reference/openapi.json patch /api/v1/apps/{appId}/app-config # Update App domain Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/update-app-domain /api-reference/openapi.json patch /api/v1/apps/{appId}/domains/{domainId} # Update App resource Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/update-app-resource /api-reference/openapi.json patch /api/v1/apps/{appId}/resources/{resourceId} # Update App route Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/update-app-route /api-reference/openapi.json patch /api/v1/apps/{appId}/routes/{routeId} # Validate web-domain routing config Source: https://docs.promptingcompany.com/api/reference/apps-&-publishing/validate-web-domain-routing-config /api-reference/openapi.json post /api/v1/domain/{id}/routing/validate Deprecated. Web-domain path routing was served by the Web Edge Router, which has been retired; publishing a config no longer affects request routing. These endpoints stop responding after 2026-12-15. # Cancel in-flight content generation Source: https://docs.promptingcompany.com/api/reference/content/cancel-in-flight-content-generation /api-reference/openapi.json post /api/v1/content/{id}/cancel Cancel a draft whose generation is still `pending` or `generating`. The draft is marked `cancelled` and soft-deleted so it leaves the generating queue. Completed, failed, rejected, approved, or published drafts return 409 — delete or revert those instead. # Count content Source: https://docs.promptingcompany.com/api/reference/content/count-content /api-reference/openapi.json get /api/v1/content/count/{orgId} # Create content Source: https://docs.promptingcompany.com/api/reference/content/create-content /api-reference/openapi.json post /api/v1/content Create content pages. Created pages land in the review queue as `pending_review` drafts and publish only after approval. # Create or update a product scraper configuration Source: https://docs.promptingcompany.com/api/reference/content/create-or-update-a-product-scraper-configuration /api-reference/openapi.json put /api/v1/products/{productId}/scraper # Create site pages Source: https://docs.promptingcompany.com/api/reference/content/create-site-pages /api-reference/openapi.json post /api/v1/site/pages Deprecated, will be removed in future versions. Please use POST /api/v1/content instead. # Delete a product scraper configuration Source: https://docs.promptingcompany.com/api/reference/content/delete-a-product-scraper-configuration /api-reference/openapi.json delete /api/v1/products/{productId}/scraper # Delete content Source: https://docs.promptingcompany.com/api/reference/content/delete-content /api-reference/openapi.json delete /api/v1/content/{id} Delete one content item by id. A live document is soft-deleted along with its linked draft and tracked URL; an unpublished review draft is deleted directly, including drafts still in `generating`. # Delete site pages Source: https://docs.promptingcompany.com/api/reference/content/delete-site-pages /api-reference/openapi.json delete /api/v1/site/pages Deprecated, will be removed in future versions. Please use DELETE /api/v1/content/{id} instead. # Generate content for prompts Source: https://docs.promptingcompany.com/api/reference/content/generate-content-for-prompts /api-reference/openapi.json post /api/v1/content/generate Start the content-generation agent for one or more prompts. Each prompt gets a draft (returned with its `draftId` and `runId`); generated content lands in the review queue as `pending_review`, never published directly. Poll `GET /api/v1/content/{draftId}` until `generationStatus` is `completed` or `failed`. # Get a product scraper configuration Source: https://docs.promptingcompany.com/api/reference/content/get-a-product-scraper-configuration /api-reference/openapi.json get /api/v1/products/{productId}/scraper # Get content Source: https://docs.promptingcompany.com/api/reference/content/get-content /api-reference/openapi.json get /api/v1/content/{id} Get one content item by id. Accepts a live document id or a review draft id; `kind` in the response tells which one answered. # Get content by path Source: https://docs.promptingcompany.com/api/reference/content/get-content-by-path /api-reference/openapi.json get /api/v1/content/by-path # Get public markdown content by ID Source: https://docs.promptingcompany.com/api/reference/content/get-public-markdown-content-by-id /api-reference/openapi.json get /api/v1/md/{id} Retrieves public markdown content by ID. Supports standard x-api-key authentication (productId/productSlug via query param or X-Tpc-Product-* headers as fallback) as well as the legacy X-Tpc-* header model. # Get public markdown content by path Source: https://docs.promptingcompany.com/api/reference/content/get-public-markdown-content-by-path /api-reference/openapi.json get /api/v1/md/by-path/{path} Retrieves public markdown content by file path. Supports standard x-api-key authentication (productId/productSlug via query param or X-Tpc-Product-* headers as fallback) as well as the legacy X-Tpc-* header model. # Get root public markdown content Source: https://docs.promptingcompany.com/api/reference/content/get-root-public-markdown-content /api-reference/openapi.json get /api/v1/md/by-path Retrieves the root public markdown content. Supports standard x-api-key authentication (productId/productSlug via query param or X-Tpc-Product-* headers as fallback) as well as the legacy X-Tpc-* header model. # Get summary metrics for tracked URLs Source: https://docs.promptingcompany.com/api/reference/content/get-summary-metrics-for-tracked-urls /api-reference/openapi.json get /api/v1/tracked-urls/metrics # List content Source: https://docs.promptingcompany.com/api/reference/content/list-content /api-reference/openapi.json get /api/v1/content Unified content list across the lifecycle. `status` selects the view: `published` (default) and `draft` list live site pages; `pending_review`, `generating`, `failed`, `rejected`, and `approved` list content drafts in the review queue. Provide exactly one of `productId` or `productSlug`. # List site pages Source: https://docs.promptingcompany.com/api/reference/content/list-site-pages /api-reference/openapi.json get /api/v1/site/pages Deprecated, will be removed in future versions. Please use `GET /api/v1/content` instead. # List tracked URLs ranked by citation count Source: https://docs.promptingcompany.com/api/reference/content/list-tracked-urls-ranked-by-citation-count /api-reference/openapi.json get /api/v1/tracked-urls/analytics # Publish an approved content draft Source: https://docs.promptingcompany.com/api/reference/content/publish-an-approved-content-draft /api-reference/openapi.json post /api/v1/content/{id}/publish Queue publishing for an approved review draft. Publishing is gated on approval: an unapproved draft returns 409. # Queue a product scraping run Source: https://docs.promptingcompany.com/api/reference/content/queue-a-product-scraping-run /api-reference/openapi.json post /api/v1/products/{productId}/scraper/runs # Replace content Source: https://docs.promptingcompany.com/api/reference/content/replace-content /api-reference/openapi.json put /api/v1/content/{id} # Restore archived content Source: https://docs.promptingcompany.com/api/reference/content/restore-archived-content /api-reference/openapi.json post /api/v1/content/{id}/restore Restore a soft-deleted live document and its linked draft and tracked URL. Accepts an archived document id. # Revert published content to the review queue Source: https://docs.promptingcompany.com/api/reference/content/revert-published-content-to-the-review-queue /api-reference/openapi.json post /api/v1/content/{id}/revert Unpublish a draft's live document (soft-delete, including its tracked URL) and return the draft to the review queue. # Review a content draft Source: https://docs.promptingcompany.com/api/reference/content/review-a-content-draft /api-reference/openapi.json post /api/v1/content/{id}/review Approve or reject a draft awaiting review. Approval enqueues publishing for publishable content; rejection stores `feedback` as the rejection reason. # Revise a content draft Source: https://docs.promptingcompany.com/api/reference/content/revise-a-content-draft /api-reference/openapi.json post /api/v1/content/{id}/revision Submit an edited revision (`content`) or relaunch the generation agent with reviewer `feedback` (Pro plan). Both keep the draft in the review queue and reset a prior rejection. # Search content Source: https://docs.promptingcompany.com/api/reference/content/search-content /api-reference/openapi.json post /api/v1/content/search/{orgId} # Track a URL for citation analytics Source: https://docs.promptingcompany.com/api/reference/content/track-a-url-for-citation-analytics /api-reference/openapi.json post /api/v1/tracked-urls # Untrack a URL Source: https://docs.promptingcompany.com/api/reference/content/untrack-a-url /api-reference/openapi.json delete /api/v1/tracked-urls/{id} # Update a tracked URL Source: https://docs.promptingcompany.com/api/reference/content/update-a-tracked-url /api-reference/openapi.json put /api/v1/tracked-urls/{id} Fields you omit keep their stored values. Send null or an empty string to clear title, description, or documentId; an empty category resets it to other. url cannot be cleared. # Update content Source: https://docs.promptingcompany.com/api/reference/content/update-content /api-reference/openapi.json patch /api/v1/content/{id} # Update content domains Source: https://docs.promptingcompany.com/api/reference/content/update-content-domains /api-reference/openapi.json patch /api/v1/content/{id}/domains # Update site pages Source: https://docs.promptingcompany.com/api/reference/content/update-site-pages /api-reference/openapi.json patch /api/v1/site/pages Deprecated, will be removed in future versions. Please use PUT /api/v1/content/{id} instead. # Retrieve product knowledge across documents and code Source: https://docs.promptingcompany.com/api/reference/knowledge/retrieve-product-knowledge-across-documents-and-code /api-reference/openapi.json post /api/v1/products/{productId}/knowledge/retrieve Retrieves product-scoped knowledge through public source types. The request uses include values such as documents, generated, and code; raw corpus ids and storage backends are not part of the public contract. # Cancel a persona's personal agent request Source: https://docs.promptingcompany.com/api/reference/personas/cancel-a-personas-personal-agent-request /api-reference/openapi.json post /api/v1/personas/{personaId}/personal-agents/{agent} Cancels a requested Grok Bot or Muse on a persona. The response is the new request status and never includes accounts, profiles, or connection details. # Create a persona Source: https://docs.promptingcompany.com/api/reference/personas/create-a-persona /api-reference/openapi.json post /api/v1/personas Creates a persona for the product named by productId (brandId is accepted as a legacy alias). Idempotent on name, case-insensitively: an existing persona with the same name is returned with status 200 instead of being duplicated. # Delete a persona Source: https://docs.promptingcompany.com/api/reference/personas/delete-a-persona /api-reference/openapi.json delete /api/v1/personas/{personaId} Soft-deletes a persona. Prompts that referenced it keep their history. # Get a persona Source: https://docs.promptingcompany.com/api/reference/personas/get-a-persona /api-reference/openapi.json get /api/v1/personas/{personaId} # List personas Source: https://docs.promptingcompany.com/api/reference/personas/list-personas /api-reference/openapi.json get /api/v1/personas Lists the personas of one product, newest first. Each persona includes promptCount and personal-agent statuses (requested or active). The payload never includes accounts, Kernel profiles, or connection details. Pass the product as productId; brandId is accepted as a legacy alias. page is zero-based. # Request personal agents for a persona Source: https://docs.promptingcompany.com/api/reference/personas/request-personal-agents-for-a-persona /api-reference/openapi.json post /api/v1/personas/{personaId}/personal-agents Asks the TPC team to add Grok Bot, Muse, or both to a persona. Allowed only when the organization has an active Enterprise plan and that agent's organization flag. The response is the new request statuses and never includes accounts, profiles, or connection details. # Update a persona Source: https://docs.promptingcompany.com/api/reference/personas/update-a-persona /api-reference/openapi.json put /api/v1/personas/{personaId} Replaces the supplied fields of a persona; fields left out are unchanged. # Create a product (brand) in the active organization Source: https://docs.promptingcompany.com/api/reference/products/create-a-product-brand-in-the-active-organization /api-reference/openapi.json post /api/v1/brands # Get a product by ID Source: https://docs.promptingcompany.com/api/reference/products/get-a-product-by-id /api-reference/openapi.json get /api/v1/brands/{brandId} # List products (brands) in the active organization Source: https://docs.promptingcompany.com/api/reference/products/list-products-brands-in-the-active-organization /api-reference/openapi.json get /api/v1/brands # Replace product settings by ID Source: https://docs.promptingcompany.com/api/reference/products/replace-product-settings-by-id /api-reference/openapi.json put /api/v1/brands/{brandId} # List a prompt's answer engines Source: https://docs.promptingcompany.com/api/reference/prompts/list-a-prompts-answer-engines /api-reference/openapi.json get /api/v1/prompts/{id}/answer-engines Each active conversation query on the prompt, with its engine, location, schedule, last completed answer, pause state, and persona. # Verify production runtime capabilities Source: https://docs.promptingcompany.com/api/reference/service-status/verify-production-runtime-capabilities /api-reference/openapi.json get /api/v1/runtime-capabilities Runs a fixed, local, read-only probe of the production runtime. It accepts no model, text, module, URL, or filesystem input and performs no paid or third-party operation. # List agent simulation runs Source: https://docs.promptingcompany.com/api/reference/simulations/list-agent-simulation-runs /api-reference/openapi.json get /api/v1/agent-simulation/runs # Get cited-source analytics and citation events Source: https://docs.promptingcompany.com/api/reference/traffic-&-sources/get-cited-source-analytics-and-citation-events /api-reference/openapi.json get /api/v1/sources/analytics # Add conversations to a view Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/add-conversations-to-a-view /api-reference/openapi.json post /api/v1/views/{viewId}/conversations Adds conversation queries of the view's brand to the view. Send conversationQueryIds, or promptIds to add each prompt's active conversation queries, not both. Ids outside the brand are skipped; the request fails with 400 when none are valid. Answers 200 with addedCount 0 when every valid id is already in the view. # Approve or reject prompt suggestions Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/approve-or-reject-prompt-suggestions /api-reference/openapi.json post /api/v1/prompt-suggestions/review Batch-approve or reject prompt suggestions. Approval creates tracked prompts and conversation queries using each suggestion's persona and answer engines, falling back to the product default persona and chatgpt/gemini/sonar. # Create a view Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/create-a-view /api-reference/openapi.json post /api/v1/views Creates a view for a brand in the organization. Send conversationQueryIds, or promptIds to add each prompt's active conversation queries, not both. Ids that do not belong to the brand are skipped. # Get a view Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/get-a-view /api-reference/openapi.json get /api/v1/views/{viewId} Returns a view with its brand and conversations, including memberships whose conversation query was archived. # Get per-prompt sentiment analytics for a product Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/get-per-prompt-sentiment-analytics-for-a-product /api-reference/openapi.json get /api/v1/analytics/sentiment # Get rolling share of voice time series and breakdowns Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/get-rolling-share-of-voice-time-series-and-breakdowns /api-reference/openapi.json get /api/v1/analytics/sov/timeseries # Get share of voice accumulated over a date range Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/get-share-of-voice-accumulated-over-a-date-range /api-reference/openapi.json get /api/v1/analytics/sov # Ingest server-side SDK analytics event (page_visit) Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/ingest-server-side-sdk-analytics-event-page_visit /api-reference/openapi.json post /api/v1/analytics/events # List conversation queries Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/list-conversation-queries /api-reference/openapi.json get /api/v1/conversation-queries Requires at least one of `brandId`, `promptId`, or `promptIds`. Use `viewId` with `brandId` to limit results to a view. # List prompt suggestions for a product Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/list-prompt-suggestions-for-a-product /api-reference/openapi.json get /api/v1/prompt-suggestions # List views Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/list-views /api-reference/openapi.json get /api/v1/views Lists the organization's views, newest first, each with its brand and conversationCount. Filter by brandId; search matches name or description. page is one-based. # Regenerate prompt suggestions for a product (fan-out by topic) Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/regenerate-prompt-suggestions-for-a-product-fan-out-by-topic /api-reference/openapi.json post /api/v1/prompt-suggestions/regenerate # Remove conversations from a view Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/remove-conversations-from-a-view /api-reference/openapi.json delete /api/v1/views/{viewId}/conversations Removes the listed conversation queries, or every conversation query of the listed promptIds, from the view, including ones whose conversation query was archived. # Run a dimensional analytics query for a product Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/run-a-dimensional-analytics-query-for-a-product /api-reference/openapi.json post /api/v1/analytics/explore Query one analytics metric (sov, citations, traffic, sentiment) grouped by at most one dimension, scoped by filters and a date window. Returns flat rows plus column metadata for generic rendering. # Summarize industry rankings across prompt topics Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/summarize-industry-rankings-across-prompt-topics /api-reference/openapi.json get /api/v1/prompt-topics/industry-rankings/summary Returns each topic's competitive position and compact product ranking, aggregated from the existing prompt-level share-of-voice data. Pass status to filter to one competitive state (winning, contested, opportunity, or unranked) server-side. Pass page and/or pageSize (max 100) to page through topics; totals always cover every topic and matchedTopics counts the filtered set. # Update a prompt message and its query analytics Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/update-a-prompt-message-and-its-query-analytics /api-reference/openapi.json put /api/v1/prompts/with-queries/{id} # Update a prompt suggestion's message, persona, or answer engines Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/update-a-prompt-suggestions-message-persona-or-answer-engines /api-reference/openapi.json patch /api/v1/prompt-suggestions/{id} # Update a view Source: https://docs.promptingcompany.com/api/reference/visibility-&-mentions/update-a-view /api-reference/openapi.json patch /api/v1/views/{viewId} Updates the supplied fields of a view. Setting isDefault to true clears the default flag on the brand's other views. # Scopes Source: https://docs.promptingcompany.com/api/scopes Review the TPC API scope catalog and minimum-scope examples. # Scopes Scopes define what an API key or OAuth bearer token can do. Session callers skip scope checks because the dashboard uses route-level organization and product authorization instead. Use the smallest scope set that can complete the workflow. Organization owners and admins can grant all catalog scopes; members can grant read scopes only. The key creation form pairs each selected write scope with its matching read scope. A scope does not make an internal endpoint public. Use the generated reference to find endpoints available to organization API keys. `mcp:api` is reserved for OAuth access tokens and cannot be granted to API keys. ## Catalog | Scope | Description | | - | - | | `content:read` | Read site pages, markdown content, and llms.txt files | | `content:write` | Create, update, and delete site pages and content | | `prompts:read` | Read prompts, topics, Radar topics, prompt suggestions, and prompt analysis results | | `prompts:write` | Create, update, archive prompts and generate, edit, or review prompt suggestions | | `simulations:read` | Read agent-simulation tasks, runs, environments, and analytics | | `simulations:write` | Create and trigger simulation runs | | `logs:read` | Read AI-traffic logs and request-level audit events | | `analytics:read` | Read analytics aggregates, including rankings, mentions, sources, and SOV | | `analytics:write` | Write events to analytics | | `products:read` | Read product metadata and competitor data | | `products:write` | Update product settings and competitor lists | > [!NOTE] > > This catalog is copied from `apps/client/src/lib/api/scopes.ts`. Update both > places whenever scopes are added, renamed, or removed. ## Minimum scope examples | Task | Minimum scopes | | - | - | | Read-only dashboard integration | `content:read` | | Content sync pipeline that writes pages | `content:read`, `content:write` | | Analytics export job | `analytics:read` | | Prompt reporting job | `prompts:read` | | Simulation runner | `simulations:read`, `simulations:write` | | Support or compliance audit export | `logs:read` | ## Denied requests If a token-style caller lacks a required scope, TPC returns `403`: ```json theme={null} { "ok": false, "code": "FORBIDDEN", "message": "insufficient_scope", "details": { "requiredScopes": ["content:write"], "missingScopes": ["content:write"] } } ``` Create a new key or rotate the existing integration key from: ```text theme={null} https://app.promptingco.com/{orgSlug}/settings/api-keys ``` Do not add write scopes to a key used only for dashboards or reporting. # Authentication Source: https://docs.promptingcompany.com/cli/authentication Log in with device flow, or authenticate the TPC CLI non-interactively for CI. # Authentication ## Login Authenticate with browser-based device flow: ```bash theme={null} tpc auth login ``` The CLI uses the OAuth bearer path described in the [API authentication guide](/api/authentication#oauth-bearer). The flow is: 1. `tpc` requests a device code. 2. Your browser opens. 3. You sign in to The Prompting Company. 4. You approve the CLI. 5. The CLI stores your session locally. After login, verify your session: ```bash theme={null} tpc auth whoami ``` Logout when needed: ```bash theme={null} tpc auth logout ``` ## Non-interactive authentication For CI, scripts, and other headless environments where browser login is not available, the CLI reads credentials from environment variables. Two schemes are supported and they map to different request headers: | Variable | Header sent | Use for | | - | - | - | | `TPC_API_TOKEN` | `Authorization: Bearer ` | OAuth bearer tokens — for example, the session token issued by `tpc auth login`. | | `TPC_API_KEY` | `x-api-key: ` | API keys created via the dashboard. See [API authentication](/api/authentication#api-key) for how to create one. | ```bash theme={null} # OAuth bearer token export TPC_API_TOKEN="your-bearer-token" tpc auth whoami # API key export TPC_API_KEY="your-api-key" tpc auth whoami ``` If both `TPC_API_TOKEN` and `TPC_API_KEY` are set, the CLI uses `TPC_API_TOKEN` and prints a warning to stderr. When neither variable is set, the CLI falls back to the session created by `tpc auth login`. # Agent Experience Source: https://docs.promptingcompany.com/cli/commands/agent-experience Set up AX experiments and competitive benchmarks, and answer onboarding questions from your terminal. # Agent Experience Use `tpc sim ax setup` to configure an Agent Experience experiment for your product. Add `--type benchmark` to design a competitive benchmark instead. ## Prerequisites * [Install the CLI](/cli/installation) and sign in with `tpc auth login`. Setup requires OAuth login; API keys are not supported. * Supply your organization and product with `--scope /`. * For competitive benchmarks, your organization must have benchmarks enabled. ## Guided setup ```bash theme={null} # Set up your product's Agent Experience experiment tpc sim ax setup --scope acme/my-product # Design a competitive benchmark tpc sim ax setup --type benchmark --scope acme/my-product ``` In an interactive terminal, benchmark setup asks for a brief and competitors. Enter competitors as `NAME` or `NAME=DOMAIN`, then submit a blank line to finish. Your own product is included automatically. Setup follows progress and prompts when the agent requests text, credentials, or files. Credential input is hidden. File requests accept a local file path and upload the file before submitting the answer. Uploads must be regular files no larger than 100 MiB. The backend does not accept archives for benchmark setup; provide individual files when requested. Optional questions can be declined with a blank answer. Required questions must be answered; press Ctrl+C to leave the run paused and reconnect later. On successful watched setup, the command prints the experiment ID and a `tpc sim experiment run` command. Setup does not start a benchmark iteration. Review the experiment and configure any task credentials before running it. `tpc sim experiment run status ` includes saved per-run failure reasons in text and JSON output. `tpc sim experiment results ` reports execution coverage when available: executed runs, runs that did not start, and scored runs. Runs that fail before execution are flagged separately; their task and model performance remains unknown, and an incomplete batch should be repaired before comparing models. Older results retain their original summary fields until results are regenerated. ## Supply benchmark inputs with flags ```bash theme={null} tpc sim ax setup \ --type benchmark \ --scope acme/my-product \ --intent "Compare how easily agents can deploy a web app" \ --competitor "Vercel=https://vercel.com" \ --competitor "Netlify=https://netlify.com" \ --watch ``` | Flag | Default | Description | | - | - | - | | `--type` | `agent-experience` | `agent-experience` or `benchmark`. | | `--intent` | — | Benchmark brief, 1–4000 characters. Only valid with `--type benchmark`. | | `--competitor` | — | Repeatable `NAME` or `NAME=DOMAIN`. Supply 1–10 entries; the server adds your own product and requires at least one other product. Only valid with `--type benchmark`. | | `--watch` | Enabled interactively; disabled otherwise | Follow progress. Use `--watch=false` to start setup and detach. | Omitting `--type` selects the existing product AX flow. Product AX setup refreshes the product's singleton Agent Experience experiment. Each new benchmark setup run creates its own benchmark. Both types reattach to an existing in-flight run for the same product and type; resubmitting flags does not edit that in-flight run. ## Resume onboarding ```bash theme={null} # Reconnect and answer pending questions for either setup type tpc sim ax setup resume --scope acme/my-product # Inspect progress without answering questions tpc sim ax status --scope acme/my-product # Follow progress until completion or a question requires input tpc sim ax status --scope acme/my-product --watch ``` `setup resume` follows the existing run without starting another one. After it completes, use `tpc sim experiment list --scope acme/my-product` to inspect the generated experiment. ## Automation and JSON output Without an interactive terminal, or with `--format json`, benchmark setup requires `--intent` and at least one `--competitor`. It never reads answers from piped stdin. ```bash theme={null} tpc sim ax setup --type benchmark \ --scope acme/my-product \ --intent "Compare deployment workflows" \ --competitor "Vercel=https://vercel.com" \ --format json ``` Without `--watch`, JSON output contains the setup response, including `runId` and `setupRunId`. With `--watch`, the command emits one final JSON object: * Completion: `runId`, `status`, `milestones`, and `experimentId` for watched `setup`. * Failure: `runId`, `status: "failed"`, and `milestones`, with a nonzero exit. * Required interaction: `runId`, `status: "input_required"`, and `pending` containing the requested items, with a nonzero exit. Reconnect with `setup resume` in a terminal. Progress-only `status --watch` and non-interactive `setup resume` also stop with a nonzero exit when input is needed. Error guidance is written separately from JSON output. Secret answers are never included in the CLI's output. ## Product AX credentials ```bash theme={null} tpc sim ax env set "API_KEY=$PRODUCT_API_KEY" --scope acme/my-product tpc sim ax env list --scope acme/my-product tpc sim ax env rm API_KEY --scope acme/my-product ``` These `env` commands apply to the product's singleton Agent Experience experiment, not competitive benchmarks. They require that experiment to exist and do not answer an onboarding question. Use `setup resume` for pending onboarding requests. # Analytics Source: https://docs.promptingcompany.com/cli/commands/analytics Read share of voice, sentiment, traffic, and citations from the TPC CLI, or build a custom query with explore. # Analytics Read analytics for the active product from the terminal. Analytics commands are read-only and require a token or API key with the `analytics:read` scope. > [!NOTE] > > Analytics commands require `--scope /`. ```bash theme={null} # Product share of voice over the last 30 days tpc analytics sov --scope pro-org/my-product # Industry ranking (competitor share of voice) tpc analytics sov --scope pro-org/my-product --by competitor # Per-prompt sentiment with week-over-week change tpc analytics sentiment --scope pro-org/my-product --wow # AI traffic grouped by page tpc analytics traffic --scope pro-org/my-product --by page # Cited sources leaderboard tpc analytics citations --scope pro-org/my-product --last 30d --top 25 ``` ## Performance reports Generate the same one-page bento PDF as the admin-mode report generator. The CLI command is available to admins and non-admins with access to the product. ```bash theme={null} # Last complete Monday–Sunday week in UTC tpc analytics report --scope acme/my-product # Any date selects its Monday–Sunday week tpc analytics report --scope acme/my-product --week 2026-07-13 --output weekly.pdf # Custom inclusive range, up to 366 days tpc analytics report --scope acme/my-product --from 2026-07-01 --to 2026-07-19 # Full data, including every topic and industry rank tpc analytics report --scope acme/my-product --week 2026-07-13 --json > report.json ``` | Flag | Description | | - | - | | `--week` | Any `YYYY-MM-DD` date in a completed Monday–Sunday week. Defaults to the last complete week. Use `--from` / `--to` to include the current partial week. | | `--from`, `--to` | Custom inclusive UTC range. Both required together; cannot combine with `--week`. Future dates are rejected. | | `--output`, `-o` | PDF path. Defaults to a filename containing the product and dates. Existing files are never overwritten. | | `--json` | Print the full report data instead of writing a PDF. Also available through `--format json`; cannot combine with `--output`. | All visibility metrics use the selected date range, not rolling 30-day snapshots. SoV change is in **percentage points** against the preceding equal-length period. AI traffic includes inference visits only. The PDF shows the industry leader and nearby ranks, share of voice for up to five models, and up to six topics representing winning, contested, and opportunity states. Model bars show each model's share of voice, not a normalized split that adds up to 100%. JSON contains the full ranking, model, and topic data. Topic labels follow the dashboard: winning means the product ranks first; contested means another product leads but this product is ranked; opportunity means the topic has a leader but this product is unranked. Topics without a leader are labeled unranked. Successful empty visibility queries show `0.0%`, including topic rows. Failed sections are marked unavailable, not zero. A partial report still downloads and lists unavailable sections. ## Share of voice `tpc analytics sov` returns one value for the selected date range. It counts completed runs that mention the product, divides by all completed runs in the same scope and range, and then multiplies by 100. The default range includes today and the preceding 29 calendar days. ```bash theme={null} # One accumulated value for an explicit range tpc analytics sov --scope pro-org/my-product --from 2026-04-01 --to 2026-04-30 # Rolling 30-day snapshots for charting tpc analytics sov --scope pro-org/my-product --timeseries --last 90d # Seven-day rolling snapshots over the last 30 snapshot dates tpc analytics sov --scope pro-org/my-product --timeseries --rolling-window 7 --last 30d # Four-week rolling snapshots grouped into Monday-starting weekly buckets tpc analytics sov --scope pro-org/my-product --timeseries --granularity week --rolling-window 4 --last 90d # Ranked breakdowns use the time-series analytics endpoint tpc analytics sov --scope pro-org/my-product --by competitor --last 30d # Competitor ranking within one topic tpc analytics sov --scope pro-org/my-product --by competitor --topic ``` `--timeseries`, `--by`, `--prompt`, and `--topic` return rolling snapshots. In those modes, `--from`, `--to`, and `--last` select snapshot dates. For a product or `--by engine` request, `--granularity day|week|month` selects the UTC calendar bucket and `--rolling-window 1..30` controls how many buckets are included in each point. They default to `day` and `30`. Adjacent snapshots overlap, so do not sum their `mentions` or `runs` values. ## Explore: build your own analytics query `tpc analytics explore` is the flexible query surface behind the fixed commands above. Pick one metric, group it by at most one value with `--by`, then scope it with filters and a date window. It calls the `POST /api/v1/analytics/explore` endpoint, so anything you can do here you can also do from the API or the `explore_analytics` MCP tool. | Metric | Group by (`--by`) | Filters | | - | - | - | | `sov` | `date`, `prompt`, `topic`, `engine`, `competitor` | `--view`, `--prompt`, `--topic`, `--engine`, `--region` | | `citations` | `source`, `category`, `type`, `author`, `model`, `date` | `--view`, `--topic`, `--region`, `--category`, `--content-type`, `--model`, `--author`, `--query`, `--product-mentioned` | | `traffic` | `date`, `page`, `model`, `category` | `--traffic-type`, `--provider`, `--category` | | `sentiment` | `prompt` | `--view`, `--prompt`, `--topic` | ```bash theme={null} # Latest product share-of-voice snapshot tpc analytics explore --scope pro-org/my-product --metric sov # Seven-day rolling share-of-voice series tpc analytics explore --scope pro-org/my-product --metric sov --by date --rolling-window 7 --last 30d # Four-week rolling share-of-voice series tpc analytics explore --scope pro-org/my-product --metric sov --by date --granularity week --rolling-window 4 --last 90d # Four-week rolling share of voice grouped by answer engine tpc analytics explore --scope pro-org/my-product --metric sov --by engine --granularity week --rolling-window 4 --last 90d # Industry ranking: every competitor's share of voice, ranked tpc analytics explore --scope pro-org/my-product --metric sov --by competitor --last 30d # Industry ranking within one topic (category ranking) tpc analytics explore --scope pro-org/my-product --metric sov --by competitor --topic # Share-of-voice time series for one prompt tpc analytics explore --scope pro-org/my-product --metric sov --by date --prompt # Citations grouped by source category over the last 90 days tpc analytics explore --scope pro-org/my-product --metric citations --by category --last 90d # Top cited sources sorted by unique conversations tpc analytics explore --scope pro-org/my-product --metric citations --by source --sort-by mentions --top 25 # Weekly AI traffic buckets tpc analytics explore --scope pro-org/my-product --metric traffic --by date --granularity week # Human traffic by page tpc analytics explore --scope pro-org/my-product --metric traffic --by page --traffic-type human # Sentiment per prompt with week-over-week comparison tpc analytics explore --scope pro-org/my-product --metric sentiment --compare wow ``` Date windows default to the last 30 days. Use `--last 7d|30d|90d`, or `--from` and `--to` together to select a range. The flexible `explore` SoV query retains snapshot semantics: omitting `--by` returns only the latest available rolling snapshot, while `--by date` returns one overlapping rolling snapshot per date. `--granularity day|week|month` selects the UTC bucket and `--rolling-window 1..30` controls how many buckets each SOV snapshot contains; they default to `day` and `30`. Custom settings work for product, date, and engine SOV series. SoV `mentions` and `runs` from `explore` are not start-to-end totals, so you must not sum them across dated rows. Use the fixed `tpc analytics sov` command when you need one accumulated date-range value. The response is a generic table: the API returns column metadata alongside flat rows, so every metric renders the same way. Add `--json` to get the machine-readable response for scripting: ```bash theme={null} # Top three competitors as JSON rows tpc analytics explore --scope pro-org/my-product --metric sov --by competitor --top 3 --json | jq '.rows' ``` Filters that do not apply to the chosen metric are rejected with the supported list, so agents and scripts get a correcting error instead of silently wrong data. See `tpc analytics explore --help` for the full flag reference. # Content Source: https://docs.promptingcompany.com/cli/commands/content Create, generate, review, publish, and manage content from the TPC CLI. # Content Manage the full content lifecycle for a product from the terminal: create or generate drafts, work the review queue (approve, reject, revise), publish approved drafts, and edit live pages. Pass `--scope /` to select the product. Every JSON response includes the resolved scope. > [!NOTE] > > `tpc content` replaces the removed `tpc site page` command group. Publishing is gated on review: `create` and `generate` land drafts in the review queue, and `publish` fails with a conflict until the draft is approved. The old ungated `site page update --status published` path no longer exists. ## The lifecycle ``` create / generate → review (approve / reject / revise) → publish ``` The review queue is a list filter: `tpc content list --status pending-review`. ## List content List published pages (default): ```bash theme={null} tpc --scope pro-org/my-product content list ``` Filter the published list (search, path prefix, pagination, sort): ```bash theme={null} tpc --scope pro-org/my-product content list \ --query pricing \ --path-prefix blog/ \ --page 2 --page-size 10 \ --order-by createdAt --order-dir asc ``` List the review queue and other lifecycle states: ```bash theme={null} tpc --scope pro-org/my-product content list --status pending-review tpc --scope pro-org/my-product content list --status generating tpc --scope pro-org/my-product content list --status rejected # includes rejection feedback tpc --scope pro-org/my-product content list --status failed tpc --scope pro-org/my-product content list --status approved ``` `--prompt ` works with every status, including `published` — published pages keep the prompt they were generated from, so you can answer "which prompts have no content yet?": ```bash theme={null} # every published page generated from one prompt tpc --scope pro-org/my-product content list --prompt prompt_123 # the same prompt's drafts still in review tpc --scope pro-org/my-product content list --status pending-review --prompt prompt_123 ``` Published items include a `promptId` field (`null` for manually created pages) and an allowlisted metadata envelope containing the normalized generated content type: ```json theme={null} { "metadata": { "contentType": "decision-guide" } } ``` `metadata.contentType` is available consistently for published pages and review drafts. It is `null` for manual pages and content platforms that do not map to a selectable generation type. Internal generation metadata is not exposed. ## Get one item `get` accepts a draft id or a published document id; the response says which kind answered. ```bash theme={null} tpc --scope pro-org/my-product content get adraft_123 tpc --scope pro-org/my-product content get adoc_123 ``` Both variants include the same normalized `metadata.contentType` field in JSON output. Text output prints it as `Content type: ` when present. You can also read page-specific social metadata: `ogTitle`, `ogDescription`, `ogImage`, `twitterTitle`, `twitterDescription`, and `twitterImage`. Text output labels these Open Graph and Twitter/X; unset values display as `-`. ## Create content Created pages land in the review queue as `pending_review` drafts — they publish only after approval. ```bash theme={null} tpc --scope pro-org/my-product content create \ --slug blog/hello-world \ --title "Hello" \ --content "# Hello" ``` Create from a local markdown file: ```bash theme={null} tpc --scope pro-org/my-product content create \ --slug docs/install \ --title "Install" \ --content-file ./install.md ``` ### Place a page in a view Views contain prompts, not pages. A page appears in a view through the prompt it answers. Link the page to a prompt with `--prompt`, then add that prompt to the view: ```bash theme={null} tpc --scope pro-org/my-product content create \ --slug guides/sso \ --title "SSO guide" \ --content-file ./sso.md \ --prompt tpc view add-prompts "Enterprise" --prompt-id --scope pro-org/my-product ``` The prompt must belong to the same product. Find prompt IDs with `tpc prompts list`. ## Generate content Start the content-generation agent for one or more prompts (Pro plan). Generated drafts land in the review queue. ```bash theme={null} tpc --scope pro-org/my-product content generate --prompt prompt_123 tpc --scope pro-org/my-product content generate \ --prompt prompt_123 --prompt prompt_456 \ --type recommended \ --watch ``` `--watch` polls each draft every 5 seconds until generation completes or fails. Cancel a draft that is still generating (or stuck there after the worker died). This marks it `cancelled` and removes it from the generating queue. A server-side reaper also moves drafts that stay in `generating` for more than six hours to `failed`. ```bash theme={null} tpc --scope pro-org/my-product content cancel adraft_123 tpc --scope pro-org/my-product content list --status failed ``` ## Review the queue Approve one or more drafts (approval queues publishing for publishable content): ```bash theme={null} tpc --scope pro-org/my-product content approve adraft_123 tpc --scope pro-org/my-product content approve adraft_123 adraft_456 ``` Reject with a reason (stored as reviewer feedback, shown in `list --status rejected`): ```bash theme={null} tpc --scope pro-org/my-product content reject adraft_123 --reason "Wrong sources cited" ``` Revise a draft — submit an edited replacement, or send feedback for an agent re-run (Pro plan). Both return the draft to the review queue and clear a prior rejection: ```bash theme={null} tpc --scope pro-org/my-product content revise adraft_123 --content-file ./revised.md tpc --scope pro-org/my-product content revise adraft_123 --feedback "Tighten the intro and cite the pricing page" ``` ## Publish and revert `publish` queues publishing for an approved draft and fails with a conflict when the draft is unapproved: ```bash theme={null} tpc --scope pro-org/my-product content publish adraft_123 ``` `revert` unpublishes the live page and returns the draft to the review queue: ```bash theme={null} tpc --scope pro-org/my-product content revert adraft_123 ``` ## Update a live page Use these optional flags for page-specific social metadata: | Flag | Field | | - | - | | `--og-title` | Open Graph title | | `--og-description` | Open Graph description | | `--og-image` | Open Graph image URL | | `--twitter-title` | Twitter/X title | | `--twitter-description` | Twitter/X description | | `--twitter-image` | Twitter/X image URL | Only supplied fields change. Pass `""` to clear one field; untouched SEO and social values are preserved. These are per-page fields, not Website Settings defaults. Use the review drawer to edit social metadata on drafts. Only the flags you pass are changed. There is no `--status` flag — publishing goes through approve/publish. ```bash theme={null} tpc --scope pro-org/my-product content update adoc_123 --title "Updated title" tpc --scope pro-org/my-product content update adoc_123 --content-file ./page.md ``` Pass an empty string to clear an optional field: ```bash theme={null} tpc --scope pro-org/my-product content update adoc_123 --redirect-url "" ``` Manage domain attachments: ```bash theme={null} tpc --scope pro-org/my-product content update adoc_123 \ --attach-domain-id domain_123 \ --canonical-domain-id domain_123 ``` ## Delete content Soft-deletes a live page (with its linked draft and tracked URL) or deletes an unpublished draft, including drafts still in `generating`: ```bash theme={null} tpc --scope pro-org/my-product content delete adoc_123 tpc --scope pro-org/my-product content delete adoc_123 adraft_456 tpc --scope pro-org/my-product content delete adraft_stuck_generating ``` `delete` is valid on `status: generating`. Use `cancel` when you want to stop generation without hard-deleting the row. Every command also supports `--format json` for scripting: ```bash theme={null} tpc --scope pro-org/my-product content list --status pending-review --format json ``` # Model council Source: https://docs.promptingcompany.com/cli/commands/council Run Model Council snapshots, manage config.yaml, and read or delete results from the TPC CLI. # Model council `tpc council` is the CLI for Model Council. It scores every response for a product, topic, or prompt against the product's question config. You can run a council snapshot, read status and reports, replace the config YAML, and delete completed snapshots. `tpc snapshot` is an alias for `tpc council`. > [!NOTE] > > Product-scoped council commands require `--scope /`. Saving or deleting `config.yaml` requires an admin session. ## Config Get the current YAML: ```bash theme={null} tpc council config get --scope pro-org/my-product tpc council config get --out config.yaml --scope pro-org/my-product ``` Replace it from a file (or stdin): ```bash theme={null} tpc council config set --file config.yaml --scope pro-org/my-product cat config.yaml | tpc council config set --file - --scope pro-org/my-product ``` Edit it in `$VISUAL` or `$EDITOR`: ```bash theme={null} tpc council config edit --scope pro-org/my-product ``` Delete it. `tpc council run` will fail until a new config is uploaded: ```bash theme={null} tpc council config delete --scope pro-org/my-product ``` ## Run Fast mode is on by default (synchronous gateway analysis). Pass `--fast-mode=false` for the batch path. ```bash theme={null} tpc council run --scope pro-org/my-product tpc council run --scope pro-org/my-product --topic tpc council run --prompt --scope pro-org tpc council run --scope pro-org/my-product --from 2025-01-01 --to 2025-04-01 tpc council run --fast-mode=false --scope pro-org/my-product ``` `run` starts the workflow and exits. Council runs can take a long time. Check status with `list`. ## Results ```bash theme={null} tpc council list --scope pro-org/my-product tpc council get --snapshot tpc council report --snapshot tpc --format json council report --snapshot > report.json ``` `report` prints a markdown summary by default (executive summary, tracked signals, suggested actions, and a capped claims table). Use `--format json` for the full payload. The report is only available for snapshots with status `completed`. ## Delete a snapshot There is no API to patch an existing snapshot row. Change the scoring rubric with `tpc council config set`, then run again. Delete a completed or failed snapshot with: ```bash theme={null} tpc council delete --snapshot ``` Snapshots still generating cannot be deleted. ## JSON output ```bash theme={null} tpc --format json council list tpc --format json council config get tpc --format json council get --snapshot ``` # Model Council v2 Source: https://docs.promptingcompany.com/cli/commands/council-v2 Create narrative questions, collect fresh answer batches, and retrieve narrative results with noninteractive commands. # Model Council v2 Use `tpc council-v2` to ask a question, collect model responses, inspect or recluster narratives, assign share directions, and retrieve dashboard data. Every command is noninteractive. ## Prerequisites * Authenticate with a TPC session token, such as one obtained through `tpc auth login` or `tpc auth claim`. Enterprise API keys are not supported. * Model Council v2 must be enabled for your organization. * Pass `--scope /` on every command. You can also pass the product's dashboard URL as the scope. * Use `--format json` to emit one structured result object. Text mode emits indented JSON; CSV is unsupported. ## Agent workflow ### 1. Discover a question (optional) ```bash theme={null} tpc --format json council-v2 questions suggest --scope acme/my-product ``` Returns suggested questions with `text`, `topicId`, and `topicText`. Missing suggestions are generated and cached. You can also supply your own question directly. ### 2. Create the question and start analysis Generate and retain a UUID for this operation before issuing the command. The example UUID below is illustrative; use a new UUID for each new question. ```bash theme={null} tpc --format json council-v2 questions create \ --scope acme/my-product \ --text "Is My Product suitable for enterprise teams?" \ --idempotency-key 8df3413a-4f6a-4f45-96db-6ecc0e6db8f1 ``` Creation starts analysis and exits immediately. The idempotency key becomes the question ID. Retry an interrupted request with the **same key and identical input**, including models, prompts, scheduled iterations, and initial narratives. Reusing a key with different setup returns a conflict. Without a custom prompt set, setup targets 25 generated prompts and uses ChatGPT and Claude. Inspect the dashboard's `phrasings` to confirm the saved prompt set before starting a repeated-run experiment. When selecting a suggestion, also pass `--source generated`, its `--topic-text`, and `--topic` when its `topicId` is non-null. Defaults for custom questions are `--source user`, no topic ID, and `--topic-text "Custom question"`. If the question was saved but analysis could not start, the command prints `status: "saved"`, the question ID, and recovery instructions, then exits with code 1. Recover with: ```bash theme={null} tpc --format json council-v2 questions start --scope acme/my-product ``` `start` also retries incomplete or failed analysis. An already-running workflow is reused; fully processed questions need no new run. #### Advanced question setup Choose models, supply reviewed prompts, set scheduled repetitions, and define initial narratives at creation: ```bash theme={null} tpc --format json council-v2 questions create \ --scope acme/my-product \ --text "Is My Product suitable for enterprise teams?" \ --idempotency-key 8df3413a-4f6a-4f45-96db-6ecc0e6db8f1 \ --models chatgpt,claude,gemini,sonar,deepseek,google-ai-mode \ --scheduled-iterations 3 \ --file setup.json ``` `setup.json`: ```json theme={null} { "selectedPrompts": [ { "text": "Which platforms suit a 500-person engineering team?" }, { "text": "What are the risks of adopting My Product at enterprise scale?" } ], "initialNarratives": [ { "label": "Enterprise ready", "definition": "Claims that the product supports enterprise security and operational needs.", "exclusion": "Claims about individual or small-team use only." }, { "label": "Enterprise limitations", "definition": "Claims that missing capabilities prevent enterprise adoption." } ] } ``` | Flag | Behavior | | - | - | | `--models ` | Comma-separated `chatgpt`, `claude`, `gemini`, `sonar` (Perplexity), `deepseek`, or `google-ai-mode`. Select at least one, without duplicates. Default: `chatgpt,claude`. | | `--scheduled-iterations ` | 1–10 repetitions per prompt per model in scheduled collections. Default: 1. This does not change the initial analysis or manual `collect` iteration count. | | `--file ` | JSON setup, or `-` for stdin. Accepts `answerEngines`, `selectedPrompts`, `scheduledRunIterations`, and `initialNarratives`. | | `--prompt ` | Repeat for exact prompts. Appends to prompts in either input file. | | `--prompts-file ` | Read prompts from JSON, CSV, or plain text; `-` for stdin. Import 1–1,000 prompts. | | `--prompts-format ` | `json`, `csv`, or `text`. Inferred from `.json` / `.csv`; other extensions and stdin default to text. Requires `--prompts-file`. | Files are limited to 1 MB each. Only one file can read stdin. Set models and iterations in either JSON or flags, not both. Supply a prompt file or `selectedPrompts` in the setup file, not both; `--prompt` can append to either. JSON rejects unknown fields. Generated output's `scope` and `dashboardUrl` metadata is accepted; `scope` must match the resolved target product, including when the command uses the legacy product/org scope order. Prompts must be distinct ignoring case and whitespace, and contain 5–2,000 characters. Optional prompt fields are `persona` (up to 200 characters), `situation` (up to 500), and `sourcePromptId` for a prompt from this product's library. Edit or remove entries in `selectedPrompts` before creating the question. Omit `selectedPrompts` to generate the default set. Supply 1–199 initial narratives with unique labels (1–200 characters), definitions (1–2,000), and optional exclusions (up to 2,000). `Others` is reserved for unmatched claims. Supplied narratives classify claims from the first run; omit `initialNarratives` for automatic discovery. Empty arrays are rejected. #### Generate and review prompts ```bash theme={null} tpc --format json council-v2 prompts generate \ --scope acme/my-product \ --text "Is My Product suitable for enterprise teams?" \ --count 10 > prompts.json ``` `--count` accepts 1–100 and defaults to 25. Optional `--topic-text` supplies topic context. This generates a `selectedPrompts` setup file without creating a question or collecting answers. Review and edit it, then pass `--file prompts.json` or `--prompts-file prompts.json` to `questions create`. Retain that file for retries instead of generating a different set under the same idempotency key. An unmeasurable question exits nonzero with the reason. #### Select existing library prompts ```bash theme={null} tpc --format json council-v2 prompts library \ --scope acme/my-product --search enterprise --page 1 ``` Results contain `prompts` (`id`, `text`, `topicId`), `topics`, `page`, and `hasMore`. Use `--topic ` to filter by topic, and increment `--page` while `hasMore` is true. Pages contain up to 25 prompts. Copy chosen entries into your setup file using `text` and `sourcePromptId`: ```json theme={null} { "selectedPrompts": [ { "text": "Which enterprise platform should we choose?", "sourcePromptId": "" } ] } ``` The server checks that each source prompt still belongs to this product and is available. You can edit its selected text without changing the library prompt. #### Import prompts or write them directly Use plain text with one prompt per line, or CSV with exactly one `prompt` header. Quote CSV prompts containing commas or newlines. Blank prompts are skipped; invalid or duplicate prompts reject the whole request. ```bash theme={null} tpc council-v2 questions create --scope acme/my-product \ --text "Is My Product suitable for enterprise teams?" \ --idempotency-key 8df3413a-4f6a-4f45-96db-6ecc0e6db8f1 \ --prompts-file prompts.csv \ --prompt "What would prevent a large company from adopting My Product?" ``` JSON prompt imports use the same `{"selectedPrompts":[...]}` shape as generated output. Use `--file` when the JSON also contains model, iteration, or narrative settings. ### 3. Inspect or wait for analysis ```bash theme={null} tpc --format json council-v2 questions get --scope acme/my-product tpc --format json council-v2 questions watch \ --scope acme/my-product --timeout 5m --interval 3s ``` `get` returns the question's saved setup, current prompts and narratives, processing progress, `state`, and `nextAction`: | Field | Contents | | - | - | | `question.answerEngines` | Selected model IDs; older questions without an explicit selection return the ChatGPT/Claude defaults. | | `question.selectedPrompts` | Originally supplied prompt text and optional persona, situation, and library source ID. `null` when setup used automatic prompt generation. | | `phrasings` | Current saved analysis prompts, each with `id` and `text`. Includes automatically generated prompts once they are saved. | | `question.initialNarratives` | Originally supplied narrative labels, definitions, and exclusions; `null` when setup used automatic narrative discovery. | | `clusters` | Current major narratives with `id`, `label`, `definition`, `exclusion`, `kind`, and `stance`. Excludes Others. | | `question.scheduledRunIterations` | Repetitions per prompt per model for scheduled collections. | | `question.collectionInterval` | Scheduled collection cadence, such as `7d`. | | `question.nextScheduledRunAt` | Next scheduled collection time, or `null`. | | `question.topicId`, `topicText`, `source` | The question's topic and origin. | `phrasings` and `clusters` can be empty while initial setup is still processing. The original `selectedPrompts` and `initialNarratives` remain available before generated rows exist and are distinct from the current prompts and narratives after later edits. `question` also retains status, errors, grouping state, ready/position timestamps, and phrase tracking. For narrative shares and answer evidence, use `narratives list` or `dashboard`. `questions watch` continues to poll the lightweight status response without fetching setup, prompts, or narratives on each iteration. | State | Meaning | Next step | | - | - | - | | `draft` | Saved; processing has not yet started | `questions start` | | `processing` | Generating, collecting, or clustering | `questions watch` | | `awaiting_positions` | Analysis complete; directions need to be assigned | `narratives list`, then `positions set` | | `ready` | Analysis and position selection complete | `dashboard` | | `failed` | Analysis failed or remains incomplete | Inspect progress, then `questions start` | `watch` polls without starting or retrying analysis. It stops at `awaiting_positions`, `ready`, or `failed`. The default timeout is five minutes, measured after authentication and scope resolution; the default polling interval is three seconds, with a minimum of one second. Both flags accept Go durations such as `30s` or `5m`. On timeout, `watch` prints the last observed state with `timedOut: true` and exits with code 1. If no status response arrived, the state is `unknown`. Resume with `get` or another `watch` invocation. ### 4. Inspect narratives and save positions ```bash theme={null} tpc --format json council-v2 narratives list \ --scope acme/my-product --question ``` The response includes current narrative IDs, labels, definitions, shares, and sampled evidence. Unset share directions default to Maintain. Evidence is capped per model; the response includes `evidencePerModelLimit`. Others contains uncategorized claims and is excluded from narrative lists, share calculations, charts, and response coverage. In the dashboard, open the Others section below the narratives to browse its claims. Previously dismissed claims appear in Others and remain excluded from automatic reclustering. An admin can restore a processed claim by moving it to a named narrative. Create a positions file using the returned major narrative IDs: ```json theme={null} { "marks": [ { "clusterId": "", "stance": "mine" }, { "clusterId": "", "stance": "opposing" }, { "clusterId": "", "stance": "neutral" } ] } ``` Stances express the desired share direction: `mine` means **increase**, `opposing` means **reduce**, and `neutral` means **maintain**. Choose directions using the product's goals. ```bash theme={null} tpc --format json council-v2 positions set \ --scope acme/my-product --question --file positions.json tpc --format json council-v2 positions set \ --scope acme/my-product --question --file - < positions.json ``` Submit every current major narrative exactly once, excluding Others. The API saves the set atomically and rejects stale or incomplete sets. If the narrative set changes, fetch it again before retrying. Use `{"marks":[]}` when there are no major narratives. Input is limited to 1 MiB. ### 5. Get the dashboard ```bash theme={null} tpc --format json council-v2 dashboard \ --scope acme/my-product --question tpc --format json council-v2 dashboard \ --scope acme/my-product --question \ --from 2026-09-01 --to 2026-09-27 ``` The result includes narrative shares and evidence, stance breakdown (`framing`), `modelComparison`, top cited URLs, current suggested actions, processing progress, and a `dashboardUrl`. Date filters are inclusive UTC dates and apply to the dashboard's claim and citation data; suggested actions and processing progress describe the current question. Either date boundary can be omitted. Evidence and citation caps are included in the response. Phrase tracking is configured per question in the web dashboard and takes effect on the next collection. `question.phraseTracking` contains the current phrase list, user alternates, and generated grammatical variants. `phraseCounts` contains response-level counts for the selected range: `explicit`, `implicit`, `checked`, `failed`, and a `variants` breakdown. Add `explicit + implicit` for the combined count; alternate counts can overlap. A response is checked implicitly only when no explicit variant matches. Failed implicit checks and older, untracked responses are not counted as absent. Editing a phrase or its alternates starts a new phrase ID, keeping earlier results separate. To get the product question overview, omit `--question`: ```bash theme={null} tpc --format json council-v2 dashboard --scope acme/my-product tpc --format json council-v2 questions list --scope acme/my-product ``` Both return up to 100 active questions, newest first, with their status and summary metrics. Date flags require `--question`. ### 6. Collect a fresh batch (platform admins) After initial processing finishes and you save positions, use `collect` to run the saved prompts again: ```bash theme={null} tpc --format json council-v2 questions collect \ --scope acme/my-product \ --idempotency-key af06d95b-8a5e-4f1e-a3fc-2c3e7893a594 tpc --format json council-v2 questions runs \ --scope acme/my-product --page 1 ``` `collect` requires a **platform-admin session**, rather than just an organization-admin role. It uses the same collection operation as the web app's **Run same prompts** action, reusing the saved prompts, models, and narrative definitions. Your API deployment must support `POST /api/v1/products/{productId}/narrative-split/{questionId}/runs`. Generate and retain a new UUID for each intended batch. **That UUID becomes the collection's run ID.** Retry an interrupted request with the same key to retrieve or resume that same run. The result contains `id`, `questionId`, and a `nextCommand` to inspect history. A completed key returns its original run, even if a different run is now active; a failed collection can be resumed when its configuration still matches and no other run is active. Only one collection can be queued or running per question. A different request while a collection is active returns **HTTP 409 Conflict**, without creating another run. Wait for it to finish, then retry your new request. For sequential experiments, use a new UUID for each iteration and count distinct completed run IDs, not successful command invocations. `collect` returns without waiting. `questions runs` returns up to 20 collections per page, newest first, with status, errors, expected/completed/failed answer counts, `total`, `page`, `pageSize`, and `activeRunId`. Follow pagination to find older IDs. Wait until the returned collection ID has status `completed` before recording its result. **`questions watch` tracks initial analysis, not collection completion.** If collection dispatch fails, inspect history and retry with the same key. ### 7. Read per-run and cumulative results ```bash theme={null} tpc --format json council-v2 dashboard \ --scope acme/my-product --question --run tpc --format json council-v2 dashboard \ --scope acme/my-product --question --run initial tpc --format json council-v2 dashboard \ --scope acme/my-product --question --view all ``` | Flag | Selection | | - | - | | `--run ` | One completed collection; unavailable or unfinished collections return an error. | | `--run initial` | Initial answers through the question's initial ready timestamp. | | `--view latest` | Latest completed collection, falling back to initial answers. This is the default without date filters. | | `--view all` | All historical answers, or the selected date range when combined with `--from` / `--to`. | | `--view auto` | The server's recent-completed-run window; not an all-time cumulative estimate. | These flags require `--question`. `--run` cannot be combined with dates or `--view`; `latest` and `auto` cannot be combined with dates. The response's `selection` describes the chosen scope. Suggested actions and processing progress still describe the current question. For a convergence experiment, save each completed collection's JSON locally and compare its `runSets` prompt and definition fingerprints before pooling results. `--view all` includes scheduled collections and any other answers for the question, so use per-run results when you need exactly your experimental batches. Shares use categorized claims as their denominator; answer coverage is reported separately. Keep the prompt set, model configuration, and narrative definitions unchanged across iterations. ## Recluster saved claims Reclustering replaces the current major narratives and reassigns existing saved claims. It does not collect new answers. New narratives have new IDs and default to Maintain; save positions again after reassignment finishes. Initial analysis must have finished, the question must be ready or failed with an initial ready timestamp, and no answer collection can be active. ### Draft and review definitions Export the current set to refine it, or request a new draft using a prompt: ```bash theme={null} tpc --format json council-v2 recluster draft \ --scope acme/my-product --question > narratives.json tpc --format json council-v2 recluster draft \ --scope acme/my-product --question \ --prompt "Separate cost, privacy, and operational tradeoffs" > narratives.json ``` Drafting does not apply changes. Edit the returned `narratives` array and retain `expectedClusterIds`, which captures the current major narrative IDs **before** draft generation. The output can be passed directly to `start --file` after review. You can also write your own set using this shape: ```json theme={null} { "narratives": [ { "label": "When privacy matters", "definition": "Choose this approach when keeping data private is the main requirement.", "exclusion": "Claims favoring this approach solely for lower costs or faster responses." } ], "expectedClusterIds": [""] } ``` Include every current major narrative ID in `expectedClusterIds`, excluding Others. Use an empty array when there are none. Supply 1–199 narratives with unique labels (1–200 characters, excluding the reserved name Others) and definitions (1–2000 characters). Draft prompts accept 1–10000 characters. Files are limited to 1 MiB. The optional `questionId`, `scope`, and `dashboardUrl` metadata from `draft` is accepted; question and scope metadata must match the command. Each narrative has a title (`label`), a positive direction (`definition`, what to include), and a negative direction (`exclusion`, what to exclude, at most 2000 characters). Exclusions take precedence over inclusion during claim assignment. Generated drafts supply all three. Existing narratives and older files may omit `exclusion` or leave it empty, meaning no additional exclusion. ### Start and inspect reclustering Generate and retain a new UUID for each intended reclustering operation: ```bash theme={null} tpc --format json council-v2 recluster start \ --scope acme/my-product --question \ --request-id 3e77517e-6138-4b83-815f-e6b6b89f92da \ --file narratives.json tpc --format json council-v2 recluster status \ --scope acme/my-product --question \ --request-id 3e77517e-6138-4b83-815f-e6b6b89f92da ``` `--file -` reads reviewed JSON from stdin. Omit `--file` to generate narratives automatically using the default clustering instructions. Platform admins may supply `--metaprompt` (1–20000 characters) for automatic clustering; it cannot be combined with `--file`. Prompt-based drafting and reviewed sets do not require platform-admin access. `start` returns immediately with `requestId` and a request-aware `nextCommand`. Reviewed sets are checked for stale IDs both at submission and before replacement. If the set changed, export and review it again. `--request-id` is a workflow correlation ID, **not a general idempotency guarantee**. After an interrupted submission, inspect status before resubmitting. The API rejects a concurrent workflow; once preparation has applied, the stored request ID prevents that preparation from being repeated while it remains the latest request. Retain identical input when retrying that operation. `status` reads once; poll it with the same request ID: | State | Meaning | | - | - | | `pending` | This request has not been observed as applied or rejected. This does not prove a workflow is running. | | `processing` | This request's definitions have been applied; reassignment is still processing. | | `awaiting_positions` | Reassignment finished; fetch the new IDs with `narratives list`, then save positions. | | `ready` | Reassignment finished and positions have been saved. | | `rejected` | The request was rejected before applying changes, including stale reviews or cancellation. Prints details and exits 1. | | `failed` | The applied request's question is failed. Prints details and exits 1. | The response includes the current question and progress. The API retains only the latest applied request ID and latest rejection, so older or unknown IDs can remain `pending`. Failures before preparation may also remain `pending`; inspect `question.status` and `question.error` rather than polling indefinitely. **Do not use `questions watch` to confirm a new reclustering request:** before preparation, it can still see the previous completed state. ### Stop reclustering ```bash theme={null} tpc --format json council-v2 recluster stop \ --scope acme/my-product --question ``` This targets the question's current reclustering workflow. The CLI returns `status: "stop_requested"` to confirm the API accepted the stop request. It does not confirm that cancellation was enqueued or completed, or that work is still active. Stopping an already-finished workflow is a successful no-op; the API returns the same response for both cases. If work is active, it must drain before another workflow can start. Cancellation does not roll back changes already applied. Inspect the original request with `recluster status` before retrying. ## Agent output and exit codes Results include `scope` and `dashboardUrl`. When another step is available, `nextAction` names the command and `nextCommand` supplies an argv array including the question ID and scope. A positions command contains a `` placeholder that the agent must replace with its authored file path. * **0:** The operation succeeded. `watch` reaching `awaiting_positions` is successful because it needs agent input next. * **1:** Validation, authentication, API, or filesystem error; creation saved but did not start; `recluster status` reports rejection or failure; or `watch` encountered failed analysis, cancellation, or timeout. For creation failures after saving and watch failures after a status response, read the JSON result even when the process exits nonzero. `get` and `dashboard` are reads: inspect their `state` rather than interpreting exit code 0 as analysis completion. # Knowledge Source: https://docs.promptingcompany.com/cli/commands/knowledge List, read, write, move, and delete generated knowledge files from the TPC CLI. # Knowledge Read and write generated knowledge files for a product from the terminal. Pass `--scope /` to select the product. `tpc kb` is an alias for `tpc knowledge`. This first slice covers files only: list, get, put, move, and delete. Proposals, retrieval, ingest, and graph commands are not available yet. > [!NOTE] > > Knowledge commands require [OAuth login](/cli/authentication) (`tpc auth login`). API keys are rejected with an "OAuth login required" error. ## List files Text output is an indented Unix-style tree. JSON output is the API's flat file list. ```bash theme={null} tpc --scope pro-org/my-product knowledge file list ``` ```text theme={null} knowledge/ product/ features.md overview.md sources/ pricing.md ``` Filter to a subtree. The prefix becomes the tree root: ```bash theme={null} tpc --scope pro-org/my-product knowledge file list --path product ``` ```text theme={null} product/ features.md overview.md ``` Scriptable JSON stays flat (no nested tree): ```bash theme={null} tpc --scope pro-org/my-product knowledge file list --format json ``` `--format csv` is not supported. ## Get a file Text mode prints the file content. JSON mode prints the API payload. ```bash theme={null} tpc --scope pro-org/my-product knowledge file get product/overview.md tpc --scope pro-org/my-product knowledge file get product/overview.md --format json ``` ## Write a file `put` creates the file, or replaces it when it already exists. Use either `--content` or `--content-file`. ```bash theme={null} tpc --scope pro-org/my-product knowledge file put product/overview.md \ --content "# Overview" ``` ```bash theme={null} tpc --scope pro-org/my-product knowledge file put product/overview.md \ --content-file ./overview.md ``` Text output prints the resulting path, commit, and repository message. ## Move or archive a file `move` renames a file in one commit. To archive a file, move it under `archive/`. ```bash theme={null} tpc --scope pro-org/my-product knowledge file move entities/old-vendor.md archive/entities/old-vendor.md ``` ## Delete files `delete` removes one or more files in a single commit. Pass paths as arguments, or one per line with `--paths-file` (`-` reads stdin). Blank lines and duplicate paths are ignored, and one call accepts up to 500 paths. ```bash theme={null} tpc --scope pro-org/my-product knowledge file delete entities/junk-a.md entities/junk-b.md ``` ```bash theme={null} grep -l "lorem ipsum" -r ./kb | sed 's|^./kb/||' | \ tpc --scope pro-org/my-product knowledge file delete --paths-file - ``` Text output lists each deleted path, any path that was not found, and the commit. The knowledge schema file cannot be deleted. ## JSON output Every command supports `--format json` for scripting. List JSON is a flat list of files and paths, not a tree. # llms.txt generation Source: https://docs.promptingcompany.com/cli/commands/llmstxt Generate llms.txt files for any site from its sitemap with the TPC CLI. # llms.txt generation Turn a sitemap into one or more [llms.txt](https://llmstxt.org) files in two steps: `tpc llmstxt init` reads the sitemap and writes an editable YAML config that groups pages into sections, and `tpc llmstxt generate` renders that config to disk. Both commands run entirely locally — no authentication, organization, or product scope required. > [!NOTE] > > The YAML config is the source of truth. `init` only gives you a starting point; edit the config freely (rename sections, move pages, split files), then re-run `generate`. `generate` never re-groups or fetches anything. ## Create a config from a sitemap Parse a sitemap and write `llmstxt.yaml`: ```bash theme={null} tpc llmstxt init https://docs.example.com/sitemap.xml ``` `tpc llmstxt ` is shorthand for the same thing (without flags). Nested sitemap indexes are followed up to 5 levels deep and gzipped sitemaps are handled automatically. Pages are grouped into sections by URL path: the CLI strips the path prefix shared by every URL, then groups by the next path segment (`/docs/deployment/aws.html` → a "Deployment" section). Pages at or directly under the shared prefix land in an "Overview" section. Set the root file's header content while initializing: ```bash theme={null} tpc llmstxt init https://docs.example.com/sitemap.xml \ --name "Example" \ --title "Example Docs" \ --description "Docs for agents." \ --details "This index covers the latest release." ``` `--title` renders as the `# ...` heading, `--description` as the `> ...` blockquote, and `--details` as the free-form paragraph before the first section. ## Filter which pages are included Globs match the URL path; `**` spans path segments, `*` matches within one: ```bash theme={null} tpc llmstxt init https://example.com/sitemap.xml \ --include '/docs/**' \ --exclude '/docs/internal/**' ``` Regular expressions (Go syntax) match the full URL: ```bash theme={null} tpc llmstxt init https://docs.example.com/sitemap.xml \ --include-regex '/docs/latest(/|$)' \ --exclude-regex '/docs/(es|fr|ja)(/|$)' ``` When any include rule is present, a URL must match at least one; a URL matching any exclude rule is dropped. Use `--max-urls` (default 5000) to cap how many pages are read from the sitemap. ## Fetch real titles and descriptions By default, link titles are derived from URL slugs. With `--enrich`, the CLI fetches every page (8 concurrent workers) and fills in real metadata: ```bash theme={null} tpc llmstxt init https://docs.example.com/sitemap.xml --enrich ``` Enrichment resolves, in order of precedence: * **Title**: ``, then `og:title` / `twitter:title` * **Description**: `<meta name="description">`, then `og:description` / `twitter:description`, then the first substantial paragraph inside the page's `<main>` content region Descriptions are truncated at 400 characters on a word boundary. Raise or lower that with `--max-description`: ```bash theme={null} tpc llmstxt init https://docs.example.com/sitemap.xml --enrich --max-description 800 ``` The limit counts characters, not bytes, so the budget is the same in every script. Enrichment also chases `<meta http-equiv="refresh">` and HTTP redirects (common on S3-hosted docs whose sitemaps list stale URLs), drops pages that resolve to the same URL as another page, and re-groups sections from the final URLs. Every dropped page is listed with the target it collapsed onto — pass `--no-dedup` to keep them all. Fetch failures are skipped silently, leaving the slug-derived title. > [!NOTE] > > When rewrite rules are configured, enrichment fetches the **rewritten** URL — the link `generate` will actually emit. This matters on sites that redirect old `.html` paths but still serve content at the matching `.md` paths: the emitted links are live and distinct, so they are kept rather than collapsed. Titles and descriptions are read from markdown documents as well as HTML. ## The config file ```yaml theme={null} version: 1 sitemap: https://docs.example.com/sitemap.xml site: name: Example baseUrl: https://docs.example.com urlRewrites: - match: \.html$ replace: .md files: - path: llms.txt title: Example Docs summary: Docs for agents. info: This index covers the latest release. sections: - title: Get Started pages: - url: https://docs.example.com/get-started/quickstart.html title: Quickstart description: Run your first request in five minutes. - file: guides/llms.txt - path: guides/llms.txt title: Example Guides sections: - title: Guides pages: - url: /guides/streaming.html title: Streaming ``` Key rules: * `files` may declare any number of outputs, so one `generate` run can emit a root `llms.txt` plus per-category files. Output paths must be relative, end in `.txt`, and cannot escape the output directory. * A page sets exactly one of `url` (absolute, or relative to `site.baseUrl`) or `file` (the `path` of another entry in `files`, rendered as a link to that generated file — this is how a parent llms.txt links to nested ones). * A page's `description` renders as the `: ...` suffix after the link and is omitted when empty. Sections with no pages are skipped. ## Rewrite URLs `site.urlRewrites` holds ordered regex find/replace rules applied to every resolved page URL at generate time — for example, pointing links at markdown variants by appending `.md`. Capture groups (`$1`, `${name}`) work as in Go's `Regexp.ReplaceAllString`. Seed rules from init with `--rewrite 'PATTERN=>REPLACEMENT'` (repeatable): ```bash theme={null} tpc llmstxt init https://docs.example.com/sitemap.xml --rewrite '\.html$=>.md' ``` For rewrite logic a regex can't express, set `site.urlRewriteCommand` to your own program as an argv list (no shell): ```yaml theme={null} site: urlRewriteCommand: ["python3", "scripts/rewrite-urls.py"] ``` At generate time it runs once, receives every resolved page URL (after `urlRewrites`) on stdin — one per line — and must print exactly one line per input: the rewritten URL, or a blank line to keep it unchanged. Non-zero exits and mismatched line counts are errors. Links produced by `file:` references are never rewritten. ## Generate the files ```bash theme={null} tpc llmstxt generate ``` Write to a specific directory, or preview without writing: ```bash theme={null} tpc llmstxt generate --config docs/llmstxt.yaml --out public tpc llmstxt generate --dry-run ``` Each file renders in standard llms.txt shape: ```markdown theme={null} # Example Docs > Docs for agents. This index covers the latest release. ## Get Started - [Quickstart](https://docs.example.com/get-started/quickstart.md): Run your first request in five minutes. - [Example Guides](https://docs.example.com/guides/llms.txt) ``` Use `--format json` on any llmstxt command for machine-readable output. ## Check every link `doctor` checks any llms.txt document — a local file or a live URL, whether or not this CLI produced it. Every markdown link is extracted and checked over HTTP; anything answering with a transport error or a status of 400 or higher is reported with its section, link title, and line number: ```bash theme={null} tpc llmstxt doctor https://docs.example.com/llms.txt ``` ```text theme={null} BROKEN https://docs.example.com/guides/old-page.md (HTTP 404) https://docs.example.com/llms.txt:14 Guides › Old page Checked 58 links: 57 OK, 1 broken ``` Check generated files before publishing (relative links in local files need `--base-url`; fetched URLs resolve relative links against themselves automatically): ```bash theme={null} tpc llmstxt doctor ./out/llms.txt ./out/guides/llms.txt --base-url https://docs.example.com ``` Links are checked with `HEAD`, falling back to `GET` for servers that reject it, 8 at a time (`--concurrency`). Anchors and `mailto:` links are ignored, and duplicate URLs are checked once. The command exits with code 1 when any link is broken, so you can gate CI or a publish step on it. ## Flags reference ### tpc llmstxt init ```bash theme={null} tpc llmstxt init <sitemap-url> ``` | Flag | Default | Description | | - | - | - | | `--config`, `-c` | `llmstxt.yaml` | Path to write the YAML config. | | `--name` | derived from the sitemap host | Site name used for the config and root file title. | | `--title` | the site name | Root file title (the `# ...` heading). | | `--description` | — | Root file description, rendered as the `> ...` blockquote under the title. | | `--details` | — | Root file details, rendered as free-form text between the description and the first section. | | `--include` | — | Only keep URLs whose path matches this glob (repeatable). `**` spans segments, `*` matches within one. | | `--exclude` | — | Drop URLs whose path matches this glob (repeatable). | | `--include-regex` | — | Only keep URLs matching this Go regular expression, tested against the full URL (repeatable). | | `--exclude-regex` | — | Drop URLs matching this Go regular expression, tested against the full URL (repeatable). | | `--rewrite` | — | URL rewrite rule as `PATTERN=>REPLACEMENT` (Go regex, repeatable), written to `site.urlRewrites` and applied by `generate`. | | `--enrich` | `false` | Fetch each page and fill in real titles and descriptions; chases redirects and dedupes pages that resolve to the same URL. Fetches the rewritten URL when `--rewrite` rules apply. | | `--no-dedup` | `false` | Keep every page during `--enrich`, even when several resolve to the same URL after redirects. | | `--max-description` | `400` | Maximum length, in characters, of descriptions derived during `--enrich`. | | `--max-urls` | `5000` | Maximum number of page URLs to read from the sitemap. | | `--force` | `false` | Overwrite the config file if it already exists. | ### tpc llmstxt generate ```bash theme={null} tpc llmstxt generate ``` | Flag | Default | Description | | - | - | - | | `--config`, `-c` | `llmstxt.yaml` | Path to the YAML config. | | `--out`, `-o` | `.` | Directory to write generated llms.txt files into. | | `--dry-run` | `false` | Print the rendered files to stdout instead of writing them. | ### tpc llmstxt doctor ```bash theme={null} tpc llmstxt doctor <llms.txt file or URL> [more...] ``` | Flag | Default | Description | | - | - | - | | `--base-url` | the input URL, for fetched documents | Absolute URL used to resolve relative links. Required for local files containing relative links. | | `--concurrency` | `8` | Number of links checked in parallel (1–64). | ### Global flags Available on every `tpc` command. | Flag | Default | Description | | - | - | - | | `--format`, `-f` | `text` | Output format for command results and help: `text`, `json`, or `csv`. | | `--api`, `-a` | `https://app.promptingco.com/api/v1` | API base URL for all requests (unused by `llmstxt`, which runs locally). | | `--token`, `-t` | — | Access token for one command invocation (unused by `llmstxt`). | # Organization members Source: https://docs.promptingcompany.com/cli/commands/org-members List, invite, remove, and change roles of organization members from the TPC CLI. # Organization members Manage the members of an organization with `tpc org members`. Every command takes `--scope <org-slug>` and identifies members by email. ```bash theme={null} tpc org members list --scope prompting-co tpc org members list --search dev --page 2 --scope prompting-co tpc org members add dev@acme.com --role admin --scope prompting-co tpc org members remove dev@acme.com --scope prompting-co tpc org members set-role dev@acme.com member --scope prompting-co ``` | Command | What it does | Who can run it | | - | - | - | | `tpc org members list [--search <text>] [--page <n>]` | Prints a table of name, email, role, and join date, 10 members per page. `--format json` prints the members array. | Any member | | `tpc org members add <email> [--role member\|admin\|owner]` | Sends an invitation email, the same as the dashboard invite form. Role defaults to `member`. | Administrators and owners. Only owners can invite with `--role owner`. | | `tpc org members remove <email>` | Removes the member whose email matches exactly (case-insensitive). | Administrators and owners | | `tpc org members set-role <email> <role>` | Changes a member's role to `member`, `admin`, or `owner`. | Administrators and owners | `add` does not add a member directly. The invitee becomes a member only after accepting the invitation from their email. Personal and educational email domains are rejected. `remove` and `set-role` fail with an error when no current member has that email. Server-side rules apply and their messages are shown as returned, for example that only an owner can remove or demote another owner, and that the last owner cannot be removed or demoted. # Personas Source: https://docs.promptingcompany.com/cli/commands/persona List, create, update, and delete product personas from the TPC CLI. # Personas Manage the personas of a product from the terminal. A persona is the user an AI assistant is asked to answer as when a prompt runs; prompts reference personas by ID. Pass `--scope <org-slug>/<product-slug>` to select the product. `tpc personas` is an alias for `tpc persona`. Persona commands work with an [OAuth login](/cli/authentication) (`tpc auth login`) or an API key holding `products:read` (list, get) and `products:write` (create, update, delete). ## List personas Newest first. `--search` filters by name; `--page` is zero-based; `--page-size` defaults to 50. ```bash theme={null} tpc --scope pro-org/my-product persona list tpc --scope pro-org/my-product persona list --search revops ``` ```text theme={null} PRODUCT: my-product PAGE: 1 of 1 ID NAME DESCRIPTION CREATED 4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a RevOps lead Owns CRM hygiene for a 200-seat sales org 2026-09-22 Total: 1 ``` `--format csv` is not supported. ## Get a persona Text mode prints the full description and system prompt. JSON mode prints the API payload. ```bash theme={null} tpc --scope pro-org/my-product persona get 4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a ``` ## Create a persona `--name` and `--description` are required. The system prompt is optional and comes from `--system-prompt` or `--system-prompt-file`, not both. ```bash theme={null} tpc --scope pro-org/my-product persona create \ --name "RevOps lead" \ --description "Owns CRM hygiene for a 200-seat sales org" ``` ```bash theme={null} tpc --scope pro-org/my-product persona create \ --name "Security reviewer" \ --description "Evaluates vendors for SOC 2 fit" \ --system-prompt-file ./security.md ``` Creating is idempotent on name, case-insensitively. If the product already has a persona with that name, the existing persona is returned and text output says so instead of creating a duplicate: ```text theme={null} Created persona RevOps lead (4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a) ``` ```text theme={null} Persona RevOps lead already exists (4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a) ``` ## Update a persona Pass only the fields to change; the rest are left as they are. `--clear-system-prompt` removes the system prompt and cannot be combined with `--system-prompt` or `--system-prompt-file`. ```bash theme={null} tpc --scope pro-org/my-product persona update 4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a \ --description "Owns CRM hygiene and lead routing" ``` ```bash theme={null} tpc --scope pro-org/my-product persona update 4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a \ --clear-system-prompt ``` ## Delete a persona Deleting is a soft delete: prompts that referenced the persona keep their history. ```bash theme={null} tpc --scope pro-org/my-product persona delete 4f2c9a1e-8d3b-4c1a-9e2f-7b6a5d4c3b2a ``` ## JSON output Every command supports `--format json` for scripting. `list` prints `{ "personas": [...], "total": n }` and, when the API sends them, each persona's `promptCount` and `agents` (`requested` or `active`) plus a `personalAgents` count. JSON never includes accounts, Kernel profiles, or connection status. The other commands print the persona object. Text list columns stay ID, NAME, DESCRIPTION, and CREATED. ```bash theme={null} tpc --scope pro-org/my-product persona list --format json | jq '.personas[].id' ``` # Products Source: https://docs.promptingcompany.com/cli/commands/products List products and update a product's name, domain, description, product names (aliases), and product context from the TPC CLI. # Products Product commands are org-scoped. Pass `--scope <org-slug>` and a product slug argument, or `--scope <org-slug>/<product-slug>`. ```bash theme={null} tpc product list --scope pro-org ``` Text output lists each product with its slug and its product names. Pass `--format json` to get the product objects, which include them as `keywords`. ## Update a product ```bash theme={null} tpc product update my-product --scope pro-org --description "Cloud hosting for AI agents" tpc product update my-product --scope pro-org --name "Acme Cloud Platform" --domain acme.com ``` The CLI fetches the product first and changes only the fields you pass. Fields you leave out keep their stored values. You must pass at least one flag. | Flag | Description | | - | - | | `--name` | New product name. | | `--domain` | New website domain. The scheme and path are removed, so `https://acme.com/pricing` is stored as `acme.com`. | | `--description`, `-d` | New description. `--description ""` clears it. | | `--alias` | Adds a product name (alias). Repeat it to add several. | | `--remove-alias` | Removes a product name. Repeat it to remove several. | | `--aliases` | Replaces all product names with a comma-separated list. `--aliases ""` clears them. | | `--positioning` | Sets the product context's core positioning. `--positioning ""` clears it. | | `--differentiator` | Replaces the key differentiators. Repeat it to set several; `--differentiator ""` clears them. | | `--context-file` | JSON file with product context fields to change. See [Product context](#product-context). | ## Product names (aliases) Product names are the **Product name(s)** list in product settings. Share of voice counts an AI answer as mentioning your product when it contains any of these names. If the product is often written in other ways, such as an abbreviation or a different spelling, add those as aliases. ```bash theme={null} # Add aliases tpc product update my-product --scope pro-org --alias "Acme AI Cloud" --alias acmecloud # Remove one tpc product update my-product --scope pro-org --remove-alias "Acme Inc" # Replace the whole list tpc product update my-product --scope pro-org --aliases "Acme Cloud,Acme AI Cloud,acmecloud" ``` When you combine these flags, `--aliases` replaces the list first. Then `--alias` adds names and `--remove-alias` removes them. Matching ignores case, and duplicates are dropped. The first spelling is kept. ## Product context Product context is the positioning, differentiators, personas, and competitors TPC uses when it writes content and runs simulations for the product. Only the fields you pass change; the rest keep their stored values. ```bash theme={null} tpc product update my-product --scope pro-org --positioning "Serverless Postgres for AI agents" tpc product update my-product --scope pro-org --differentiator "Branching in one second" --differentiator "Scale to zero" tpc product update my-product --scope pro-org --context-file context.json ``` `--context-file` accepts these fields. Any other field is rejected before the request is sent. ```json theme={null} { "corePositioning": "Serverless Postgres for AI agents", "keyDifferentiators": ["Branching in one second", "Scale to zero"], "targetPersonas": [ { "name": "Platform engineer", "painPoints": ["Slow test databases"] } ], "competitorsToDisplace": { "legacyStack": ["Amazon RDS"], "newFragmentedStack": ["Supabase"] } } ``` `--positioning` and `--differentiator` override the same fields in the file. The product must already have context from onboarding; otherwise the command fails with "No product context available to update". With `--format json`, a context-only update prints the updated context, and an update that also changes settings prints `{"product": ..., "context": ...}`. # Prompts Source: https://docs.promptingcompany.com/cli/commands/prompts List, create, and review prompts and prompt suggestions from the TPC CLI. # Prompts Manage tracked prompts, topic clusters, and generated prompt suggestions for a product. Pass `--scope <org-slug>/<product-slug>` to select the product. ```bash theme={null} tpc --scope pro-org/my-product prompts list tpc --scope pro-org/my-product prompts topics list tpc --scope pro-org/my-product prompts suggestions list ``` ## Factual accuracy Read the factual accuracy dashboard for an organization with an active or trialing Enterprise plan. Sign in with `tpc auth login`; API keys and OAuth access tokens cannot use these commands. ```bash theme={null} tpc --scope enterprise-org/my-product prompts factual-accuracy summary tpc --scope enterprise-org/my-product prompts factual-accuracy claims --verdicts inaccurate,undetermined --page 1 --page-size 50 tpc --scope enterprise-org/my-product prompts factual-accuracy breakdown --group-by prompt tpc --scope enterprise-org/my-product prompts factual-accuracy breakdown --group-by topic --from 2026-07-01 --to 2026-07-31 --models chatgpt,gemini tpc --scope enterprise-org/my-product prompts factual-accuracy claims --group-by prompt --group-id <prompt-id> --accuracy unknown --format json ``` All three commands accept `--from`, `--to`, `--models`, `--topic` (topic ID), and `--view` (view ID). Dates use UTC days with an inclusive end; the default is the last 30 days and the dashboard limits a range to 366 days. `claims` also supports `--verdicts`, `--accuracy`, `--search`, `--sort-by`, `--sort-order`, `--page`, `--page-size`, and a selected `--group-by` plus `--group-id`. Pages contain at most 100 claims. `breakdown` accepts `--group-by prompt|topic|claim` and returns at most 40 decided groups, with `truncated` indicating additional groups. The accuracy percentage is accurate occurrences divided by accurate plus inaccurate occurrences. Undetermined and pending occurrences are counted separately and excluded from that denominator; `null` means there are no decided occurrences. The claims response includes the dashboard summary, claims, and pagination; claim-list filters do not change the summary, while date, model, topic, view, and selected group do. These commands read existing results and do not start verification. ## Suggestions Suggestions are generated candidates. Approving one creates a tracked prompt and starts conversation queries against the selected answer engines. ``` generate → list / update → approve or reject ``` ### List suggestions ```bash theme={null} tpc --scope pro-org/my-product prompts suggestions list tpc --scope pro-org/my-product prompts suggestions list --topic-id <topic-id> tpc --scope pro-org/my-product prompts suggestions list --view <view-id> tpc --scope pro-org/my-product prompts suggestions list --format json ``` Omitting `--view` returns the unscoped product library. ### Generate suggestions ```bash theme={null} tpc --scope pro-org/my-product prompts suggestions generate tpc --scope pro-org/my-product prompts suggestions generate --topic-id <topic-id> tpc --scope pro-org/my-product prompts suggestions generate --language es ``` Generation replaces the current suggestion library for the selected product or topic. The product must have context available. ### Import Radar prompts ```bash theme={null} tpc --scope pro-org/my-product prompts suggestions import-radar ``` Adds the suggested prompts from the product's Radar topics to the library, skipping prompts that are already tracked or suggested. See [Radar](/cli/commands/radar) to list the topics first. ### Update a suggestion ```bash theme={null} tpc --scope pro-org/my-product prompts suggestions update <id> --message "Updated text" tpc --scope pro-org/my-product prompts suggestions update <id> --engine chatgpt --engine gemini tpc --scope pro-org/my-product prompts suggestions update <id> --persona-id <persona-id> ``` At least one of `--message`, `--engine`, or `--persona-id` is required. These values are used when the suggestion is approved. ### Approve suggestions ```bash theme={null} tpc --scope pro-org/my-product prompts suggestions approve <id> --yes tpc --scope pro-org/my-product prompts suggestions approve <id> <id> --engine chatgpt --yes ``` Approval creates tracked prompts and conversation queries immediately. Adding prompts may change future Share of Voice results. Product-level Share of Voice weights a prompt by how many engines it runs on. Confirm with `--yes`, or type `yes` at the prompt. ### Reject suggestions ```bash theme={null} tpc --scope pro-org/my-product prompts suggestions reject <id> tpc --scope pro-org/my-product prompts suggestions reject <id> --feedback "off topic" ``` ## Tracked prompts ```bash theme={null} tpc --scope pro-org/my-product prompts list tpc --scope pro-org/my-product prompts create --message "What is the best pricing tool?" tpc --scope pro-org/my-product prompts topics list tpc --scope pro-org/my-product prompts delete <prompt-id> tpc --scope pro-org/my-product prompts delete <prompt-id> --force ``` `prompts delete` archives a prompt: it disappears from lists, its history is kept, and the archive can be undone. Prompts with active runs need `--force`, and their runs stop while archived. The CLI cannot permanently delete prompts. ### Pause and resume answer engines ```bash theme={null} tpc --scope pro-org/my-product prompts update <prompt-id> --pause-engine gemini tpc --scope pro-org/my-product prompts update <prompt-id> --pause-engine gemini --pause-engine grok-bot tpc --scope pro-org/my-product prompts update <prompt-id> --resume-engine gemini ``` Pausing an engine stops scheduled runs on it for that prompt and hides it from every dashboard (share of voice, citations, answers) as if you had removed it. Nothing is deleted. Resuming brings the engine back with its full history and schedules it again. The prompt must run on each engine you name. Both flags are repeatable, and an engine cannot appear in both. `tpc prompts get` lists the engines a prompt runs on under `ENGINES` and the paused ones under `PAUSED ENGINES`. `--format json` returns them as `answerEngines` and `pausedAnswerEngines`, on `get`, `list`, and `update`. ## ChatGPT plugin discovery prompts Manage the prompts in a product's ChatGPT plugin discovery lane. These prompts measure which plugins ChatGPT suggests and are separate from the product's tracked prompts. The lane needs an Enterprise plan. ```bash theme={null} tpc --scope pro-org/my-product prompts plugin list tpc --scope pro-org/my-product prompts plugin create --message "Which plugin helps me track AI search visibility?" tpc --scope pro-org/my-product prompts plugin update <prompt-id> --message "Which plugin tracks brand mentions in ChatGPT?" tpc --scope pro-org/my-product prompts plugin delete <prompt-id> ``` `list` shows each prompt's ID, message, runs, suggested runs, and last run. `--format json` returns the API data, including `canEdit`. `create` and `update` take `--message` (up to 500 characters); creating a message that is already in the lane returns the existing prompt. Any member can list. `create`, `update`, and `delete` need an owner or admin role and otherwise fail with `an owner or admin role is required to change plugin discovery prompts`. Sign in with `tpc auth login`; API keys cannot use these commands. ## ChatGPT plugin discovery `tpc plugin` reads how often ChatGPT discovers a product's plugin and sets which plugin ID the product tracks. It measures the runs of the prompts above and needs an Enterprise plan. ```bash theme={null} tpc --scope pro-org/my-product plugin summary tpc --scope pro-org/my-product plugin trend tpc --scope pro-org/my-product plugin ranking tpc --scope pro-org/my-product plugin set <plugin-id> tpc --scope pro-org/my-product plugin clear ``` A run is one ChatGPT answer to a plugin discovery prompt. `summary` shows the plugin ID, measured and search runs, shortlisted runs (the plugin was in the search results ChatGPT considered), the average rank, suggested runs (ChatGPT recommended it in the answer), card shown runs (ChatGPT rendered its install card), and the plugins ChatGPT picked instead. `trend` shows one row per UTC day from the first measured run through today, with the runs for that day and rolling 30-day sums; it is not limited to 30 rows, and a product with no plugin ID set or no runs returns no rows. `ranking` lists the top 10 plugins ChatGPT suggested, ranked by suggested runs, and lists yours separately when it is outside the top 10. `--format json` returns the API data. `set` saves a plugin ID; saving the same ID again keeps the original opt-in date and a different ID restarts it. `clear` stops tracking. `set` and `clear` need an owner or admin role and otherwise fail with `an owner or admin role is required to change the ChatGPT plugin ID`. ## Topic competitive status `--status` switches `prompts topics list` from a plain list to each topic's competitive standing, the same data as the Industry Rankings card. ```bash theme={null} tpc --scope pro-org/my-product prompts topics list --status all tpc --scope pro-org/my-product prompts topics list --status opportunity tpc --scope pro-org/my-product prompts topics list --status winning --json tpc --scope pro-org/my-product prompts topics list --status all --as-of 2026-06-30 --model chatgpt ``` | Status | Meaning | | - | - | | `winning` | Your product leads the topic. | | `contested` | Your product is ranked, but another product leads. | | `opportunity` | The topic has a leader and your product is unranked. | | `unranked` | The topic has no leader yet, usually because it has no ranking data in the window. | | `all` | Every topic. | Each row shows the leader, the leader's share of voice, your rank, and your share of voice. The API filters and pages the topics, so `--page` and `--page-size` (max 100) page through the matching topics only. The header counts always cover every topic. Status covers a trailing 30-day window ending today (UTC). `--as-of <YYYY-MM-DD>` ends the window on an earlier date and cannot be in the future. The window is printed with the results and included in `--json` output. `--view`, `--model`, `--region`, `--as-of`, and `--json` work only with `--status`. `--status` reads analytics data, so an API key needs the `analytics:read` scope as well as `prompts:read`. # Radar Source: https://docs.promptingcompany.com/cli/commands/radar Read Radar topics, trend direction, size, and priority from the TPC CLI. # Radar Read the Radar scope for a product: the topics Radar found, which way each is trending, how big it is, and which priority quadrant it falls in. Radar requires the Enterprise plan. Pass `--scope <org-slug>/<product-slug>` to select the product. ```bash theme={null} tpc radar topics --scope pro-org/my-product tpc radar topics --scope pro-org/my-product --direction rising --sort mentions tpc radar topics --scope pro-org/my-product --priority act_now,keep_covered,watch tpc radar topics --scope pro-org/my-product --format json ``` | Flag | Description | | - | - | | `--direction` | Keep topics trending this way: `rising`, `steady`, `cooling` (declining), or `none`. Repeat the flag or pass a comma-separated list. | | `--priority` | Keep topics in this priority quadrant: `act_now`, `watch`, `keep_covered`, or `park`. Repeat the flag or pass a comma-separated list. | | `--sort` | `relevance` (default, the scope rank), `mentions` (30-day mentions, the bubble size on the scope chart), or `change` (7-day change). | | `--limit` | Return at most this many topics. | Topics come from the Radar scope set: the top topics by relevance shown on the scope chart (20 by default). Filters, sorting, and `--limit` apply within that set. `--format json` also returns each topic's suggested prompts and whether each one is already tracked. ## Import Radar prompts as suggestions ```bash theme={null} tpc prompts suggestions import-radar --scope pro-org/my-product ``` This adds Radar's suggested prompts to the prompt suggestion library, the same import as the trending-prompts banner on the Prompt Creation page. Prompts that are already tracked or already suggested are skipped. Review and approve them with `tpc prompts suggestions list` and `tpc prompts suggestions approve`. # Simulation environments Source: https://docs.promptingcompany.com/cli/commands/simulation-environments Create and configure agent simulation environments from the TPC CLI. # Simulation environment commands Create a simulation environment: ```bash theme={null} tpc sim env create \ --name "My Environment" \ --agent-config '{"harness":"claude","model":"claude-sonnet-4-6"}' ``` Create an environment with task links and schedule: ```bash theme={null} tpc sim env create \ --name "Test Env" \ --agent-config @examples/agent-config.json \ --task-ids task_123,task_456 \ --schedule 7d ``` TPC manages the sandbox provider. The CLI does not accept `sandboxProvider` in agent configuration or portable environment files. # Views Source: https://docs.promptingcompany.com/cli/commands/views List, create, and edit views and the prompts in them from the TPC CLI. # Views A view is a named subset of a product's prompts. Analytics commands take `--view` to report on that subset. Pass `--scope <org-slug>/<product-slug>` to select the product. The CLI does not save an active view. ```bash theme={null} tpc view list --scope pro-org/my-product tpc view get "Enterprise" --scope pro-org/my-product tpc analytics sov --scope pro-org/my-product --view Enterprise ``` `get`, `add-prompts`, and `remove-prompts` take a view ID or the exact view name (case-insensitive). If two views share a name, the CLI lists their IDs and asks you to pick one. ## Create a view ```bash theme={null} tpc view create --name "Enterprise" --scope pro-org/my-product tpc view create --name "Enterprise" --description "Enterprise buyers" --scope pro-org/my-product tpc view create --name "Enterprise" --prompt-id <prompt-id> --prompt-id <prompt-id> --scope pro-org/my-product ``` | Flag | Description | | - | - | | `--name` | Required. Up to 100 characters. | | `--description` | Optional. Up to 500 characters. | | `--prompt-id` | Optional. Prompt from the product in `--scope` to add when the view is created. Repeat the flag or pass a comma-separated list. | ## Add and remove prompts ```bash theme={null} tpc view add-prompts "Enterprise" --prompt-id <prompt-id> --scope pro-org/my-product tpc view add-prompts view_123 --prompt-id <prompt-id>,<prompt-id> --scope pro-org/my-product tpc view remove-prompts "Enterprise" --prompt-id <prompt-id> --scope pro-org/my-product ``` `--prompt-id` is required and can be repeated or comma-separated. Find prompt IDs with `tpc prompts list`. A prompt runs once per answer engine and persona. The dashboard calls each run a conversation query, and views hold those runs. Adding a prompt adds all of its runs. Removing a prompt removes all of its runs from the view but does not delete the prompt. `create` and `add-prompts` fail before changing anything if a prompt ID isn't in the product in `--scope` or has no runs. When adding prompts, runs already in the view are skipped. `remove-prompts` also removes runs of archived prompts that are still in the view. ## JSON output Pass `--format json` for machine-readable output. `create` prints the new view. `add-prompts` and `remove-prompts` print: ```json theme={null} { "viewId": "view_123", "viewName": "Enterprise", "promptIds": ["<prompt-id>"], "conversationQueryIds": ["<conversation-query-id>", "<conversation-query-id>"], "addedCount": 2, "removedCount": 0 } ``` # Installation Source: https://docs.promptingcompany.com/cli/installation Install, update, and pin versions of the TPC CLI on macOS, Linux, and Windows. # Installation ## macOS and Linux Install the latest stable release: ```bash theme={null} curl -fsSL https://cli.promptingco.com/install.sh | bash ``` After install, confirm the binary is available: ```bash theme={null} tpc --version ``` ## Windows Install with winget: ```powershell theme={null} winget install promptingcompany.tpc ``` Or install with Scoop after adding The Prompting Company bucket: ```powershell theme={null} scoop bucket add promptingcompany https://github.com/promptingcompany/scoop-bucket scoop install tpc ``` PowerShell is also supported: ```powershell theme={null} irm https://cli.promptingco.com/install.ps1 | iex ``` If your execution policy blocks the installer, run this first in the same PowerShell session: ```powershell theme={null} Set-ExecutionPolicy -Scope Process Bypass ``` Manual fallback: 1. Download the latest `tpc_<version>_windows_amd64.zip` or `tpc_<version>_windows_arm64.zip` from `https://cli.promptingco.com/tpc/<version>/`. 2. Extract `tpc.exe`. 3. Move `tpc.exe` to a directory on `PATH`, or add the new directory to `PATH` through System Properties -> Environment Variables -> Path. 4. Open a new PowerShell or cmd session, then verify the install: ```powershell theme={null} tpc --version ``` ## Update Check whether a newer CLI build is available: ```bash theme={null} tpc update --check ``` Upgrade the installed binary in place: ```bash theme={null} tpc update ``` ## Install a specific version Install a pinned version: ```bash theme={null} curl -fsSL https://cli.promptingco.com/install.sh | TPC_VERSION=0.1.0-alpha.1 bash ``` Install from a release channel: ```bash theme={null} curl -fsSL https://cli.promptingco.com/install.sh | TPC_CHANNEL=alpha bash ``` > [!NOTE] > > Putting the variable before `curl` (`TPC_VERSION=... curl ... | bash`) does not work — that assignment only applies to `curl`'s environment, not to the `bash` process reading the script on the other side of the pipe. The variable has to sit right before `bash`. ## Installer URL The public installer is served from: ```text theme={null} https://cli.promptingco.com/install.sh https://cli.promptingco.com/install.ps1 ``` # Organizations Source: https://docs.promptingcompany.com/cli/organizations List organizations, manage members, and pass --scope on TPC CLI commands. # Organizations List organizations available to your account: ```bash theme={null} tpc org list ``` The CLI does not save an active organization or product. Pass `--scope` on every org- or product-scoped command: ```bash theme={null} tpc product list --scope prompting-co tpc sim experiment list --scope cloudflare-dev/browser-run tpc analytics sov --scope nvidia-com/nvidia-dgx-spark --last 30d ``` Format is `<org-slug>/<product-slug>`, the same order as dashboard URLs (`https://app.promptingco.com/<org-slug>/p/<product-slug>/...`). You can paste that URL as `--scope`. Org-only commands may omit the product: `--scope <org-slug>`. The older `<product-slug>/<org-slug>` order still works for a transition period and prints a warning. `--scope` is a persistent flag, so it works before or after the subcommand — `tpc --scope pro-org/my-product content list` and `tpc content list --scope pro-org/my-product` are equivalent. Commands that disable Cobra flag parsing (`tpc alpha …`) still accept `--scope` before the subcommand. ## Manage members Manage organization members with `tpc org members`. See the [members command reference](/cli/commands/org-members) for every subcommand, flag, and default. ```bash theme={null} tpc org members list --scope prompting-co tpc org members add dev@acme.com --role admin --scope prompting-co ``` # CLI overview Source: https://docs.promptingcompany.com/cli/overview Terminal access to your workspace, organizations, and simulation workflows. # CLI overview The Prompting Company CLI gives you terminal access to your workspace, organizations, and simulation workflows. The binary name is: ```text theme={null} tpc ``` ## Prerequisites * macOS, Linux, or Windows * `amd64` or `arm64` Start with [Installation](/cli/installation), then [Authentication](/cli/authentication). ## Common commands ```bash theme={null} # Show current auth state tpc auth whoami # Show installed CLI version tpc version tpc --version # Check for updates tpc update --check # Install latest update tpc update # List organizations tpc org list # List and invite organization members tpc org members list --scope prompting-co # Product-scoped commands take --scope <org-slug>/<product-slug> tpc sim experiment list --scope cloudflare-dev/browser-run tpc analytics sov --scope nvidia-com/nvidia-dgx-spark --last 30d # Add product names (aliases) used for share of voice tpc product update my-product --scope prompting-co --alias "Acme AI Cloud" # Generate a one-page weekly performance PDF tpc analytics report --scope prompting-co/my-product --week 2026-07-13 # List content tpc --scope prompting-co/my-product content list # List knowledge files tpc --scope prompting-co/my-product knowledge file list # Review generated prompt suggestions tpc --scope prompting-co/my-product prompts suggestions list tpc --scope prompting-co/my-product prompts suggestions generate # List ChatGPT plugin discovery prompts (Enterprise) tpc --scope prompting-co/my-product prompts plugin list # Read ChatGPT plugin discovery and set the tracked plugin ID (Enterprise) tpc --scope prompting-co/my-product plugin summary tpc --scope prompting-co/my-product plugin set <plugin-id> # Read factual accuracy dashboard results (Enterprise) tpc --scope prompting-co/my-product prompts factual-accuracy summary tpc --scope prompting-co/my-product prompts factual-accuracy breakdown --group-by prompt # List rising Radar topics by size and import Radar prompts as suggestions tpc radar topics --scope prompting-co/my-product --direction rising --sort mentions tpc --scope prompting-co/my-product prompts suggestions import-radar # Create a view and add prompts to it tpc view create --name "Enterprise" --prompt-id <prompt-id> --scope prompting-co/my-product tpc view add-prompts "Enterprise" --prompt-id <prompt-id> --scope prompting-co/my-product # Add a persona for prompts to run as tpc --scope prompting-co/my-product persona create --name "RevOps lead" --description "Owns CRM hygiene" # Generate llms.txt files from a sitemap (no auth required) tpc llmstxt init https://docs.example.com/sitemap.xml tpc llmstxt generate # Show simulation command help tpc sim help # Start guided competitive benchmark setup tpc sim ax setup --type benchmark --scope acme/my-product # Show environment list help without requiring auth tpc env list -h # List simulation environments tpc env list # Model Council config and runs tpc council config get tpc council run tpc council list # Model Council v2 questions and dashboard tpc --format json council-v2 questions suggest --scope acme/my-product tpc --format json council-v2 prompts generate --scope acme/my-product --text "Is My Product enterprise ready?" --count 10 tpc --format json council-v2 prompts library --scope acme/my-product --search enterprise tpc --format json council-v2 dashboard --scope acme/my-product tpc --format json council-v2 questions runs <question-id> --scope acme/my-product tpc --format json council-v2 recluster draft --scope acme/my-product --question <question-id> tpc --format json council-v2 dashboard --scope acme/my-product --question <question-id> --run <run-id> ``` ## Next step Once installed and authenticated, you can move into product and simulation workflows from the terminal. See [Products](/cli/commands/products), [Content](/cli/commands/content), [Knowledge](/cli/commands/knowledge), [Prompts](/cli/commands/prompts), [Radar](/cli/commands/radar), [Views](/cli/commands/views), [Personas](/cli/commands/persona), [Analytics](/cli/commands/analytics), [Model council](/cli/commands/council), [Model Council v2](/cli/commands/council-v2), [Agent Experience](/cli/commands/agent-experience), and [Simulation environments](/cli/commands/simulation-environments). # Competitive position across topics Source: https://docs.promptingcompany.com/cli/recipes/competitive-position-by-topic Find your industry ranking in every tracked topic with the TPC CLI. # Competitive position across topics The dashboard's Industry rankings widget shows your top-mentioned competitors across all of your tracked conversations. Sometimes you want the finer-grained view: for each topic you track, where do you actually rank? This recipe uses [`tpc analytics sov`](/cli/commands/analytics) to answer that in one script. No dashboard clicking required. ## Prerequisites * The CLI installed and authenticated. See [Installation](/cli/installation) and [Authentication](/cli/authentication). * `--scope <org-slug>/<product-slug>` for the product you want to check. * [`jq`](https://jqlang.org) installed locally. ## The script Each topic requires its own ranking lookup, so this runs them concurrently instead of one at a time. Each result is captured to a temp file so parallel output doesn't interleave, then printed back in the original topic order. ```bash theme={null} #!/usr/bin/env bash set -euo pipefail SCOPE="${SCOPE:?set SCOPE to <org-slug>/<product-slug>}" ORG="${SCOPE%%/*}" SLUG="${SCOPE##*/}" YOUR_PRODUCT=$(tpc --format json product list --scope "$ORG" \ | jq -r --arg slug "$SLUG" '.[] | select(.slug == $slug) | .name') if [ -z "$YOUR_PRODUCT" ]; then echo "product $SLUG was not found in org $ORG" >&2 exit 1 fi tmpdir=$(mktemp -d) trap 'rm -rf "$tmpdir"' EXIT check_topic() { local topic_id="$1" topic="$2" local you you=$(tpc analytics sov --scope "$SCOPE" --by competitor --topic "$topic_id" --top 100 --json \ | jq -r --arg name "$YOUR_PRODUCT" '.[] | select(.label == $name) | "\(.rank)\t\(.sov)"') if [ -n "$you" ]; then local rank sov rank=$(echo "$you" | cut -f1) sov=$(echo "$you" | cut -f2) printf "%-14s rank #%-4s sov %s%%\n" "$topic" "$rank" "$sov" else printf "%-14s not in top 100\n" "$topic" fi } topic_ids=() while IFS=$'\t' read -r topic_id topic; do topic_ids+=("$topic_id") check_topic "$topic_id" "$topic" > "$tmpdir/$topic_id" & done < <(tpc analytics sov --scope "$SCOPE" --by topic --json | jq -r '.[] | [.key, .label] | @tsv') wait for topic_id in "${topic_ids[@]}"; do cat "$tmpdir/$topic_id" done ``` Run it: ```bash theme={null} chmod +x competitive-position.sh ./competitive-position.sh ``` Example output: ```text theme={null} comparison rank #1 sov 58.8% feature rank #2 sov 42.4% use-case rank #3 sov 36.0% budget rank #2 sov 34.2% industry rank #22 sov 18.0% ``` ## How it works 1. `$SCOPE` is `<org-slug>/<product-slug>`. The script takes the org from the first segment (`ORG="${SCOPE%%/*}"`) and the product slug from the second (`SLUG="${SCOPE##*/}"`), lists products in that org, and uses the matching product's display name, which is what ranking rows use as `label`. 2. `tpc analytics sov --scope "$SCOPE" --by topic` lists every topic you track, with each topic's ID (`key`) and name (`label`). 3. For each topic, a background `check_topic` call runs `tpc analytics sov --scope "$SCOPE" --by competitor --topic <topicId>`. This is the same ranking view as the dashboard's Industry rankings widget, but scoped to one topic instead of everything. All topics are looked up concurrently instead of waiting on each one in turn. 4. `jq` picks out the row matching your product's display name and writes its rank and share of voice to that topic's temp file. 5. `wait` blocks until every background lookup finishes, then the results are printed back in the original topic order (not finish order). > [!NOTE] > > The speedup scales with how many topics you track. With a handful of topics, most of the wall-clock time is per-invocation overhead (auth and org resolution), so parallelizing saves less than you'd expect. With dozens of topics, running them concurrently instead of sequentially is the difference between minutes and seconds. > [!NOTE] > > `--top 100` is the highest page size the fixed command allows. If a topic has more than 100 tracked competitors and you don't show up, use `tpc analytics explore --scope "$SCOPE" --metric sov --by competitor --topic <topicId> --page 2` rather than assuming you're unranked. ## Variations Just want the overall ranking, not broken out by topic? ```bash theme={null} tpc analytics sov --scope <org-slug>/<product-slug> --by competitor --last 30d ``` Want the raw JSON for a dashboard or Slack digest instead of a formatted table? Drop the `printf` lines and pipe the `jq` output directly. Every command in this recipe supports `--json`. Only care about a couple of topics? Skip the topic-listing step and hardcode the topic IDs you already know: ```bash theme={null} tpc analytics sov --scope "$SCOPE" --by competitor --topic <topicId> ``` ## Show competitors around your rank Knowing your rank and share of voice in a topic is useful, but it doesn't say who you're actually competing against right at that position. This script takes one topic and shows the competitors ranked immediately above and below you, reusing the exact same `tpc analytics sov --by competitor --topic` response as the main script above. Every competitor's rank is already in that one call, so no extra API request is needed. ```bash theme={null} #!/usr/bin/env bash set -euo pipefail TOPIC_ID="$1" WINDOW="${2:-2}" SCOPE="${SCOPE:?set SCOPE to <org-slug>/<product-slug>}" ORG="${SCOPE%%/*}" SLUG="${SCOPE##*/}" YOUR_PRODUCT=$(tpc --format json product list --scope "$ORG" \ | jq -r --arg slug "$SLUG" '.[] | select(.slug == $slug) | .name') if [ -z "$YOUR_PRODUCT" ]; then echo "product $SLUG was not found in org $ORG" >&2 exit 1 fi rows=$(tpc analytics sov --scope "$SCOPE" --by competitor --topic "$TOPIC_ID" --top 100 --json \ | jq -r --arg name "$YOUR_PRODUCT" --argjson window "$WINDOW" ' . as $rows | ($rows | map(.label) | index($name)) as $idx | if $idx == null then empty else $rows[(if $idx - $window < 0 then 0 else $idx - $window end):($idx + $window + 1)][] | [.rank, .label, .sov, (if .label == $name then "you" else "" end)] | @tsv end ') if [ -z "$rows" ]; then echo "$YOUR_PRODUCT is not in the top 100 for this topic" exit 0 fi echo "$rows" | while IFS=$'\t' read -r rank label sov marker; do if [ "$marker" = "you" ]; then printf "%-4s %-20s %s%% <-- you\n" "$rank" "$label" "$sov" else printf "%-4s %-20s %s%%\n" "$rank" "$label" "$sov" fi done ``` Run it with a topic ID (get one from `tpc analytics sov --scope <org-slug>/<product-slug> --by topic --json`, or from the topic-listing step of the script above): ```bash theme={null} chmod +x competitors-around-rank.sh ./competitors-around-rank.sh a8bbcb6f-1ee3-462b-98f1-abe8e05e5437 ``` Example output: ```text theme={null} 19 MongoDB 21.15% 20 Cassandra 19.23% 21 Planetscale 19.23% <-- you 22 AlloyDB 17.31% 23 ClickHouse 17.31% ``` Pass a second argument to widen or narrow the window (default is 2 rows on each side): ```bash theme={null} ./competitors-around-rank.sh a8bbcb6f-1ee3-462b-98f1-abe8e05e5437 5 ``` > [!NOTE] > > If you're ranked #1 (or near the bottom of the tracked list) in a topic, the window just clamps to whatever rows exist in that direction. You'll see fewer neighbors on that side, not an error. ## All topics, with competitors around your rank Combines both scripts above: loop every topic concurrently (like [the first script](#the-script)), but show the window of competitors around your rank in each one (like the one above) instead of just your own row. It keeps the same parallel-lookup structure, with background jobs writing to per-topic temp files and replaying them in original order, but includes more rows per topic. ```bash theme={null} #!/usr/bin/env bash set -euo pipefail WINDOW="${1:-2}" SCOPE="${SCOPE:?set SCOPE to <org-slug>/<product-slug>}" ORG="${SCOPE%%/*}" SLUG="${SCOPE##*/}" YOUR_PRODUCT=$(tpc --format json product list --scope "$ORG" \ | jq -r --arg slug "$SLUG" '.[] | select(.slug == $slug) | .name') if [ -z "$YOUR_PRODUCT" ]; then echo "product $SLUG was not found in org $ORG" >&2 exit 1 fi tmpdir=$(mktemp -d) trap 'rm -rf "$tmpdir"' EXIT check_topic() { local topic_id="$1" topic="$2" local rows rows=$(tpc analytics sov --scope "$SCOPE" --by competitor --topic "$topic_id" --top 100 --json \ | jq -r --arg name "$YOUR_PRODUCT" --argjson window "$WINDOW" ' . as $rows | ($rows | map(.label) | index($name)) as $idx | if $idx == null then empty else $rows[(if $idx - $window < 0 then 0 else $idx - $window end):($idx + $window + 1)][] | [.rank, .label, .sov, (if .label == $name then "you" else "" end)] | @tsv end ') echo "$topic" if [ -z "$rows" ]; then printf " %s not in top 100\n" "$YOUR_PRODUCT" else echo "$rows" | while IFS=$'\t' read -r rank label sov marker; do if [ "$marker" = "you" ]; then printf " %-4s %-20s %s%% <-- you\n" "$rank" "$label" "$sov" else printf " %-4s %-20s %s%%\n" "$rank" "$label" "$sov" fi done fi echo } topic_ids=() while IFS=$'\t' read -r topic_id topic; do topic_ids+=("$topic_id") check_topic "$topic_id" "$topic" > "$tmpdir/$topic_id" & done < <(tpc analytics sov --scope "$SCOPE" --by topic --json | jq -r '.[] | [.key, .label] | @tsv') wait for topic_id in "${topic_ids[@]}"; do cat "$tmpdir/$topic_id" done ``` Run it: ```bash theme={null} chmod +x competitive-position-with-window.sh ./competitive-position-with-window.sh ``` Pass a window size as the first argument (default 2): ```bash theme={null} ./competitive-position-with-window.sh 5 ``` Example output: ```text theme={null} comparison 1 Planetscale 58.82% <-- you 2 Vitess 47.06% 3 MySQL 44.12% feature 1 PostgreSQL 45.45% 2 Planetscale 42.42% <-- you 3 MySQL 42.42% 4 Google Cloud Spanner 33.33% use-case 1 Amazon Aurora 38% 2 Redis 38% 3 Planetscale 36% <-- you 4 Google Cloud Spanner 34% 5 AWS 34% budget 1 PostgreSQL 34.15% 2 Planetscale 34.15% <-- you 3 Google Cloud SQL 31.71% 4 Neon 31.71% industry 19 MongoDB 21.15% 20 Cassandra 19.23% 21 Planetscale 19.23% <-- you 22 AlloyDB 17.31% 23 ClickHouse 17.31% ``` > [!NOTE] > > Firing one concurrent request per topic can occasionally trip the API's rate limit (`429 Too many requests`) if you're re-running the script repeatedly in quick succession, for example while iterating on it. Wait a few seconds and retry. It's a rate limit on request volume, not a problem with your data or account. # Troubleshooting Source: https://docs.promptingcompany.com/cli/troubleshooting Fix common TPC CLI install, login, and update problems. # Troubleshooting ## `tpc` command not found * Open a new shell after installation. * Check whether the installer added the binary directory to your `PATH`. * Run the installer again and watch for shell profile update instructions. * On Windows, `PATH` changes only apply to new PowerShell or cmd sessions. ## Login completes in the browser but CLI does not update * Retry `tpc auth login` * complete the device flow in the same machine where the CLI is running * check whether your browser blocked the callback or redirected into a stale session ## Experiment not found, but the experiment exists The experiment is probably in a different organization or product than `--scope` on the command. The CLI does not save org or product in `~/.tpc/config.json`. Pass `--scope <org-slug>/<product-slug>` on the command: ```bash theme={null} tpc sim experiment get <experiment-id> --scope <org-slug>/<product-slug> tpc sim experiment run <experiment-id> --scope <org-slug>/<product-slug> ``` ## Update does not find a release * run `tpc update --check` * confirm you are on the expected channel or pinned version * if you installed a prerelease, make sure that prerelease metadata exists # Add prompts Source: https://docs.promptingcompany.com/guides/add-prompts Add and manage prompts to track if your product gets mentioned in AI responses Prompts are the questions you want your product to be found for. We run them on models like ChatGPT and Perplexity to see how your product gets mentioned in responses. [YouTube video player](https://www.youtube.com/embed/aFZmCK5Dnhk) ## Prompt suggestions Every day you get 10 new prompts based on your product and website. Our AI finds real questions that are already driving traffic. Open the Prompts tab in the sidebar and click Add prompts. Under Select from suggested prompts, thumbs up the ones you want to track and thumbs down the rest. When you thumbs down, give a reason so our AI can learn. Examples of the kind of questions we surface: * How do startups manage cash, runway, and spend in one place? * What is the best business banking platform for startups? * Is there a single platform to manage startup banking, cards, and payments? ## Add prompts manually To add your own prompts from scratch, use Write new prompts. #### 1. Make prompts tool-seeking Each prompt should ask for a tool, app, or platform, not just for an answer. When the question asks for a recommendation, the model is more likely to suggest a product. * Good: "What tool can help startups manage cash, runway, and spend in one place?" or "Is there a platform that helps me manage startup banking, cards, and payments?" * Avoid: "How do startups manage cash, runway, and spend in one place?" The model will answer but usually won't suggest a product. We want to show up in tool-seeking questions. #### 2. Design for the follow-up Prompts are the types of questions where you want your product to be recommended. You're not telling users what to ask. In practice, people often ask a broad question first, then follow up by asking for a tool. That second question is where your product should show up. A typical flow: * The user asks something broad (for example, how startups manage cash and spend). * They follow up: "Is there a tool that can help?" * Your product should be recommended at that second step. Write prompts for that moment. # Integration with Cloudflare Source: https://docs.promptingcompany.com/guides/analytics/cf-integration Track page visits at the edge by deploying a Cloudflare Worker that forwards page_visit events to The Prompting Company The Cloudflare Worker collector tracks page visits **at the edge**, before requests reach your origin. The worker sits in front of your existing site, transparently proxies every matching request, and forwards page visit events to The Prompting Company — without changing your origin server or adding any client-side JavaScript. This guide will walk through how to set up the Cloudflare Worker with your deployment. ## How it works The worker attaches to one or more routes and acts as a pass-through proxy: 1. A visitor requests a page that matches a configured route (for example, `example.com/*`). 2. The worker forwards the original request to your origin and returns the response immediately. 3. In parallel, the worker sends a page visit event to The Prompting Company. This happens in the background, so it never delays the response to the visitor. ## Before you start You will need: * A **Cloudflare account** with the domain you want to track added as a zone. * A **TPC API key** with the `analytics:write` scope. You can create an API key with the `analytics:write` scope going to your Organization Settings, then selecting API Keys. Note that creating an API key requires an account with the Enterprise Plan. * The `cf-collector` folder from the [samples repository](https://github.com/promptingcompany/samples/) ## Step 1: Install dependencies From the `cf-collector` directory, install the dependencies: ```bash theme={null} npm ci ``` ## Step 2: Set your API key The API key is stored as an encrypted [Wrangler secret](https://developers.cloudflare.com/workers/configuration/secrets/), not in the config file. Set it by running: ```bash theme={null} npx wrangler secret put TPC_API_KEY ``` Paste your key when prompted. > [!WARNING] > > Never commit your API key or place it in `wrangler.jsonc`. Always store it as a secret. ## Step 3: Configure your routes Edit the `routes` array in `wrangler.jsonc` to match the pages you want to track. Set the `pattern` to your domain and the `zone_name` to the matching Cloudflare zone: ```jsonc wrangler.jsonc theme={null} { "routes": [ { "pattern": "example.com/*", "zone_name": "example.com" } ] } ``` You can add more entries to the array to track additional domains or path patterns. ## Step 4: Deploy To deploy the worker to Cloudflare, run: ```bash theme={null} npm run wrangler:deploy ``` Once deployed, Cloudflare routes all traffic matching your patterns through the worker, and page visits should begin appearing in your analytics page. ## Troubleshooting ### Events are not appearing * Confirm the request URL matches a `pattern` in your `routes` array, including the correct `zone_name`. * Make sure the `TPC_API_KEY` secret is set for the environment you deployed to (`npx wrangler secret list`). * Verify the worker is deployed and bound to the route in the Cloudflare dashboard under **Workers & Pages**. ### Inspect live logs Stream logs from the deployed worker to see event delivery and any errors in real time: ```bash theme={null} npm run tail ``` # Export AI crawler traffic from Cloudflare Source: https://docs.promptingcompany.com/guides/analytics/cf-traffic-export Pull AI agent and crawler traffic for your Cloudflare-proxied domain into a CSV to share with The Prompting Company Pull AI agent and crawler traffic for your Cloudflare-proxied domain into a CSV to share with The Prompting Company. The [AI traffic](/guides/metrics#ai-traffic) metric visualizes AI hits on your **custom domain** in real time. If you want AI crawler traffic for a domain that isn't wired into TPC yet — or a history of traffic from before you connected — you can pull it directly from Cloudflare's GraphQL Analytics API instead. For a continuous stream rather than a one-off export, see [Cloudflare Logpush](/guides/analytics/log-exporters/cloudflare-logpush) or the [raw events API](/guides/analytics/log-exporters/raw-events). This guide walks through exporting traffic from AI crawlers and agents (ChatGPT, GPTBot, OAI SearchBot, Claude, Perplexity, Applebot, Amazonbot, Meta, Bytespider, DuckAssistBot, MistralAI, and others) into a CSV with `date_range`, `path`, `host`, `userAgent`, and `requests` columns. ## Before you start * Your domain must be **proxied through Cloudflare** (the DNS record's cloud icon is orange, not grey). * You need **Super Administrator** or **Administrator** access on the Cloudflare account to create an API token for method 1. * You need **Permission group: "Analytics Read"** policy access on the Cloudflare account to create an API token for method 2. * You need `python3` installed — run `python3 --version` to check. ## Part 1: Create a Cloudflare API token Both Account API Tokens and User API Tokens work with the GraphQL Analytics API. Choose based on your situation: | | Account API Token | User API Token | | - | - | - | | **Location** | Manage Account → Account API Tokens | My Profile → API Tokens | | **Best for** | Team setups, automation, service scripts | Individual one-off exports | | **Ownership** | Belongs to the Cloudflare account | Tied to your personal user account | | **Durability** | Keeps working if an individual user leaves | Stops working if your user account is removed | ### Step 1: Log in to Cloudflare Log in to the Cloudflare dashboard. Then follow **one** of the two methods below. ### Method 1: Account API Token 1. In the left sidebar, click **Manage Account**. 2. Click **Account API Tokens** (or go to `https://dash.cloudflare.com/{Account ID}/api-tokens`). 3. Click **Create Token**. 4. Name the token something like `AI traffic GraphQL read`. 5. The Permission policies section should default to custom scope at the account level. Add the first policy: * **Analytics & Logs → Account Analytics → Read** 6. Click **+ Add policy** to add a zone-level policy with: * **DNS & Zones → Zone → Read** * **Analytics & Logs → Zone Analytics → Read** 7. Click **Review Token**, then **Create Token**. 8. Copy the token somewhere safe. ### Method 2: User API Token 1. Go to your domain's overview, scroll down to the API section, and click **Get your API token** (or go to `https://dash.cloudflare.com/profile/api-tokens`). 2. Click **+ Create Token**. 3. Click **Get started** next to "Create Custom Token". 4. Add a token name (e.g. `AI traffic GraphQL read`). 5. For permission 1: **Account → Account Analytics → Read**. 6. Click **Add more**. For permission 2: **Zone → Zone → Read**. 7. Click **Add more**. For permission 3: **Zone → Zone Analytics → Read**. 8. Scroll down to **Zone Resources** and set it to: Include → Specific zone → `yourdomain.com`. 9. Optionally set a TTL for when the token expires. 10. Click **Continue to summary**, then **Create Token**. 11. Copy the token somewhere safe. > [!WARNING] > > Treat this token like a password — anyone with it can read your account's analytics. Don't share it or commit it anywhere public. ## Part 2: Get your Zone ID 1. In Cloudflare, go to **Websites** and click your domain. 2. Go to **Overview**. 3. On the right side, find **Zone ID** and copy it. You'll use this in the query below. ## Part 3: Open Cloudflare GraphQL Explorer 1. Open [https://graphql.cloudflare.com/explorer](https://graphql.cloudflare.com/explorer). 2. Grant access when prompted and review the permissions. 3. Paste your API token into the **API Token** field and click **Save**. ## Part 4: Run the query Cloudflare limits each `httpRequestsAdaptiveGroups` block to a **24-hour window**, and how far back you can query depends on your Cloudflare plan (Free and Pro plans typically only expose the last several days). Check how many days of history your plan provides before picking a date range. If you'd rather not pick dates by hand at all, skip ahead to [Auto-generate the multi-day query](#auto-generate-the-multi-day-query-optional) — the script computes a rolling window for you. Paste the query below into the explorer, then make these replacements: * `REPLACE_WITH_ZONE_ID` → the Zone ID from Part 2. * `REPLACE_WITH_YOUR_DOMAIN` → your bare domain (e.g. `example.com` — no `https://`, no trailing slash). * `datetime_geq` / `datetime_lt` → a 24-hour window inside the range your plan allows. ### Covering multiple days > [!NOTE] > > **Why the query gets long:** Cloudflare caps each `httpRequestsAdaptiveGroups` block to a single 24-hour window — there's no "give me July 6 through 13" parameter. To cover N days, you copy-paste the entire block (including the full \~14-line `userAgent_like` OR list) N times, each with a unique alias and its date window shifted forward 24 hours. An 8-day pull is the same block repeated 8 times. That's the sole reason the query balloons in length. To cover more than one day, duplicate the entire `httpRequestsAdaptiveGroups(...)` block once per day. Give each block a unique **alias** (the label before the colon, e.g. `d20260706`, `d20260707`) and shift its date window forward by 24 hours. All blocks go inside the same `zones(...)` wrapper and run as a single request. Here's a **single-day** example: ```graphql theme={null} { viewer { zones(filter: { zoneTag: "REPLACE_WITH_ZONE_ID" }) { d20260706: httpRequestsAdaptiveGroups( filter: { datetime_geq: "2026-07-06T00:00:00Z" datetime_lt: "2026-07-07T00:00:00Z" requestSource: "eyeball" clientRequestHTTPHost: "REPLACE_WITH_YOUR_DOMAIN" OR: [ { userAgent_like: "%ChatGPT-User%" } { userAgent_like: "%GPTBot%" } { userAgent_like: "%OAI-SearchBot%" } { userAgent_like: "%Claude-User%" } { userAgent_like: "%claude-code%" } { userAgent_like: "%ClaudeBot%" } { userAgent_like: "%PerplexityBot%" } { userAgent_like: "%Applebot%" } { userAgent_like: "%Amazonbot%" } { userAgent_like: "%Amazonbot-Video%" } { userAgent_like: "%meta-externalagent%" } { userAgent_like: "%Bytespider%" } { userAgent_like: "%DuckAssistBot%" } { userAgent_like: "%MistralAI-User%" } ] } limit: 10000 orderBy: [count_DESC] ) { count dimensions { clientRequestPath clientRequestHTTPHost userAgent } } } } } ``` And here's a **two-day** example showing how the blocks stack: ```graphql theme={null} { viewer { zones(filter: { zoneTag: "REPLACE_WITH_ZONE_ID" }) { d20260706: httpRequestsAdaptiveGroups( filter: { datetime_geq: "2026-07-06T00:00:00Z" datetime_lt: "2026-07-07T00:00:00Z" requestSource: "eyeball" clientRequestHTTPHost: "REPLACE_WITH_YOUR_DOMAIN" OR: [ { userAgent_like: "%ChatGPT-User%" } { userAgent_like: "%GPTBot%" } { userAgent_like: "%OAI-SearchBot%" } { userAgent_like: "%Claude-User%" } { userAgent_like: "%claude-code%" } { userAgent_like: "%ClaudeBot%" } { userAgent_like: "%PerplexityBot%" } { userAgent_like: "%Applebot%" } { userAgent_like: "%Amazonbot%" } { userAgent_like: "%Amazonbot-Video%" } { userAgent_like: "%meta-externalagent%" } { userAgent_like: "%Bytespider%" } { userAgent_like: "%DuckAssistBot%" } { userAgent_like: "%MistralAI-User%" } ] } limit: 10000 orderBy: [count_DESC] ) { count dimensions { clientRequestPath clientRequestHTTPHost userAgent } } d20260707: httpRequestsAdaptiveGroups( filter: { datetime_geq: "2026-07-07T00:00:00Z" datetime_lt: "2026-07-08T00:00:00Z" requestSource: "eyeball" clientRequestHTTPHost: "REPLACE_WITH_YOUR_DOMAIN" OR: [ { userAgent_like: "%ChatGPT-User%" } { userAgent_like: "%GPTBot%" } { userAgent_like: "%OAI-SearchBot%" } { userAgent_like: "%Claude-User%" } { userAgent_like: "%claude-code%" } { userAgent_like: "%ClaudeBot%" } { userAgent_like: "%PerplexityBot%" } { userAgent_like: "%Applebot%" } { userAgent_like: "%Amazonbot%" } { userAgent_like: "%Amazonbot-Video%" } { userAgent_like: "%meta-externalagent%" } { userAgent_like: "%Bytespider%" } { userAgent_like: "%DuckAssistBot%" } { userAgent_like: "%MistralAI-User%" } ] } limit: 10000 orderBy: [count_DESC] ) { count dimensions { clientRequestPath clientRequestHTTPHost userAgent } } } } } ``` > [!WARNING] > > **Watch out when copy-pasting blocks:** > > * Each block needs a **unique alias** (`d20260706`, `d20260707`, etc.) — duplicate aliases cause a GraphQL error. > * Keep your **braces matched**. Every `{` inside a block needs a closing `}`. Easiest check: the opening `d20260706: httpRequestsAdaptiveGroups(` and the closing `}` at the end of that block's `dimensions` section should be at the same indent level. > * **Strip any stray text** (like page headers or tab titles) that sneaks in when copying from a browser or PDF — random strings inside the query will cause syntax errors. ### Auto-generate the multi-day query (optional) If you're pulling more than a few days, hand-copying blocks gets tedious. The script below generates the full query for you and **auto-rolls the date window** — it always pulls the trailing `NUM_DAYS` ending at midnight UTC today, so you never edit a date. Run it weekly (or on a cron) and it just works. Save this as `generate_ai_traffic_query.py`: ```python theme={null} from datetime import datetime, timedelta, timezone # ---- Configure these ---- ZONE_ID = "REPLACE_WITH_ZONE_ID" DOMAIN = "REPLACE_WITH_YOUR_DOMAIN" NUM_DAYS = 7 # trailing days to pull/how many 24-hour blocks to generate (Free plan retains ~7; bump this on paid plans) # -------------------------- # Auto-roll the window: end at the start of today (UTC) and go back NUM_DAYS. # Today is a partial day, so the last COMPLETE 24-hour block ends at 00:00Z today. # Anchoring here yields NUM_DAYS full days on clean midnight boundaries — no manual edits. today_utc = datetime.now(timezone.utc).replace( hour=0, minute=0, second=0, microsecond=0 ) start = today_utc - timedelta(days=NUM_DAYS) BOTS = [ "ChatGPT-User", "GPTBot", "OAI-SearchBot", "Claude-User", "claude-code", "ClaudeBot", "PerplexityBot", "Applebot", "Amazonbot", "Amazonbot-Video", "meta-externalagent", "Bytespider", "DuckAssistBot", "MistralAI-User", ] or_block = "\n".join( f' {{ userAgent_like: "%{bot}%" }}' for bot in BOTS ) blocks = [] for i in range(NUM_DAYS): day = start + timedelta(days=i) next_day = day + timedelta(days=1) alias = f"d{day.strftime('%Y%m%d')}" blocks.append(f""" {alias}: httpRequestsAdaptiveGroups( filter: {{ datetime_geq: "{day.strftime('%Y-%m-%d')}T00:00:00Z" datetime_lt: "{next_day.strftime('%Y-%m-%d')}T00:00:00Z" requestSource: "eyeball" clientRequestHTTPHost: "{DOMAIN}" OR: [ {or_block} ] }} limit: 10000 orderBy: [count_DESC] ) {{ count dimensions {{ clientRequestPath clientRequestHTTPHost userAgent }} }}""") query = "{\n viewer {\n" + f' zones(filter: {{ zoneTag: "{ZONE_ID}" }}) {{\n\n' query += "\n\n".join(blocks) query += "\n\n }\n }\n}" print(query) ``` Run it: ```bash theme={null} python3 generate_ai_traffic_query.py ``` Copy the printed output and paste it directly into the GraphQL Explorer. > [!NOTE] > > **Set the window once with `NUM_DAYS`.** Leave it at `7` for the Free-plan retention cap. On a paid plan with longer retention, bump this single number — nothing else changes. Because the window is anchored to "today," the same script pulls a fresh trailing range every time you run it, with no date edits. > [!NOTE] > > The user-agent list above covers the major AI crawlers and agents as of this writing. Add or remove `userAgent_like` entries to track bots that aren't listed. Click the pink **Run** button to execute the query. ## Part 5: Save the response as JSON 1. Copy the full response from the right panel of the explorer. 2. Open a **plain-text** editor (not a rich-text editor). 3. Paste the response and save the file as `cloudflare_ai_traffic_response.json` in your Downloads folder. > [!WARNING] > > The file must be saved as plain-text JSON, not rich text. See Troubleshooting below if you're on Mac using TextEdit. **Mac users (TextEdit):** 1. Open TextEdit. 2. Click **Format → Make Plain Text**. 3. Paste the response. 4. Save as `cloudflare_ai_traffic_response.json`. To confirm the file format in Terminal: ```bash theme={null} cd ~/Downloads file cloudflare_ai_traffic_response.json ``` Good output says `JSON data` or `ASCII text`. If it says `Rich Text Format`, reopen the file in TextEdit, click **Format → Make Plain Text**, and save again. ## Part 6: Convert the JSON to CSV In Terminal: ```bash theme={null} cd ~/Downloads nano convert_ai_traffic_json_to_csv.py ``` Paste this script: ```python theme={null} import json import csv input_file = "cloudflare_ai_traffic_response.json" output_file = "ai_traffic_export.csv" with open(input_file, "r") as f: data = json.load(f) zone = data["data"]["viewer"]["zones"][0] with open(output_file, "w", newline="") as f: writer = csv.writer(f) writer.writerow(["date_range", "path", "host", "userAgent", "requests"]) def sanitize_cell(value): """Prefix cells that start with formula-trigger characters to prevent spreadsheet formula injection when the CSV is opened in Excel/Sheets.""" s = str(value) if s and s[0] in ('=', '+', '-', '@', '\t', '\r', '\n'): return "'" + s return s for date_range, rows in zone.items(): for row in rows: dims = row["dimensions"] writer.writerow([ date_range, sanitize_cell(dims["clientRequestPath"]), sanitize_cell(dims["clientRequestHTTPHost"]), sanitize_cell(dims["userAgent"]), row["count"] ]) print(f"Saved to {output_file}") ``` Save the file (`Ctrl + O`, `Enter`, `Ctrl + X`), then run it: ```bash theme={null} python3 convert_ai_traffic_json_to_csv.py ``` You should see `Saved to ai_traffic_export.csv`. The CSV will be in your Downloads folder. ## Part 7: Send the CSV to The Prompting Company Send `ai_traffic_export.csv` to your TPC contact, or email it to [support@promptingco.com](mailto:support@promptingco.com), so we can incorporate it into your AI traffic dashboard. ## Troubleshooting ### The query fails with a permissions error Your API token is missing a scope. Recheck Part 1 — you need **Account Analytics → Read**, **Zone → Read**, and **Zone Analytics → Read**, with the zone resource scoped to your domain. ### `file` reports "Rich Text Format" instead of JSON TextEdit defaults to rich text. Reopen the file, click **Format → Make Plain Text**, paste the response again, and save. ### The GraphQL query returns an empty result Your date window is likely outside the range your Cloudflare plan retains, or `REPLACE_WITH_YOUR_DOMAIN` doesn't exactly match `clientRequestHTTPHost` for your zone (no `https://`, no trailing slash). If you're using the auto-rolling script, make sure `NUM_DAYS` isn't set beyond what your plan retains. ### `python3: command not found` Install Python 3 (e.g. `brew install python3` on Mac), then re-run the script. # Cloudflare Logpush Source: https://docs.promptingcompany.com/guides/analytics/log-exporters/cloudflare-logpush Stream HTTP request logs from Cloudflare to The Prompting Company and watch AI crawler traffic in your dashboards > [!NOTE] > > **Set this up in the dashboard:** [Connect Cloudflare Logpush](https://app.promptingco.com/traffic-onboarding/cloudflare-logpush) walks through these steps, waits for your first AI content-page visit to arrive, and confirms the traffic is mapped to the right product. Use this page as the reference. Cloudflare Logpush pushes batches of your zone's HTTP request logs directly to The Prompting Company. Once the job is enabled, qualifying content-page visits from AI crawlers and agents (GPTBot, ChatGPT-User, ClaudeBot, PerplexityBot, and others) show up in the [AI traffic](/guides/metrics#ai-traffic) metric automatically — classification happens on our side, so you send everything and we keep what matters. Not on Cloudflare Enterprise? Use the [raw events API](/guides/analytics/log-exporters/raw-events) to stream from any log source instead, or [export a one-off CSV](/guides/analytics/cf-traffic-export) for history. ## Before you start * You need a The Prompting Company **API key** (organization or service-account key) from **Settings → API Keys**. * The zone must be on a Cloudflare **Enterprise** plan — Logpush for the HTTP requests dataset is Enterprise-only. * Your DNS records must be **proxied** (orange cloud) — Logpush only captures traffic that flows through Cloudflare. ## Configure the destination ```text theme={null} https://logs.promptingco.com/v1/events/cf-logpush?header_Authorization=Bearer%20YOUR_API_KEY ``` Cloudflare converts `header_*` query parameters into request headers, so this sends your key as an `Authorization: Bearer` header with every push. Keep the value URL-encoded (`%20` for the space). ### Using the dashboard 1. In the Cloudflare dashboard, open your zone and go to **Analytics & Logs → Logpush**. 2. Click **Create a Logpush job** and select the **HTTP requests** dataset. 3. Choose **HTTP destination** and paste the destination URL above. 4. Select these fields: `ClientIP`, `ClientRequestHost`, `ClientRequestMethod`, `ClientRequestReferer`, `ClientRequestSource`, `ClientRequestURI`, `ClientRequestUserAgent`, `WorkerSubrequest`, `EdgeStartTimestamp`, `EdgeResponseContentType`, `EdgeResponseStatus`. 5. Save and enable the job. Cloudflare validates the destination with a test message — this succeeds automatically. ### Using the API ```bash theme={null} curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/logpush/jobs" \ -H "Authorization: Bearer $CF_API_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "name": "tpc-crawler-logs", "dataset": "http_requests", "enabled": true, "destination_conf": "https://logs.promptingco.com/v1/events/cf-logpush?header_Authorization=Bearer%20YOUR_API_KEY", "max_upload_bytes": 5000000, "output_options": { "field_names": [ "ClientIP", "ClientRequestHost", "ClientRequestMethod", "ClientRequestReferer", "ClientRequestSource", "ClientRequestURI", "ClientRequestUserAgent", "WorkerSubrequest", "EdgeStartTimestamp", "EdgeResponseContentType", "EdgeResponseStatus" ], "timestamp_format": "rfc3339" } }' ``` Any `timestamp_format` works (`unixnano`, `unix`, or `rfc3339`); `rfc3339` is the easiest to debug. ## What gets ingested You don't need to pre-filter traffic — send everything and The Prompting Company classifies AI crawlers and agents on ingestion. Recognized AI traffic is kept only when it qualifies as a content-page visit: `GET`, a `200`–`299` status except `204` and `205` (or `304`), and an HTML or XHTML content type when those fields are present. Numeric status values may arrive as JSON numbers or decimal strings. Missing or non-numeric HTTP metadata fails open for page-looking paths. Jobs that omit `EdgeResponseContentType` or `EdgeResponseStatus` will still ingest non-HTML AI hits such as JSON APIs unless the path matches a Next.js prefix or an asset suffix. Canonical Next.js prefixes (`/_next/static`, `/_next/image`, and `/_next/data`, lowercase) are always filtered, as are common script, stylesheet, source-map, image, font, media, Rive, WASM, JSON, XML, text, and PDF suffixes when content type is missing. Suffix matching is case-insensitive and ignores a trailing slash; an HTML content type keeps legitimate dotted pages. A few line types are skipped automatically so visits aren't double-counted: Cloudflare's destination-validation test message, Worker subrequests (`WorkerSubrequest: true`), non-eyeball requests (`ClientRequestSource` values like `edgeWorkerFetch` or purges), and lines without a `ClientRequestHost`. You can optionally add a Logpush filter to reduce volume, but it isn't required for correctness. ## Responses | Status | Meaning | | - | - | | `200` | Batch processed. Body reports `{"ok": true, "received": N, "ingested": N, "skipped": N, "filtered": N}`. A positive `filtered` count means non-AI or non-page requests were intentionally not stored. | | `401` | Missing or invalid API key — check the key in the destination URL | | `429` | Key verification was rate limited — Cloudflare retries | | `400` | Body could not be decoded | | `413` | Decompressed batch too large — lower the job's `max_upload_bytes` | | `503` | Temporary ingestion outage — Cloudflare retries automatically | Delivery is at-least-once: failed batches are re-pushed in full, and occasional duplicates are expected and tolerated by the traffic metrics. ## Verify it's working Real traffic starts appearing in the [AI traffic](/guides/metrics#ai-traffic) dashboard within a few minutes of enabling the job. To exercise the pipeline immediately without waiting for a crawler visit, send one test event through the [raw events API](/guides/analytics/log-exporters/raw-events#verify-its-working). # Raw events API Source: https://docs.promptingcompany.com/guides/analytics/log-exporters/raw-events Send crawler logs to The Prompting Company from any log source — nginx, CDNs, or a backfill script > [!NOTE] > > **Set this up in the dashboard:** [Connect the raw events API](https://app.promptingco.com/traffic-onboarding/raw) gives you the request to copy, waits for your first AI content-page visit to arrive, and confirms the traffic is mapped to the right product. Use this page as the reference. The raw events API accepts request logs from any source: your own web server, a CDN without a managed export, or a script replaying historical logs. Events land in the same [AI traffic](/guides/metrics#ai-traffic) metric as every other collector, with AI crawler and agent classification handled on our side. On Cloudflare Enterprise? [Cloudflare Logpush](/guides/analytics/log-exporters/cloudflare-logpush) streams the same data with zero ongoing work. ## Before you start * You need a The Prompting Company **API key** (organization or service-account key) from **Settings → API Keys**. ## Send events POST a JSON array (a single object also works), plain or gzipped, to `https://logs.promptingco.com/v1/events/raw`. Authenticate with either an `X-API-Key` header or `Authorization: Bearer`. ```bash theme={null} curl -X POST "https://logs.promptingco.com/v1/events/raw" \ -H "X-API-Key: $TPC_API_KEY" \ -H "Content-Type: application/json" \ --data '[ { "timestamp": "2026-08-11T12:00:00.000Z", "status_code": 200, "request_method": "GET", "request_path": "/pricing", "query_string": "ref=x", "content_type": "text/html", "client_ip": "203.0.113.7", "hostname": "example.com", "user_agent": "GPTBot/1.2", "referrer": "https://www.google.com" } ]' ``` | Field | Required | Notes | | - | - | - | | `hostname` | yes | Events without it are counted as skipped | | `timestamp` | no | ISO 8601 or unix seconds/millis/nanos; defaults to arrival time | | `request_path` | no | Defaults to `/`; may include the query string inline (`/pricing?ref=x`) | | `query_string` | no | Alternative to inlining the query in `request_path` | | `user_agent`, `client_ip`, `request_method`, `status_code`, `content_type`, `referrer` | no | Recommended — user agent and client IP drive AI classification; method, status, and content type identify content pages | Requests can be up to 64 MB (compressed and decompressed). Batch as many events per request as fits. ## What gets ingested The Prompting Company keeps recognized AI traffic only when it qualifies as a content-page visit. When present, the method must be `GET`, the numeric status must be `200`–`299` except `204` and `205` (or `304`), and the content type must be `text/html` or `application/xhtml+xml`. Numeric `status_code` values may arrive as JSON numbers or decimal strings. Missing or non-numeric HTTP metadata fails open for page-looking paths. Senders that omit `content_type` or `status_code` will still ingest non-HTML AI hits such as JSON APIs unless the path matches a Next.js prefix or an asset suffix. Canonical Next.js prefixes (`/_next/static`, `/_next/image`, and `/_next/data`, lowercase) are always filtered, as are paths ending in common script, stylesheet, source-map, image, font, media, Rive, WASM, JSON, XML, text, or PDF suffixes when content type is missing. Suffix matching is case-insensitive and ignores a trailing slash; an HTML content type keeps a legitimate dotted page such as `/docs/node.js`. ## Responses | Status | Meaning | | - | - | | `200` | Batch processed. Body reports `{"ok": true, "received": N, "ingested": N, "skipped": N, "filtered": N}`. A positive `filtered` count means non-AI or non-page requests were intentionally not stored. | | `401` | Missing or invalid API key | | `429` | Key verification was rate limited — retry shortly | | `400` | Body could not be decoded or parsed as JSON | | `413` | Decompressed body too large — send smaller batches | | `503` | Temporary ingestion outage — retry the batch | Delivery is at-least-once: retry the whole batch after a `503`, and occasional duplicates are expected and tolerated by the traffic metrics. ## Verify it's working ```bash theme={null} curl -s -X POST "https://logs.promptingco.com/v1/events/raw" \ -H "X-API-Key: $TPC_API_KEY" \ -H "Content-Type: application/json" \ --data '[{"hostname": "example.com", "request_path": "/", "user_agent": "GPTBot/1.2", "client_ip": "203.0.113.7"}]' ``` A `200` with `"ingested": 1` confirms the pipeline, and the visit appears in your [AI traffic](/guides/metrics#ai-traffic) dashboard shortly after. # CLI, ChatGPT, or Claude Source: https://docs.promptingcompany.com/guides/cli-chatgpt-claude Compare the TPC CLI with the TPC plugin in ChatGPT and Claude, and pick the one that fits how you work. You can work with The Prompting Company (TPC) outside the dashboard in two ways: * **The CLI**: `tpc`, a binary you run in a terminal or a script. * **The TPC plugin**: you ask an AI assistant in plain language, and it calls TPC for you. The plugin works in ChatGPT and in Claude. The plugin is one server, the TPC MCP server at `https://mcp.promptingco.com/mcp`. ChatGPT and Claude connect to the same server, so they have the same tools and the same access. Only the install steps differ. Both sign in with your TPC account, so you see the same organizations and products as in the dashboard, and the same plan limits apply. ## CLI or the TPC plugin | | CLI | TPC plugin | | - | - | - | | How you use it | Typed commands in a terminal, a script, or CI | Questions in a chat with ChatGPT or Claude | | Who decides which calls run | You | The assistant | | Output | Tables, or JSON with `--format json` | A written answer, with a prompt list and analytics charts in clients that show them | | Best for | Repeatable or bulk work, automation, and features only the CLI has | Asking questions and making changes without learning commands | ### What each one can do | Feature | CLI | TPC plugin | | - | - | - | | Organizations and products | Yes | Yes | | Tracked prompts and prompt suggestions | Yes | Yes | | Topics and views | Yes | Yes | | Tracked URLs | Yes | Yes | | Site content: draft, generate, review, publish | Yes | Yes | | Knowledge files | Yes | Yes | | Analytics: share of voice, citations, sentiment, AI traffic | Yes | Yes | | [ChatGPT plugin discovery (Enterprise)](/cli/commands/prompts#chatgpt-plugin-discovery) | Yes | Yes | | [Personas](/cli/commands/persona) | Yes | No | | [Model council](/cli/commands/council) | Yes | No | | [Simulations and Agent Experience](/cli/commands/agent-experience) | Yes | No | For every tool the plugin can call, see [Connect the MCP server](/mcp/connect#tools). **Use the TPC plugin** when you want answers without learning commands. Ask "How is my product doing in AEO?" and the assistant finds your product, runs the analytics calls, and summarizes the results. See [How is my product doing in AEO?](/mcp/check-aeo) and [Help me improve the AEO of my product](/mcp/improve-aeo). **Use the CLI** when you need: * The same steps every time, in a script, a cron job, or CI * JSON output to feed into other tools * Personas, Model council, or simulations and Agent Experience You can use both. Coding agents such as Claude Code can also run `tpc` commands themselves. ## ChatGPT or Claude Pick the assistant you already use. The TPC tools are the same in both. | | ChatGPT | Claude | | - | - | - | | Where to get it | [The Prompting Company](https://chatgpt.com/plugins/plugin_asdk_app_6acd8fe391b48191a1d6e6237bbd52bf) in the ChatGPT plugin directory | A custom connector you add with the server URL | | Works in | ChatGPT | Claude.ai, Claude Desktop, and Claude Code | | Sign in | TPC sign-in in your browser | TPC sign-in in your browser | | Setup steps | [ChatGPT](/mcp/connect#chatgpt) | [Claude.ai and Claude Desktop](/mcp/connect#claude-ai-and-claude-desktop), [Claude Code](/mcp/connect#claude-code) | Claude Code also suits engineering teams: a coding agent can read your analytics and update content and knowledge files while it works in your repository. ## Get started > [card] [CLI](/cli/installation) > > Install `tpc` and sign in. > [card] [ChatGPT](/mcp/connect#chatgpt) > > Connect the TPC plugin in ChatGPT. > [card] [Claude](/mcp/connect#claude-ai-and-claude-desktop) > > Add TPC as a custom connector in Claude. # Connect a custom endpoint Source: https://docs.promptingcompany.com/guides/cms/custom Publish TPC drafts to your own server via a JSON POST endpoint with bearer authentication Use the custom endpoint integration when your CMS is not natively supported. The Prompting Company POSTs JSON to your endpoint with a bearer token. ## Endpoint requirements Your server must: * Accept `POST` requests with `Content-Type: application/json` * Validate the `Authorization: Bearer <token>` header * Return a `2xx` status code on success The response body is logged in TPC but not parsed. ## Bearer token authentication TPC sends the token you paste into the integration form as: ```text theme={null} Authorization: Bearer <token> ``` Validate this on your endpoint before processing the request. Reject anything without a valid bearer with `401`. ## Body template Use placeholders to map TPC's fields into your endpoint's expected shape. Available placeholders: * `{{title}}` * `{{content}}` * `{{excerpt}}` * `{{platform}}` * `{{status}}` * `{{thumbnailUrl}}` * `{{heroImageUrl}}` Example body template: ```json theme={null} { "title": "{{title}}", "html": "{{content}}", "cover": "{{heroImageUrl}}" } ``` TPC substitutes placeholders before sending. Unset placeholders resolve to empty string. ## Optional custom headers If your endpoint needs extra headers (API key, tenant ID), paste them as a JSON object in the integration form: ```json theme={null} { "X-Tenant-Id": "abc123" } ``` ## Connect in TPC 1. Open **Settings → Integrations** in your TPC product workspace. 2. Select **Custom endpoint**. 3. Enter: * **Endpoint URL** — the fully qualified URL TPC should POST to * **Bearer token** — the token your server will validate * **Body template** — JSON with placeholders * **Custom headers** — optional JSON object 4. Click **Save**, then **Test connection**. ## Troubleshooting ### Test connection times out TPC waits up to 30 seconds. Confirm the endpoint is publicly reachable and responds within that window. ### 401 or 403 Your endpoint rejected the bearer token. Confirm the token stored in your server matches the one pasted into TPC. ### Non-2xx status but content saved Return a `2xx` status only after the write is durable. Any non-2xx response is treated as a failure and shown as an error in the publish log. # Connect Framer Source: https://docs.promptingcompany.com/guides/cms/framer Publish TPC drafts to a Framer CMS collection using a Framer API key The Prompting Company writes to a Framer CMS collection via the Framer API. > [!NOTE] > > Framer CMS API access requires a **Framer Pro plan or higher**. ## Before you start * Admin access to the Framer project. * A CMS collection created inside the project. ## Generate an API key 1. In Framer, open your project. 2. Click the project name (top-left) and open **Settings**. 3. Open the **API** tab. 4. Click **Generate API key**. 5. Grant **CMS write** scope. 6. Copy the key. Framer shows it only once. ## Copy your project URL and collection ID * **Project URL** is the `framer.com` URL of the project. * **Collection ID** is shown when you select a CMS collection in the Framer editor — copy it from the URL or the collection settings panel. ## Match field names Default fields are: * `title` * `body` If you renamed fields in your collection, paste the exact field slug (not the visible label). ## Connect in TPC 1. Open **Settings → Integrations** in your TPC product workspace. 2. Select **Framer**. 3. Enter API key, project URL, collection ID, and any custom field slugs. 4. Click **Save**, then **Test connection**. ## Troubleshooting ### 401 Unauthorized The plan does not include CMS API access, or the token was revoked. Confirm you are on Pro or higher and regenerate the key. ### 404 collection not found The collection ID does not belong to the project URL you entered. Double-check both in Framer. ### Fields save empty Field slugs are case-sensitive and must match the collection schema exactly. ## Related links * [Framer developer documentation](https://www.framer.com/developers/) # Connect Ghost Source: https://docs.promptingcompany.com/guides/cms/ghost Publish TPC drafts to Ghost using a Custom Integration Admin API key The Prompting Company publishes to Ghost using a Custom Integration's Admin API key. ## Before you start * Owner or Administrator role on the Ghost site. * Ghost 4.0 or later. ## Create a custom integration 1. In your Ghost admin panel, click the gear icon (**Settings**). 2. Open **Integrations**. 3. Scroll to **Custom integrations** and click **Add custom integration**. 4. Name it `TPC publisher` and click **Create**. ## Copy the admin API key On the integration page, copy the **Admin API Key**. It looks like: ```text theme={null} xxxxxxxxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy ``` > [!WARNING] > > Copy the **Admin API Key**, not the Content API Key. TPC needs write access, and only the admin key can create drafts. ## Connect in TPC 1. Open **Settings → Integrations** in your TPC product workspace. 2. Select **Ghost**. 3. Enter: * **Site URL** — your Ghost blog root, e.g. `https://blog.example.com` * **Admin API key** — the key you copied 4. Click **Save**, then **Test connection**. ## Troubleshooting ### 401 Unauthorized Wrong key type — Content API keys are read-only. Regenerate a custom integration and copy the Admin API Key. ### 403 Forbidden The Ghost site restricts custom integrations. Confirm your role is Owner or Administrator. ### Draft appears but images are missing Ghost fetches images by URL. If TPC-hosted image URLs are blocked by your Ghost network policy, the draft still saves but images render as broken. ## Related links * [Ghost Admin API documentation](https://ghost.org/docs/admin-api/) # CMS integrations Source: https://docs.promptingcompany.com/guides/cms/overview Connect The Prompting Company to your CMS to publish generated content as drafts The Prompting Company publishes generated content directly into your CMS as drafts. You connect a CMS once per product, and every subsequent publish action writes to that destination. ## Supported CMS * [WordPress](/guides/cms/wordpress) — self-hosted or WordPress.com Business+ via TPC connector plugin * [Sanity](/guides/cms/sanity) — dataset writes via project-scoped API token * [Webflow](/guides/cms/webflow) — CMS collection writes via site API token * [Ghost](/guides/cms/ghost) — Admin API custom integration * [Framer](/guides/cms/framer) — CMS collection writes via Framer API key (Pro plan or higher) * [Prismic](/guides/cms/prismic) — repository writes via permanent access token * [Custom endpoint](/guides/cms/custom) — POST JSON to your own server with a bearer token ## Where to connect Every CMS is configured per-product from **Settings → Integrations** inside your product workspace. Each connector accepts credentials, validates them on save, and exposes a **Test connection** button. > [!NOTE] > > TPC always publishes as drafts. Nothing goes live until you approve it inside your CMS. ## Before you start * You must be an admin on the target CMS site — API token generation usually requires it. * Prepare a dedicated integration user or token labelled `TPC publisher` so you can revoke it independently. * If your CMS supports scoped tokens (Sanity, Webflow, Ghost), grant the minimum scope required to create drafts. # Connect Prismic Source: https://docs.promptingcompany.com/guides/cms/prismic Publish TPC drafts to a Prismic repository using a permanent access token The Prompting Company writes documents to your Prismic repository using a write-scoped permanent access token. ## Before you start * Owner or Administrator role on the Prismic repository. * Your custom types deployed to the repository. ## Find your repository name Your Prismic repository name is the subdomain of your Prismic URL. For `myblog.prismic.io`, the repository name is `myblog`. ## Generate a permanent access token 1. Open your Prismic repository. 2. Go to **Settings → API & Security**. 3. Scroll to **Permanent access tokens**. 4. Click **Create new** and grant **Write** access. 5. Copy the token immediately. Prismic shows it only once. ## Connect in TPC 1. Open **Settings → Integrations** in your TPC product workspace. 2. Select **Prismic**. 3. Enter: * **Repository name** — the subdomain (e.g. `myblog`) * **Access token** — the token you copied * **Custom type** — the API ID of the custom type you want to write to 4. Click **Save**, then **Test connection**. > [!NOTE] > > If your repository is public and you only need read access, you can leave **Access token** blank — but TPC requires write access to publish drafts. ## Troubleshooting ### 401 Unauthorized The token is read-only. Regenerate with **Write** access. ### 400 "unknown type" The **Custom type** value does not match a deployed API ID. Check **Custom Types** in the Prismic dashboard — the API ID appears next to the display name. ### Fields save empty Prismic slice-based content requires the field paths to match your custom type schema. Confirm the field API IDs and rich-text structure. ## Related links * [Prismic access token documentation](https://prismic.io/docs/access-token) # Connect Sanity Source: https://docs.promptingcompany.com/guides/cms/sanity Publish TPC drafts to Sanity using a project-scoped API token The Prompting Company writes documents to your Sanity dataset using a project-scoped API token with Editor or Maintainer permissions. ## Before you start * Admin or Developer role on the target Sanity project. * Your document schema deployed to the dataset you plan to write to. ## Generate an API token 1. Go to [sanity.io/manage](https://sanity.io/manage) and open your project. 2. Open the **API** tab, then **Tokens**. 3. Click **Add API token**. 4. Name it `TPC publisher` and pick **Editor** or **Maintainer**. 5. Copy the token. Sanity shows it only once. ## Find your project ID and dataset * **Project ID** is shown at the top of the project page in `sanity.io/manage`. * **Dataset** is usually `production`. Match the exact dataset name. * **API version** defaults to `v2025-03-01`. Bump only if you need a newer feature. ## Match your schema fields TPC writes to a single document type. Defaults: * **Document type** — `post` * **Fields** — `title`, `content`, `slug`, `excerpt` * **Image fields** — `thumbnail`, `hero` (optional) If your schema uses different names, paste the exact field names in the integration form. Image fields are optional — leave them blank if your schema has no image references. ## Connect in TPC 1. Open **Settings → Integrations** in your TPC product workspace. 2. Select **Sanity**. 3. Fill in project ID, dataset, API version, document type, field names, and the API token. 4. Click **Save**, then **Test connection**. ## Troubleshooting ### 401 Unauthorized Token is missing write permission. Regenerate with **Editor** or **Maintainer** scope. ### 404 or "unknown type" The **Document type** in TPC does not exist in the deployed schema. Deploy the schema or update the type name to match. ### Fields save as `null` Field names are case-sensitive and must match the schema key exactly, not the display label. ## Related links * [Sanity API token documentation](https://www.sanity.io/docs/http-auth) # Connect Webflow Source: https://docs.promptingcompany.com/guides/cms/webflow Publish TPC drafts to a Webflow CMS collection using a site API token The Prompting Company publishes to a Webflow CMS collection using a site-scoped API token. ## Before you start * Workspace admin on the Webflow site. * A CMS collection created for the content type you want to publish (e.g. Blog Posts). ## Generate an API token 1. In Webflow Designer, click the **Webflow** logo (top-left) and open **Site Settings**. 2. Go to the **Apps & integrations** tab. 3. Scroll to **API access** and click **Generate API token**. 4. Grant **CMS read/write** scope for the site that owns your collection. 5. Copy the token. ## Get your collection ID 1. In Designer, open the **CMS** panel. 2. Click the collection you want to publish to. 3. Click the **⚙ Settings** icon. 4. Copy the **Collection ID** at the bottom. > [!WARNING] > > Use the Collection ID, not the slug. They look similar but the ID is a longer alphanumeric string. ## Match your collection field slugs TPC defaults to these field slugs: * `name` * `slug` * `body` * `summary` If you renamed fields in Webflow, paste the exact **slug** (not the visible label). Image fields are optional. ## Connect in TPC 1. Open **Settings → Integrations** in your TPC product workspace. 2. Select **Webflow**. 3. Enter the API token, collection ID, and any custom field slugs. 4. Click **Save**, then **Test connection**. ## Troubleshooting ### 401 Unauthorized Token is missing CMS write scope, or the token was generated for a different site. Regenerate on the correct site with **CMS read/write** enabled. ### 400 "unknown field" A field slug in TPC does not exist on the collection. Confirm field slugs in Webflow Designer → CMS → Collection settings → Fields. ### Draft published but not visible in the CMS panel Refresh Designer. Webflow's Designer caches the collection list — the item appears after a refresh. ## Related links * [Webflow API token documentation](https://developers.webflow.com/data/reference/authentication) # Connect WordPress Source: https://docs.promptingcompany.com/guides/cms/wordpress Publish TPC drafts to WordPress using the TPC connector plugin The Prompting Company publishes drafts to WordPress via a small connector plugin that exposes a token-authenticated endpoint. This works for self-hosted WordPress and WordPress.com Business or higher (plans that allow custom plugins). ## Before you start * Admin access to your WordPress site. * Ability to upload and activate plugins. ## Install the connector 1. Download the connector plugin: ```text theme={null} https://r2-assets.promptingco.com/tpc-wordpress-connector.php.zip ``` 2. In WordPress admin, go to **Plugins → Add New → Upload Plugin**. 3. Upload `tpc-wordpress-connector.php.zip` and click **Install Now**. 4. Click **Activate**. A new menu item **Settings → TPC Connector** appears. ## Generate a connector token 1. Open **Settings → TPC Connector**. 2. Click **Generate Token**. 3. Copy the token immediately. The token is shown only once. > [!WARNING] > > If you lose the token, generate a new one — the old token stops working as soon as a new one is generated. ## Connect in TPC 1. In your TPC product workspace, open **Settings → Integrations**. 2. Select **WordPress**. 3. Enter: * **Site URL** — your WordPress site root, e.g. `https://blog.example.com` * **Connector token** — the token you copied above 4. Click **Save** and then **Test connection**. ## Meta title and description Each published post carries the document's meta title and meta description from TPC. The connector writes them to the active SEO plugin so they appear in that plugin's post settings and in the rendered page: * Yoast SEO * Rank Math * All in One SEO * SEOPress If none of these plugins is active, the connector sets the `<title>` and `<meta name="description">` tags on the post page itself. Connector version 0.4.0 or later is required; older versions ignore these fields. ## Troubleshooting ### Test connection fails with 401 The token in TPC does not match the token in WordPress. Regenerate the token in **Settings → TPC Connector** and paste the new value into TPC. ### Test connection fails with 404 The plugin is not activated, or the site URL is wrong. Confirm the plugin appears in **Plugins → Installed Plugins** as active, and that the site URL has no trailing path. ### Draft appears but images are broken WordPress uploads require the connector to reach your media library. Check that the WordPress site is publicly reachable — TPC uploads images by URL, not by binary transfer. # Environments Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/environments Configure which agents attempt your tasks and the sandboxes they run in An environment pairs an agent configuration with sandbox resources. It answers two questions: *which agent attempts the task*, and *what machine does it get*? Because environments are the variable in an experiment, you'll typically create one per configuration you want to compare — "Claude Code + latest Sonnet" vs "Codex + latest GPT", for example — and run them against the same tasks. ## Agent configuration | Setting | Options | | - | - | | **Harness** | `claude` (Claude Code), `codex` (Codex CLI), `opencode` (OpenCode) | | **Model** | Any model supported by the chosen harness — validated when the run starts | | **Temperature / max tokens** | Optional sampling overrides | | **Sandbox mode** | `read-only`, `workspace-write`, or `danger-full-access` | The harness runs headless inside the sandbox, exactly as a developer would run it in their own terminal. Its session logs are captured and parsed into a unified transcript regardless of which harness produced them, so runs are comparable across harnesses. ## Sandbox resources Every run gets a fresh, isolated Linux sandbox: * **CPU**: 1–4 cores * **Memory**: 1–8 GB * **Disk**: 1–10 GB * **GPU** (optional): T4, L4, A10G, A100, or H100 Runs without a GPU execute on the default sandbox provider; requesting a GPU automatically routes the run to GPU-backed infrastructure. The sandbox is created at run start, initialized with the task's files, commands, and secrets, archived after the run, and destroyed. ## Scheduling Environments can run on a recurring schedule (every 7 or 14 days). Scheduled runs execute the environment's tasks automatically, which is the easiest way to monitor agent experience continuously — a docs change that breaks agent onboarding shows up in the next scheduled run instead of the next manual experiment. ## Choosing what to compare Common comparison setups: * **Model sweep** — same harness, different models, to see which models handle your product well * **Harness sweep** — same model family across Claude Code, Codex, and OpenCode, to find harness-specific friction * **Before/after** — identical environments run as separate iterations around a docs or API change ## Working with environments from the CLI The simplest way to create an environment is to declare it in an `environment.json` beside a task and run the directory — see [Run a task from a directory](/guides/coding-agent-optimization/tasks#run-a-task-from-a-directory). `tpc sim run` creates the environment, links it, and queues runs in one command. To manage environments directly, the agent configuration is passed as inline JSON or a `@file` (JSON or TOML): ```json theme={null} { "harness": "claude", "provider": "anthropic", "model": "claude-sonnet-4-6", "sandboxResources": { "cpu": 2, "memory": 4, "disk": 10 } } ``` ```bash theme={null} # Create an environment from the config file, linking tasks at creation tpc sim env create --name "Claude Code + Sonnet" \ --agent-config @agent-config.json \ --task-ids task_123,task_456 # Or pass the config inline tpc sim env create --name "Codex sweep" \ --agent-config '{"harness":"codex","provider":"openai","model":"gpt-5"}' # Browse environments (filters combine) tpc sim env list --search claude --enabled true # Inspect one environment — agent config, init commands, init file names, linked tasks tpc sim env get env_123 # Link or unlink tasks later tpc sim env task attach env_123 task_789 tpc sim env task detach env_123 task_789 # Update settings — flags combine in one call (--schedule: 7d or 14d; none clears) tpc sim env update env_123 --name "Shared Claude Sonnet" --schedule 7d tpc sim env update env_123 --enabled false # Delete (detach all tasks first) tpc sim env delete env_123 ``` To request a GPU sandbox, add it to `sandboxResources` — for example `"gpu": "A100", "gpuCount": 1`. ## Secrets from the CLI Secrets are set per environment and injected as environment variables at run time. Values are never printed back by the CLI. ```bash theme={null} # Set a secret from a literal value, or safely from your local shell tpc sim env secret set env_123 --name FEATURE_FLAG --value enabled tpc sim env secret set env_123 --name ACME_API_KEY --from-env ACME_API_KEY # Bulk-import from a .env file (or stdin with --env-file -) tpc sim env secret import env_123 --env-file .env.simulation # List metadata and clean up tpc sim env secret list env_123 tpc sim env secret delete env_123 --name ACME_API_KEY ``` # Experiments Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/experiments Run tasks across environments in parallel and read the results An experiment is a controlled comparison: a set of tasks, a set of environments, and an optional signal config. Running an experiment produces an **iteration** — one run for every task × environment pair, executed in parallel. ## Setting up an experiment 1. Create the experiment and give it a name 2. Attach the tasks to evaluate 3. Attach the environments to compare 4. Optionally upload a [signal config](/guides/coding-agent-optimization/signals) to extract custom metrics 5. Trigger an iteration Experiments live in your product's **Simulation** section in the dashboard, and can also be created and run via the [API](/api/overview) or the CLI: ```bash theme={null} tpc sim experiment create --name "Onboarding friction" \ --task-ids task_abc,task_def \ --env-ids env_123,env_456 \ --signal-config signals.yaml # Or build it up incrementally tpc sim experiment create --name "Onboarding friction" tpc sim experiment task add exp_789 task_abc tpc sim experiment env add exp_789 env_123 ``` Triggering an iteration creates one run per task × environment pair. See [Runs & iterations](/guides/coding-agent-optimization/runs) for what happens inside each run and what it records. ## Iteration results When every run in an iteration completes, results are generated at the iteration level: * **Signal aggregates** — each signal folded across runs into rates, averages, medians, and distributions, grouped by environment and task * **Failure clusters** — recurring friction patterns identified across failing runs, each with a root cause (what in your product, docs, or infra caused it) and a recommended fix * **Summary** — task-level scores and environment comparisons Iterations are immutable. Re-running an experiment creates a new numbered iteration rather than overwriting the last one, so improvements stay measurable over time. ## Running experiments from the CLI ```bash theme={null} # Trigger a new iteration and follow it to completion in one command # (one run per task × environment pair; polls every 5 seconds) tpc sim experiment run exp_789 --watch # Read iteration results: summary, task scores, failure clusters, suggestions tpc sim experiment results exp_789 # Compare against an earlier iteration, or drill into one failure cluster tpc sim experiment results exp_789 --iteration 2 tpc sim experiment results exp_789 --error-category "Auth failures" # Signal values, aggregated and per run tpc sim experiment signals exp_789 ``` Use `--format json` on any of these to feed results into scripts or CI. To drill into individual runs (`tpc sim run get/logs/actions`), see [Runs & iterations](/guides/coding-agent-optimization/runs#inspecting-runs-from-the-cli). # Limits & constraints Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/limits How the sandbox executes a run, and the hard limits that shape how you write tasks A few properties of the execution model shape how you should write tasks. Knowing them up front is the difference between a run that produces a clean result and one that produces nothing useful. This page collects the behavioral constraints and the hard limits in one place; the [core concept](/guides/coding-agent-optimization/overview) pages cover each piece in depth. ## Execution model ### Every run is a fresh, isolated sandbox Each run provisions a new sandbox, initializes it, and destroys it when the run completes — see [Runs & iterations](/guides/coding-agent-optimization/runs). Nothing carries over between runs or between tasks: no files, installed packages, environment variables, or context. Write each [task](/guides/coding-agent-optimization/tasks) to be **self-contained**. A task can't depend on another task having run first, and an instruction like "using the SDK you installed earlier" will fail. Anything the agent needs on disk or installed must come from the task's init files and init commands, or be done by the agent during the run. ### The instruction is one-shot The agent receives the task instruction once and runs until it finishes or hits the time limit. There is **no multi-turn conversation** — you can't answer a clarifying question or send a follow-up mid-run. Everything the agent needs must be in the instruction. ### No interactive display Sandboxes are **headless Linux** — there is no interactive browser or desktop UI. Design tasks around outcomes the agent can reach from the command line, the filesystem, or HTTP. (A headless browser is used internally for screenshot-based evaluation, but it isn't an agent tool.) ### Finish the work and leave an artifact A run ends when the agent process exits, and the sandbox is torn down immediately after. **Any process the agent leaves running in the background is killed** and its output is lost. The common failure is an agent that ends its turn with "the dev server is now running" — the server dies with the sandbox and nothing is captured. Write instructions and goals so the agent **completes the work and leaves a durable artifact** rather than holding a process open: * Have the agent write output to a file, capture the HTTP response, or save logs — then score that artifact. * For "stand up a server" tasks, instruct the agent to start it, call it, save the response to a file, and stop it, all within the run. * Score the saved artifact (for example with a `bash_command` or `script_judge` [goal](/guides/coding-agent-optimization/tasks#goals-and-criteria)), not the live process. ## Hard limits | Area | Limit | | - | - | | Agent execution | Up to 60 minutes per run (the full run, including evaluation and analysis, can take up to \~70 minutes) | | Init command — length | 1–10,000 characters each | | Init command — count | Up to 50 on a task and up to 50 on an environment (applied separately), run sequentially and fail-fast (first non-zero exit aborts setup) | | Init command — timeout | 1 second to 30 minutes each (default 5 minutes) | | Init command — working dir | Must be under `/home/agent-user/` | | Init file — zip size | Up to 500 MB, auto-extracted | | Init file — target path | Must be under `/home/agent-user/` | | Sandbox resources | CPU 1–4, memory 1–8 GB, disk 1–10 GB — see [Environments](/guides/coding-agent-optimization/environments#sandbox-resources) | | `script_judge` goal | 120-second timeout by default, configurable per goal (exit code 124 means it timed out) | Out-of-range sandbox resource values are clamped to the allowed range rather than rejected. Requesting any GPU routes the run to GPU-backed infrastructure automatically. ## Secrets and isolation Secrets are scoped to an environment and injected as environment variables at run time — see [Environments](/guides/coding-agent-optimization/environments#secrets-from-the-cli). Two constraints to know: * **Reserved names can't be overridden.** Platform-managed variables such as `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `AWS_*`, `HOME`, and `PATH` are protected. * **Platform secrets are revoked while a `script_judge` runs**, so a verification script can't read or exfiltrate them. Outbound network access is allowed by default — the agent harness needs it to reach the model provider. ## Using `script_judge` The `script_judge` [evaluation type](/guides/coding-agent-optimization/tasks#goals-and-criteria) runs your own shell script in the sandbox after the agent finishes (exit 0 = pass). Before relying on it: * It requires the **`script_judge` feature flag** on your organization. Without it, use a deterministic alternative (`bash_command`, `file_exists`) or an `llm_judge`. * Every script is **security-reviewed when the task is registered** — scripts that read platform secrets, exfiltrate data, fetch and execute remote code, or exhaust resources are flagged. # Overview Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/overview Evaluate and optimize how coding agents experience your product in sandboxed environments Agent experience lets you run real coding agents — Claude Code, Codex, and OpenCode — against your product inside isolated sandboxes, score each attempt against goals you define, and turn the results into concrete fixes for your docs, APIs, and onboarding. If AI agents struggle to install your SDK, authenticate, or follow your docs, they recommend something else. This product shows you exactly where that friction happens and what to change. ## How it works 1. **Define a task** — what the agent should accomplish with your product (e.g. "install the SDK and send a first event"), plus the goals that define success 2. **Define environments** — which agent harness and model attempt the task, and what sandbox it runs in 3. **Run an experiment** — execute every task across every environment in parallel, in fresh sandboxes 4. **Review the results** — per-run scores, full transcripts, extracted signals, and failure clusters with root causes and recommended fixes ## How the pieces fit together ```text theme={null} Experiment ├── Tasks (what to do + how success is measured) ├── Environments (which agent/model attempts it) └── Iterations (numbered batches of runs) └── Runs (task × environment, one sandbox each) ├── score, pass/fail, transcript, cost └── signal values → aggregated per iteration ``` Each concept has its own page under **Core concepts** in the sidebar, and a matching command group in the [tpc CLI](/cli/overview): | Concept | Command group | Common commands | | - | - | - | | [Tasks](/guides/coding-agent-optimization/tasks) | `tpc sim task` | `create --file task.json`, `list`, `get`, `update`, `run` | | [Environments](/guides/coding-agent-optimization/environments) | `tpc sim env` | `create`, `list`, `update`, `task attach/detach`, `secret set` | | [Runs & iterations](/guides/coding-agent-optimization/runs) | `tpc sim run` | `list`, `get`, `logs`, `actions` | | [Experiments](/guides/coding-agent-optimization/experiments) | `tpc sim experiment` | `create`, `run --watch`, `results` | | [Signals](/guides/coding-agent-optimization/signals) | `tpc sim experiment` | `validate-signal-config`, `signals` | ## What you get from each run * A pass/fail verdict and a 0–100 score against your goals * The complete agent transcript: every message, tool call, and thinking step * An archive of the sandbox after the run, so you can inspect exactly what the agent built * Token usage, cost, and duration * Signal values — custom metrics you define in YAML, extracted from the run automatically ## Try it from the CLI With the [tpc CLI](/cli/overview), a task and the agent that attempts it live in a small directory, and one command runs the whole thing: ```bash theme={null} # One-time setup curl -fsSL https://cli.promptingco.com/install.sh | bash tpc auth login ``` ```text theme={null} my-task/ ├── task.json # what to do + how success is scored ├── instruction.md # the prompt the agent receives └── environment.json # which agent/model attempts it (optional) ``` ```bash theme={null} # Create the task and environment if needed, then run — one command, from nothing tpc sim run ./my-task --scope pro-org/my-product ``` `tpc sim run ./my-task --scope pro-org/my-product` is idempotent: it reuses a matching task and environment if they already exist, updates them if the files changed, and creates them if they're new — so running it again never makes duplicates. Run `tpc sim spec` to print the full `task.json` contract, or `tpc sim task export <task-id>` to turn an existing task into a directory like this. To compare several agents on the same tasks, group them into an [experiment](/guides/coding-agent-optimization/experiments): ```bash theme={null} tpc sim experiment create --name "Quickstart friction" --task-ids task_abc --env-ids env_1,env_2 --scope pro-org/my-product tpc sim experiment run exp_789 --watch --scope pro-org/my-product # trigger and follow to completion tpc sim experiment results exp_789 --scope pro-org/my-product ``` Every command accepts `--format json` for scripting. The guides below cover the CLI workflow for each abstraction. ## Where to start * [Tasks](/guides/coding-agent-optimization/tasks) — defining what agents should do and how success is measured * [Environments](/guides/coding-agent-optimization/environments) — configuring agents and sandboxes * [Runs & iterations](/guides/coding-agent-optimization/runs) — what happens during an attempt and what it records * [Experiments](/guides/coding-agent-optimization/experiments) — running iterations and reading results * [Signals](/guides/coding-agent-optimization/signals) — extracting custom metrics from runs * [Limits & constraints](/guides/coding-agent-optimization/limits) — the execution model and hard limits that shape how you write tasks # Runs & iterations Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/runs What happens during a single agent attempt, what it records, and how runs batch into iterations A **run** is a single attempt: one environment executing one task in a fresh sandbox. An **iteration** is one batch of runs within an experiment — every attached task executed against every attached environment. ## The lifecycle of a run Each run moves through these statuses: ```text theme={null} queued → creating_sandbox → running → evaluating → analyzing → completed ↘ failed ``` 1. **creating\_sandbox** — a fresh sandbox is provisioned and initialized with the task's files, commands, and secrets 2. **running** — the agent harness executes the instruction (agent execution is capped at 60 minutes; a full run, including evaluation and analysis, can take up to \~70 minutes) 3. **evaluating** — each goal's criteria are checked against the sandbox and transcript, producing a score and pass/fail verdict 4. **analyzing** — signals are extracted and the transcript is analyzed for friction points 5. **completed** — results are final; the sandbox is archived and destroyed Failed infrastructure steps are retried automatically; a run is only marked `failed` after retries are exhausted. ## What each run records * **Score and verdict** — overall 0–100 score and whether the run passed its goals * **Transcript** — the unified timeline of agent messages, thinking, tool calls, and results * **Goal results** — per-goal, per-criterion scores with evaluation details * **Sandbox archive** — a snapshot of the agent's home directory after the run, downloadable for inspection * **Usage** — tokens, estimated cost, and duration * **Snapshots** — the exact task definition and environment config used, frozen at run time Because runs snapshot their task and environment configuration at execution time, historical results always reflect the exact setup that produced them — editing a task later never rewrites old results. ## Iterations Runs inside an experiment are grouped into numbered iterations. Iterations are immutable: the signal config and aggregated results are frozen when the iteration runs, so you can compare iteration 5 to iteration 1 and trust that each reflects its moment in time. See [Experiments](/guides/coding-agent-optimization/experiments) for how iterations are triggered and how their results are generated. ## Inspecting runs from the CLI ```bash theme={null} # Find runs tpc sim run list --task-id task_abc --status failed # Inspect one run tpc sim run get run_123 # score, verdict, usage, snapshots tpc sim run logs run_123 # the execution log timeline tpc sim run actions run_123 # normalized agent actions # Deeper analysis of a run or a task's history tpc sim analysis get --run-id run_123 tpc sim analysis get --task-id task_abc ``` Use `--format json` on any of these to feed results into scripts or CI. # Signals Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/signals Extract custom metrics from runs with a YAML signal config Signals turn raw run transcripts into metrics. You define them once in a YAML config attached to an experiment; every run extracts its own values, and every iteration aggregates them into comparable numbers — no code required. Signals are distinct from [goals](/guides/coding-agent-optimization/tasks#goals-and-criteria): a goal is the pass/fail verdict for a single run, while a signal is a measurement aggregated across every run in an iteration. Goals answer "did this run succeed?"; signals answer "how do the environments differ?" ## Signal types and scopes A signal produces one value per run, typed as: * **boolean** — "did the agent fabricate an API?" * **number** — "how many tokens did the run use?" * **category** — "which install method did the agent choose?" (requires `category_enums`) Signals are extracted at one of two **scopes**: * `run` — one observation per run (the default) * `message` — an observation per matching message, then **folded** into a single per-run value (`sum`, `count`, `average`, `min`, `max`, or `histogram`). Message-scoped signals require a `target_role` (`assistant`, `user`, or `tool`) and a `fold`. ## Extraction methods | Method | How it works | Constraints | | - | - | - | | `pattern` | Regex over message content | `message` scope only; boolean (via `patterns`) or number (via `needle`) | | `stats` | Built-in run metrics: `duration`, `token_in`, `token_out`, `token_total`, `cost`, `tool_calls`, `turns`, `steps`, `status`, `termination_reason` | `run` scope only | | `llm` | A judge model evaluates content against your prompt | boolean or category; requires `modelId` and `prompt` | Run-scoped `pattern` and `llm` signals also declare a `source` — which part of the transcript to read: `codeText`, `assistantText`, `userText`, `thinkingText`, `toolCalls`, `toolResults`, `finalAnswer`, or `any`. ## Aggregates Aggregates fold per-run signal values into iteration-level metrics: `count`, `count_where`, `rate`, `sum`, `avg`, `min`, `max`, `median`, `mode`, `count_by_category`, `avg_by_category`, and `distribution`. Each aggregate references a signal by id and gets a display label. `rate` returns a fraction from 0 to 1 (truthy runs ÷ total runs), not a percentage. ## Example config ```yaml theme={null} version: 1 signals: # Message-scoped pattern: count hallucinated endpoints per run - id: fabricated-endpoint name: "Fabricated API endpoint" type: boolean scope: message target_role: assistant extract: method: pattern patterns: - name: legacy-v2-api regex: "api\\.acme\\.com/v2/" fold: fn: count # Run-scoped stat: total tokens - id: total-tokens name: "Total tokens" type: number scope: run extract: method: stats stat: token_total # Run-scoped LLM judge: did the agent give up? - id: agent-gave-up name: "Agent abandoned the task" type: boolean scope: run extract: method: llm source: finalAnswer modelId: deepseek/deepseek-v4-flash-0731 prompt: > Did the agent abandon the task or deliver a workaround instead of completing the instruction? Answer true if it gave up. aggregates: - id: fabrication-rate signal_id: fabricated-endpoint fn: rate label: "Share of runs with fabricated endpoints" - id: avg-tokens signal_id: total-tokens fn: avg label: "Average tokens per run" - id: give-up-rate signal_id: agent-gave-up fn: rate label: "Share of runs where the agent gave up" ``` Signal and aggregate ids must be kebab-case and unique. The config is validated on upload — mismatched scopes, missing folds, or aggregates referencing unknown signals are rejected with specific errors. For `llm` extraction, `modelId` is a gateway model id. The default small judge is `deepseek/deepseek-v4-flash-0731`. Stored configs that still name Claude Haiku 4.5 are rewritten to that id at resolve time. ## Working with signal configs from the CLI Validate locally before uploading — validation runs entirely client-side and needs no authentication: ```bash theme={null} tpc sim experiment validate-signal-config signals.yaml ``` The command exits `0` if the config is valid and `1` with specific errors if not, so it works as a CI check or pre-commit hook. Attach the config when creating the experiment, or update it later: ```bash theme={null} tpc sim experiment create --name "Docs friction" \ --task-ids task_abc --env-ids env_123 \ --signal-config signals.yaml tpc sim experiment update exp_789 --signal-config signals.yaml tpc sim experiment update exp_789 --clear-signal-config ``` After an iteration completes, read the extracted values: ```bash theme={null} # Iteration-level aggregates plus per-run values tpc sim experiment signals exp_789 # A specific iteration (defaults to the latest) tpc sim experiment signals exp_789 --iteration 1 # Machine-readable, for dashboards or regression checks tpc --format json sim experiment signals exp_789 ``` ## Versioning The signal config is stored on the experiment with a content hash. Each iteration freezes the config it ran with, so changing the config later never rewrites historical aggregates — the next iteration simply uses the new version. Every extracted value also keeps **evidence**: the transcript event it came from and a short snippet, so you can audit why a signal fired. # Tasks Source: https://docs.promptingcompany.com/guides/coding-agent-optimization/tasks Define what agents should accomplish and how success is measured A task tells the agent what to accomplish and tells the platform how to score the attempt. Both halves live on the task itself, so every environment that runs it is measured the same way. ## Anatomy of a task | Part | Purpose | | - | - | | **Instruction** | The prompt the agent receives — what to build, install, or accomplish | | **Goals** | Success criteria, each with weighted scoring and a passing threshold | | **Init files** | Files placed in the sandbox before the run: zip uploads or git repositories | | **Init commands** | Shell commands run during sandbox setup (installing dependencies, seeding data) | | **Secrets** | Named credentials exposed to the run as environment variables | ## Writing instructions Write instructions the way a real user would brief an agent — not the way you wish they would. The goal is to measure your product's agent experience, so avoid embedding hints the average user wouldn't provide: * **Good:** "Set up error tracking for this Express app using Acme." * **Too helpful:** "Install `@acme/sdk@2.1`, then call `acme.init()` with the DSN from the dashboard." ## Goals and criteria Each goal contains one or more **criteria**. A criterion has an evaluation type, a weight, and a max score. Goals are scored by `weighted_average`, `binary`, or `percentage`, against a passing threshold from 0–100. Criteria are evaluated by one of: | Evaluation | What it checks | | - | - | | `comparison` | A run metric against a threshold (duration, tokens, cost) | | `file_exists` | A file is present in the sandbox after the run | | `file_content_match` | File contents match a pattern | | `json_schema` | Output validates against a JSON Schema | | `bash_command` | A shell command exits 0 in the post-run sandbox | | `python_script` | A custom Python check passes | | `script_judge` | Your own verification script (exit 0 = pass) | | `llm_judge` | An LLM judges the transcript against a rubric | Prefer deterministic checks (`file_exists`, `bash_command`, `script_judge`) where possible — they're cheaper and more reproducible. Reserve `llm_judge` for genuinely subjective criteria like "did the agent follow the documented approach?" ## Sandbox setup Init files and commands prepare the sandbox before the agent starts: * **Zip upload** — extract an archive into the sandbox (default target: the agent's home directory) * **Git clone** — clone a repository at a specific ref; private repos authenticate via a secret reference * **Init commands** — run shell commands in order, each with a working directory and timeout The two compose, and the rule of thumb is simple: **init files put bytes in place** (a starter repo, fixtures, a docs bundle), while **init commands execute setup** (install dependencies, build, seed data). Use them together to start the agent from a realistic state, like a half-finished app that needs your product integrated — and keep this setup out of the instruction so you measure the task, not the plumbing. ## Secrets Secrets are encrypted credentials scoped to your organization (or to a single environment). Reference them by name in a task and they're injected as environment variables during the run — API keys never appear in the task definition or transcripts. Secrets are managed on environments — see [Environments](/guides/coding-agent-optimization/environments#secrets-from-the-cli) for the CLI workflow. ## Working with tasks from the CLI Tasks are created from a JSON file. Run `tpc sim spec` to print the full contract; a minimal `task.json` looks like: ```json theme={null} { "name": "Checkout regression", "description": "Validate checkout flow", "category": "coding", "prompt": "Open the app, add an item to cart, and complete checkout successfully.", "goals": [ { "name": "Checkout succeeds", "description": "The agent should add an item to the cart, proceed through the checkout flow, and reach a confirmation page without errors.", "evaluationType": "llm_judge", "model": "claude-sonnet-4-6", "passingThreshold": 70, "scoringMethod": "weighted_average" } ] } ``` `category` is one of `coding`, `research`, `documentation`, or `analysis`. Don't include a `product` field — the CLI injects the product from `--scope <org-slug>/<product-slug>`. ```bash theme={null} # Create the task tpc sim task create --file task.json --scope pro-org/my-product # Browse and inspect tasks tpc sim task list --search checkout --scope pro-org/my-product # Task detail — goals, init commands, init file names, linked environments tpc sim task get task_123 --scope pro-org/my-product # Update metadata, or replace goals/definition from a file tpc sim task update task_123 --name "Checkout regression v2" --scope pro-org/my-product tpc sim task update task_123 --file task.json --scope pro-org/my-product # Queue runs across the task's linked, enabled environments tpc sim task run task_123 --scope pro-org/my-product # ...or only on specific ones (comma-separate or repeat the flag) tpc sim task run task_123 --environment-id env_a,env_b --scope pro-org/my-product # Delete a task (soft delete; run history is kept) tpc sim task delete task_123 --scope pro-org/my-product ``` ## Run a task from a directory A task and the agent that attempts it can live together in a small, portable directory: ```text theme={null} checkout-regression/ ├── task.json # metadata + goals (no prompt — see below) ├── instruction.md # the prompt the agent receives └── environment.json # the agent config under test (optional) ``` An `environment.json` declares the agent config: ```json theme={null} { "name": "Claude Code + Sonnet", "agentConfig": { "harness": "claude", "provider": "anthropic", "model": "claude-sonnet-4-6" } } ``` ```bash theme={null} tpc sim run ./checkout-regression ``` One command reconciles the directory with your product and queues runs: it reuses a matching task and environment, updates them if the files changed, and creates them if they're new — so running it again never makes duplicates. Omit `environment.json` (or pass `--environment-id`) to run against environments that already exist. `tpc sim task export <task-id>` writes a directory in exactly this shape — including `environment.json` when the task has a single linked environment — so you can pull a task down, edit it, and run it anywhere. # Create content Source: https://docs.promptingcompany.com/guides/create-content Generate blog posts from your tracked prompts to educate AI about your business If AI doesn't know you, it won't recommend you. You need to educate AI about your business by creating **content** so it can train on it and fetch it to users via web search. [YouTube video player](https://www.youtube.com/embed/KP53RgfKV54) The most effective way to create content is to answer the specific questions users are already asking. Instead of guessing topics, this workflow lets you instantly generate blog posts from your tracked prompts, ensuring every piece fills a specific gap in your visibility. ## Create content from prompts * Navigate to the **Prompts** tab in the sidebar * Click the three dots beside the prompt you want to create content for * Choose **Create blog** * You'll be taken to the **Review drafts** section, which contains all the blogs you've generated that require review * Accept or reject the blog * If you accept, your blog will be published on the **Custom domain** you connected (e.g. ai.yourdomain.com/article-slug) * If you reject, give feedback so our AI learns ## Set up custom domain All content you publish is hosted on a **Custom domain** you connect. Before publishing, add your domain in Settings so your content appears at a URL like **ai.yourdomain.com** and is discoverable by AI via web search. ### Add a DNS record #### The Prompting Company * Open [Domains settings](https://app.promptingco.com/go/domains?connect=dns). **Connect your domain** opens with **Dedicated domain via DNS** selected * Enter a custom domain you want your content to be hosted on (e.g. **ai.yourdomain.com**) and click **Add domain** * Open the domain's **DNS settings** to get the CNAME record you need to add to your DNS provider #### Your DNS provider (e.g. Cloudflare, GoDaddy, Namecheap, etc.) * Go to DNS > **Manage DNS** * Add a record with the following values: | Type | Name | Value | | - | - | - | | CNAME | ai.yourdomain.com (replace with your domain) | web.tpcdns.com | * Turn off **Proxy** * Choose the lowest **TTL** ### Host content on a subpath (optional) Instead of a subdomain like `ai.yourdomain.com`, you can publish content on a path of your main site, like `www.yourdomain.com/info`. Your content then sits on the same domain as the rest of your site, rather than on a separate subdomain. A subpath works by adding a **reverse proxy rule** on your side: requests to `/info` and `/info/*` on your site get forwarded to an origin we host for you. Visitors and crawlers only ever see your domain. > [!NOTE] > > This is a configuration change on your hosting or CDN, not a code change to your site's pages. On Vercel/Next.js or Netlify it's a small config file change that ships with your next deploy. #### Connect the subpath 1. Open [Domains settings](https://app.promptingco.com/go/domains?connect=subpath). **Connect your domain** opens with **Subpath on your domain** selected 2. Enter your **Domain**. Include `www.` if your website uses it (e.g. `www.yourdomain.com`, not `yourdomain.com`) 3. Pick a **Path prefix**. `/info` works well, but you can use any path that doesn't already exist on your site (e.g. `/learn`, `/resources`) 4. Click **Add domain** 5. Open the domain's menu and choose **Proxy settings** #### Add the proxy rule **Proxy settings** shows your public content address (e.g. `https://www.yourdomain.com/info`), the origin to forward requests to, and the exact config for your website stack: Next.js, SvelteKit, Vercel, Netlify, Cloudflare, Nginx, Caddy, or Amazon CloudFront. Add that config to your site, or use **Copy prompt** to hand the setup to your coding agent. Whichever stack you use, the rule must: * Forward `/info` and `/info/*` to your origin, keeping the path and query string as-is * Send your origin hostname as the `Host` header, not your own domain. If this is wrong, the origin can't match the request and returns errors. * Pass the visitor's `User-Agent` and `Accept` headers through unchanged, so AI crawler traffic is attributed correctly If you use a CDN like Cloudflare in front of your site, add the rule there, since it receives requests first. #### Allow AI crawlers If your site uses bot protection (e.g. Cloudflare Bot Fight Mode or a WAF), make sure it doesn't challenge or block AI crawlers on `/info` and `/info/*`. These pages exist for crawlers to read, so a blocked crawler means the content never gets picked up. At minimum, allow: `GPTBot`, `OAI-SearchBot`, `ChatGPT-User`, `ClaudeBot`, `PerplexityBot`, `Google-Extended`, `Bingbot`, `Googlebot`. Also check that your `robots.txt` doesn't disallow `/info`. #### Verify Once the rule is live, click **Verify connection** in **Proxy settings** to check that your public content address loads through your proxy. Your domain's card in **Settings > Website > Domains** also shows a **Sitemap** status, which checks `/info/sitemap.xml` and whether your main site's `robots.txt` lists that sitemap (see below). You can also check that both a browser and a crawler get a `200`: ```bash theme={null} curl -I https://www.yourdomain.com/info curl -I -A "GPTBot" https://www.yourdomain.com/info ``` If the second command returns `403` or a challenge page, your bot protection is still blocking crawlers. #### Indexing on a subpath Use your subpath sitemap in the indexing steps below: `https://www.yourdomain.com/info/sitemap.xml`. If your main domain is already verified in Google Search Console, you don't need a new property. Just submit the sitemap there. Also add it to your main site's `robots.txt`: ```text theme={null} Sitemap: https://www.yourdomain.com/info/sitemap.xml ``` ### Submit indexing to Google & Bing Ensure your custom domain is indexable by Google and Bing by submitting it for indexing. Replace ai.yourdomain.com with your domain in the URLs below. **Google:** * Go to **Google Search Console** * Click **Add property** * Choose **Domain** (the left option) and enter your domain (e.g. ai.yourdomain.com) * Follow the instructions to add DNS records * Go to the **Sitemaps** tab and submit [https://ai.yourdomain.com/sitemap.xml](https://ai.yourdomain.com/sitemap.xml) **Bing:** * Go to **Bing Webmaster Tools** * Choose **Import from Google Search Console** * Go to the **Sitemaps** tab and submit [https://ai.yourdomain.com/sitemap.xml](https://ai.yourdomain.com/sitemap.xml) # Knowledge base Source: https://docs.promptingcompany.com/guides/knowledge-base Understand how your product's facts and guidance improve prompts, content, and factual accuracy Your knowledge base is the shared repository of facts and guidance about a product. Think of it like a private, product-specific library that gives The Prompting Company the context it needs to answer and write accurately. It can include: * Product descriptions, features, and differentiators * Audience, customer, and use-case information * Positioning, competitors, and approved claims * Writing guidance and content rules * Source material imported from your website, documentation, and other trusted pages Each product has its own knowledge base, so its context stays separate from your other products. ## How the knowledge base is used The Prompting Company uses your knowledge base as grounding for product-specific work across the platform: * **Prompt suggestions and refinement:** Product context helps generate relevant questions that your audience may ask AI assistants. * **Content generation:** Facts, positioning, and writing guidance help generated content stay accurate and consistent with your product. * **Workspace assistant:** The assistant searches relevant knowledge base files before completing work that depends on product facts. * **Factual accuracy:** Product claims can be checked against the knowledge base and the sources you trust. The knowledge base supports these workflows; it does not publish its files as customer-facing content. ## Add and maintain knowledge During product setup, confirm the website and documentation URLs that should seed your knowledge base. To add more information later: 1. Select your product and open **Knowledge** in the sidebar. 2. From **Overview**, select **Add link** to import a trusted page. 3. Ask the workspace assistant to add or correct facts, positioning, or guidance in plain language. 4. Open **Files** to inspect the information and content rules stored for the product. 5. Review proposed changes before they become part of the knowledge base. Keep the knowledge base current when product features, pricing, positioning, or approved claims change. More complete and accurate source material gives the platform better context for future prompts, content, and analysis. > [!TIP] > > Add authoritative sources that describe the product directly. Avoid pages with outdated claims or information that applies to a different product. # Metrics Source: https://docs.promptingcompany.com/guides/metrics Understand share of voice, industry rankings, AI traffic, and content analytics Metrics help you track how your product appears in AI responses and how AI discovers your content. [YouTube video player](https://www.youtube.com/embed/xH91qnRgQdY) ## Share of voice Share of voice is how often your product is mentioned when we run your prompts across AI models like ChatGPT and Perplexity. As you publish content to target those prompts, your content gets cited and your product gets mentioned, therefore increasing your share of voice. ## Industry rankings Industry rankings list the top-mentioned competitors in your tracked prompts, each with its share of voice. Click on a competitor to see how their share of voice changes over time, which prompts they win, and where they lead versus where you lead. ## AI traffic AI traffic tracks when AI visits your content, visualizing the raw hits from AI agents, crawlers, and search bots on your custom domain in real-time. * **Total visits:** Number of AI traffic during the selected period * **Traffic graph:** See how your content gets AI traffic over time * **Top bots:** See which AI agents and crawlers visit your domain most frequently * **Top pages:** See which content gets the most AI traffic ## Content analytics Cited content shows where AI models get information when answering user prompts. A table lists the specific URLs AI cites, which models cite them, and how many times each URL appears in answers. * **On page:** Content you own (site, blog, docs). Focus on improving and expanding on-page content so AI has more to reference. * **Off page:** Third-party sources AI pulls from. Use this to see who influences AI answers and where to invest. # Quickstart guide Source: https://docs.promptingcompany.com/guides/quickstart-guide The fastest way to get started with The Prompting Company [YouTube video player](https://www.youtube.com/embed/QwbZS4q5488?si=Has9vi84sP6tyKHh) ## Step 1: Add your prompts **Prompts** are the questions you want your product to be found for. We run them across AI models like ChatGPT and Perplexity to see how your product gets mentioned in responses. [YouTube video player](https://www.youtube.com/embed/aFZmCK5Dnhk) Each day, we give you 10 prompts based on your product and website. Our AI uncovers real questions driving traffic. * Navigate to the **Prompts** tab in the sidebar * Click **Add prompts** * Under **Select from suggested prompts**, give a thumbs up to the prompts you want to start tracking or thumbs down to the prompts you don't like. Then, give a reason why you don't like a certain prompt so our AI learns If you decide to manually add your own prompts, go to **Write new prompts** instead. The platform uses your product's facts and guidance to make prompt suggestions and other generated work more relevant. Learn [what the knowledge base contains and how to maintain it](./knowledge-base). **Examples:** * How do startups manage cash, runway, and spend in one place? * What is the best business banking platform for startups? * Is there a single platform to manage startup banking, cards, and payments? ## Step 2: Create your content If AI doesn't know you, it won't recommend you. You need to educate AI about your business by creating **content** so it can train on it and fetch it to users via web search. [YouTube video player](https://www.youtube.com/embed/KP53RgfKV54) The most effective way to create content is to answer the specific questions users are already asking. Instead of guessing topics, this workflow lets you instantly generate blog posts from your tracked prompts, ensuring every piece fills a specific gap in your visibility. * Navigate to the **Prompts** tab in the sidebar * Click the three dots beside the prompt you want to create content for * Choose **Create blog** * You'll be taken to the **Review drafts** section, which contains all the blogs you've generated that require review * Accept or reject the blog * If you accept, your blog will be published on the **Custom domain** you connected (e.g. ai.yourdomain.com/article-slug) * If you reject, give feedback so our AI learns ## Step 3: View your results [YouTube video player](https://www.youtube.com/embed/xH91qnRgQdY) ### Share of voice **Share of voice** is how often your product is mentioned when we run our prompts across AI models like ChatGPT and Perplexity. As you publish content to target those prompts, your content gets cited and your product gets mentioned, therefore increasing your share of voice. ### Industry rankings **Industry rankings** list the top-mentioned competitors in your tracked prompts, each with its share of voice. Click on a competitor to see how their share of voice changes over time, which prompts they win, and where they lead versus where you lead. ### AI traffic **AI traffic** tracks when AI visits your content, visualizing the raw hits from AI agents, crawlers, and search bots on your custom domain in real-time. * **Total visits:** Number of AI traffic during the selected period * **Traffic graph:** See how your content gets AI traffic over time. Distinguish traffic by model, identify spikes, and trace which content drove the influx * **Top bots:** See which AI agents, crawlers, and search bots visit your domain most frequently * **Top pages:** See which content gets the most AI traffic If you publish a new page and see zero traffic here, AI crawlers aren't finding it. High traffic from **Inference** bots (like OpenAI User) confirms your content is being actively served to people in real-time AI chats. The pages that get the most traffic reflect the questions people are already asking LLMs. We use AI traffic data to shape your suggested prompts: 80% are aligned with topics that already drive traffic, and 20% are reserved for exploring new topics. ### Content analytics **Cited content** shows where AI models get information when answering user prompts. A table lists the specific URLs AI cites, which models cite them, and how many times each URL appears in answers. * **On page:** Content you own (site, blog, docs). If your or your competitors' pages are cited a lot, focus on improving and expanding on-page content so AI has more to reference. * **Off page:** Third-party sources AI pulls from: articles, comparisons, reviews, listicles, forums. Use this to see who influences AI answers and where to invest. # TPC Benchmarks in ChatGPT Source: https://docs.promptingcompany.com/mcp/benchmarks Use the TPC Benchmarks plugin in ChatGPT to look up measured results on whether an AI coding agent can integrate a developer API from its documentation. TPC Benchmarks answers one question about a developer API, SDK, or tool: can a real AI coding agent go from the product's documentation to a first successful integration? The Prompting Company (TPC) runs AI coding agents against each product's public documentation and records what happens. Every attempt ends as passed, failed, or blocked. The plugin reports those results inside ChatGPT, so you can choose or compare products with measured data. The plugin is free. You do not sign in, it does not change anything in your accounts, and it does not ask for credentials. The only thing it writes is a benchmark request, and only when you ask for one. ## Add the plugin In ChatGPT, add the TPC Benchmarks plugin. There is nothing to configure. The plugin is a remote MCP server. To use it from ChatGPT developer mode or another MCP client that supports remote servers, add this URL: ```text theme={null} https://benchmarks.promptingcompany.com/mcp ``` ## Tools | Tool | What it does | | - | - | | `search_benchmarks` | Returns results for a product or category as text. | | `show_benchmarks` | Shows the same results as cards. Products are ordered by overall score. Products in the same category get a comparison table with an Overall column and a weekly overall score trend chart, with a view of the weekly experience score per task. | | `request_benchmark` | Asks the TPC team to benchmark a product that is not covered yet, from its website or docs URL and an optional note. ChatGPT asks you to confirm first. Requests are reviewed and not guaranteed to be benchmarked. Records the request; if the product is already shown in this app (3 or more benchmark runs), it also returns a link to its results. | | `get_benchmark_trends` | Returns the weekly overall and experience score history of the matched products as data, for clients that cannot show cards or for questions about how a score has changed. | `search_benchmarks`, `show_benchmarks` and `get_benchmark_trends` are read-only. `request_benchmark` only records a request; it never changes or deletes a result. ## Example prompts * Compare agent onboarding benchmark results for search APIs. * How have Exa and Firecrawl's benchmark scores trended over recent weeks? * Show benchmark cards for email APIs that send transactional email. * Request a benchmark for acme.dev. You can ask about a product, a category, or a task in a category. If your question names no covered product or category, the plugin matches it to the closest category or task by meaning. ## What the results include For each product: * Completion rate: the share of attempts that reached a first successful integration. * Passed, failed, and blocked counts, and the total number of attempts. * Average successful run time. * An overall score from 0 to 100 that averages the experience score and an agent readiness score. The experience score comes with letter grades from S to D for five dimensions: Install, Auth, Execute, Docs, and Current. Auth and Execute carry the most weight. A product with no agent readiness scan shows its experience score. * The date of the last test. * A link to the product's full benchmark page on promptingcompany.com. Products, cards and comparison tables are ordered by overall score, falling back to the experience score for a product with no agent readiness scan. A category with several tasks ranks products by a task only when your question is about that task. The weekly chart plots each product's overall score, its experience for that week averaged with the agent readiness score of the latest TPC benchmark scan up to that week, starts a product's line at its first scan, and marks products with no scan as experience only. A card shows the overall score (or the experience score when there is no agent readiness scan) with the experience and agent readiness scores beneath it, a passed, failed, and blocked bar, the five grades, the last test date, and a **View benchmark** button. A task that a product does not offer through its public API shows as not supported, with the documentation that shows it. It is left out of the product's scores. Benchmark results are informational. They describe how AI coding agents performed on the days they were tested, and they are not a guarantee of how a product will work for you. ## Coverage The plugin covers the categories on the live [TPC benchmarks leaderboard](https://promptingcompany.com/benchmarks) that have at least one product with 3 or more benchmark attempts. The leaderboard itself applies the same minimum: a product with fewer attempts, and a category with no such product, is not listed there or in the plugin. The categories and products grow as new benchmarks run. A product that is not on the leaderboard returns no results, and the plugin lists the categories it does cover. ## Limits Each user can make 60 lookups per 10 minutes. After that, the plugin asks you to try again shortly. Each user can also request up to 5 benchmarks per day. ## Data handling * The plugin receives the arguments ChatGPT sends, such as the search text, category, or product names. * Search text that names no covered product or category goes to a TPC-hosted embedding model, and to a language model judge if the match is uncertain. It is not used to train models. * The plugin stores a keyed hash of the ChatGPT user and session identifiers, card events such as shown and link opened, timestamps, and error and latency data, for 90 days. * For a benchmark request, TPC stores the product URL, the optional note you give and the time, with a request ID that is a keyed one-way hash of your ChatGPT user identifier and the product host, used to recognise a repeat request, so the team can review it. The first request for a new product host is also posted to TPC's Slack workspace with its URL and note. A keyed hash of your user identifier is also kept in a daily rate-limit counter that expires at the end of the UTC day. The plugin does not ask for or store your email address. * It does not store your location, IP address, raw user agent, or raw ChatGPT identifiers. * Card links open through `benchmarks.promptingcompany.com`, which counts the visit and redirects to promptingcompany.com. It sets a visit cookie that lasts 30 minutes on that domain only. See the [privacy policy](https://promptingcompany.com/privacy-policy) for details. ## Support Email [support@promptingco.com](mailto:support@promptingco.com) with questions, problems, or feedback about TPC Benchmarks. The [terms of use](https://promptingcompany.com/term-of-use) apply to the plugin. # How is my product doing in AEO? Source: https://docs.promptingcompany.com/mcp/check-aeo Ask your agent how your product shows up in AI answers, and see which MCP tools it uses to answer. Ask your agent this, with `<product-name>` replaced by your product's name: ```text theme={null} How is my product <product-name> doing in AEO? ``` The agent answers with numbers from TPC analytics for that product. ## Before you ask * Connect the server and sign in. See [Connect the MCP server](/mcp/connect). * If you belong to more than one organization, put your organization slug in the same message. See [Find your organization slug](/mcp/connect#find-your-organization-slug). * Use the product name as it appears in TPC. The agent searches for it. * Name a date range if you want one. Without one, the date window is the last 30 days. TPC measures share of voice on the prompts it tracks for the product. See [Add prompts](/guides/add-prompts). ## What the agent does The agent chooses its own calls. A typical answer uses these tools in this order. **1. Find the product** If you did not give your organization slug, `list_organizations` finds it. Then `list_products` with your `organizationSlug` and the product name as `query` returns the product's slug and ID, which the next calls need. **2. Get the headline numbers** `explore_analytics` with `metric: "sov"` and no `dimension`. It returns your share of voice (`sov`), `mentions`, and `runs` from the latest snapshot in the date window. **3. Break the numbers down** `explore_analytics` with `metric: "sov"` and one `dimension`. Use `competitor` for your rank among competitors, `engine` for each answer engine, and `prompt` or `topic` for share of voice on each prompt or topic. **4. Add context** `explore_analytics` with `metric: "citations"` and `dimension: "source"` for the sources answer engines cite, `metric: "sentiment"` for positive, neutral, and negative mentions per prompt, and `metric: "traffic"` for visits from AI crawlers and assistants. Each `explore_analytics` call returns one metric with at most one dimension, as `columns` and `rows`, along with the product and date window it used. > [!NOTE] > > Without a dimension, or with `dimension: "date"`, share of voice, mentions, and runs are trailing 30-day snapshot values. With `dimension: "date"`, each row is a separate snapshot, so do not add up mentions or runs across rows. ## What you get back The agent writes a summary from those calls. Depending on which calls it makes, the summary can include: * Your share of voice, mentions, and runs * Your rank among competitors * Share of voice for each answer engine, prompt, or topic * The sources answer engines cite, with citation counts * Positive, neutral, and negative mentions per prompt, with reasons for the negative ones and an optional week-over-week change * AI visits in total, or by date, page, model, or category See [Metrics](/guides/metrics) for what each number means. To act on the results, see [Help me improve the AEO of my product](/mcp/improve-aeo). # How often does ChatGPT suggest my plugin? Source: https://docs.promptingcompany.com/mcp/check-plugin-discovery Ask your agent how often ChatGPT discovers and suggests your product's plugin, and see which MCP tools it uses to answer. Ask your agent this, with `<product-name>` replaced by your product's name: ```text theme={null} How often does ChatGPT suggest the plugin for my product <product-name>? ``` The agent answers with numbers from TPC's ChatGPT plugin discovery measurement for that product. ## Before you ask * Connect the server and sign in. See [Connect the MCP server](/mcp/connect). * If you belong to more than one organization, put your organization slug in the same message. See [Find your organization slug](/mcp/connect#find-your-organization-slug). * Use the product name as it appears in TPC. The agent searches for it. * Your organization needs an Enterprise plan. * The product needs a ChatGPT plugin ID. If it has none, ask the agent to set it. Changing the plugin ID needs an owner or admin role. * The measurement uses the prompts in the product's plugin discovery lane. These are separate from the product's tracked prompts. If the lane is empty, ask the agent to add some. ## What the agent does The agent chooses its own calls. A typical answer uses these tools in this order. **1. Find the product** If you did not give your organization slug, `list_organizations` finds it. Then `list_products` with your `organizationSlug` and the product name as `query` returns the product's slug and ID, which the next calls need. **2. Get the headline numbers** `get_plugin_discovery` with no `dimension` returns the summary: measured and search runs, shortlisted, suggested, and card shown runs, the plugin's average rank in the search results, and the plugins ChatGPT picked instead. A product with no plugin ID set returns `optedIn: false`. **3. See the trend** `get_plugin_discovery` with `dimension: "date"` returns one row per UTC day from the first measured run through today, with that day's runs and rolling 30-day sums. It is not limited to 30 rows. A product with no plugin ID set or no runs returns `{ days: [] }`. **4. Compare with other plugins** `get_plugin_discovery_ranking` returns the top 10 plugins ChatGPT suggested, ranked by suggested runs. If your plugin is outside the top 10, it is returned separately. **5. Look at the prompts behind it** `list_plugin_discovery_prompts` returns each prompt in the lane with how often it has run and its last run. A run is one ChatGPT answer to a plugin discovery prompt. A plugin is shortlisted when it appears in the search results ChatGPT considered, suggested when ChatGPT recommends it in the answer, and card shown when ChatGPT renders its install card. ## What you get back The agent writes a summary from those calls. Depending on which calls it makes, the summary can include: * Measured, search, shortlisted, suggested, and card shown runs, and your plugin's average rank * The plugins ChatGPT picked instead of yours * A daily trend with rolling 30-day sums * The top 10 plugins by suggested runs, and where yours stands if it is outside them * The prompts in the lane, with runs, suggested runs, and last run ## Change what is measured Ask the agent to change the lane or the plugin ID. These tools write, so the agent asks for your go-ahead first. | Ask | Tool | Needs | | - | - | - | | Add a prompt (up to 500 characters) | `create_plugin_discovery_prompt` | Owner or admin role | | Rewrite a prompt | `update_plugin_discovery_prompt` | Owner or admin role | | Remove a prompt | `delete_plugin_discovery_prompt` | Owner or admin role | | Set or stop tracking a plugin ID | `update_plugin_discovery_settings` | Owner or admin role | Adding text that is already in the lane returns the existing prompt. Saving the same plugin ID again keeps the original opt-in date, and a different ID restarts it. The same data is available from the terminal. See [ChatGPT plugin discovery](/cli/commands/prompts#chatgpt-plugin-discovery) in the CLI reference. # Connect the MCP server Source: https://docs.promptingcompany.com/mcp/connect Add The Prompting Company MCP server to ChatGPT, Claude Code, Claude.ai, or another MCP client and sign in with your TPC account. The Prompting Company (TPC) MCP server lets an AI agent manage your TPC products, prompts, site content, and knowledge files, and read your product analytics. It is a remote server at: ```text theme={null} https://mcp.promptingco.com/mcp ``` You sign in with your TPC account through OAuth. The authorization server is `https://app.promptingco.com/api/auth`. Each tool calls the TPC API with your access token, so the agent can only reach organizations you are a member of. ## Tools | Area | Tools | | - | - | | Organizations | `list_organizations` | | Products | `list_products`, `get_product`, `create_product`, `update_product` | | Analytics | `explore_analytics`, `list_topic_status` | | Prompts | `list_prompts`, `create_prompt`, `update_prompt`, `delete_prompt` | | Topics | `list_prompt_topics`, `create_prompt_topic`, `update_prompt_topic`, `delete_prompt_topic` | | Views | `list_views`, `get_view`, `create_view`, `update_view`, `add_prompts_to_view`, `remove_prompts_from_view` | | Tracked URLs | `list_tracked_urls`, `create_tracked_url`, `update_tracked_url`, `delete_tracked_url` | | Prompt suggestions | `list_prompt_suggestions`, `generate_prompt_suggestions`, `update_prompt_suggestion`, `approve_prompt_suggestions`, `reject_prompt_suggestions` | | Content | `list_content`, `get_content`, `create_content_draft`, `revise_content_draft`, `generate_content_drafts`, `cancel_content_generation`, `update_content`, `approve_content_draft`, `reject_content_draft`, `publish_content`, `unpublish_content`, `delete_content`, `restore_content` | | Knowledge files | `list_knowledge_files`, `get_knowledge_file`, `put_knowledge_file` | | ChatGPT plugin discovery | `list_plugin_discovery_prompts`, `create_plugin_discovery_prompt`, `update_plugin_discovery_prompt`, `delete_plugin_discovery_prompt`, `get_plugin_discovery`, `get_plugin_discovery_ranking`, `update_plugin_discovery_settings` | Every tool except `list_organizations` needs an [organization slug](#find-your-organization-slug). Tools that work on one product also need its slug or ID. The agent looks these up with `list_organizations` and `list_products`. ## ChatGPT The Prompting Company is listed in the ChatGPT plugin directory, so you do not need the server URL. 1. Open [The Prompting Company](https://chatgpt.com/plugins/plugin_asdk_app_6acd8fe391b48191a1d6e6237bbd52bf) in the ChatGPT plugin directory. 2. Connect the plugin, then sign in to The Prompting Company in the browser and approve access. 3. Select **Try in chat** to start a conversation with the plugin. To disconnect the plugin later, open the same page and select **Manage**. ![The Prompting Company in the ChatGPT plugin directory, with Manage and Try in chat buttons and three example questions](https://mintcdn.com/thepromptingcompany/Br9-qqVA7QNr0NW8/images/chatgpt-plugin-listing.png?fit=max\&auto=format\&n=Br9-qqVA7QNr0NW8\&q=85\&s=30d345b48db87c669a1684340cecb4a5) ## Claude Code Add the server: ```bash theme={null} claude mcp add --transport http tpc https://mcp.promptingco.com/mcp ``` Then run this command in Claude Code, select `tpc`, and sign in: ```text theme={null} /mcp ``` Your browser opens. Sign in to The Prompting Company and approve access. `claude mcp add` adds the server to the current project only. To use it in every project, add `--scope user` to that command. ## Claude.ai and Claude Desktop 1. Open **Settings** > **Connectors**. 2. Select **Add custom connector**. 3. Enter a name, such as `TPC`, and the URL `https://mcp.promptingco.com/mcp`. 4. Connect, then sign in to The Prompting Company in the browser and approve access. ## Other MCP clients Clients that support remote MCP servers with OAuth use the same URL. Add `https://mcp.promptingco.com/mcp` as a remote HTTP server. The client registers itself and opens your browser to sign in, so you do not need a client ID or secret. ## Find your organization slug Every tool except `list_organizations` takes an `organizationSlug` argument. If you don't give the agent your slug, it calls `list_organizations`, which returns the organizations you are a member of, each with its name, slug, and ID. Your organization slug is the first part of the path when you open your organization at `app.promptingco.com`. Product pages follow the pattern `https://app.promptingco.com/<org-slug>/p/<product-slug>`. For example, in `https://app.promptingco.com/acme/p/acme-cloud`, the organization slug is `acme` and the product slug is `acme-cloud`. If you belong to more than one organization, put the slug in your message so the agent uses the right one: ```text theme={null} My organization slug is acme. ``` If you use the TPC CLI, `tpc org list` prints each organization as `Name (slug)`. See [Organizations](/cli/organizations). If a tool returns `organization not found`, check the slug. TPC returns that error for a slug that does not exist and for an organization you are not a member of. ## Next steps * [How is my product doing in AEO?](/mcp/check-aeo) * [Help me improve the AEO of my product](/mcp/improve-aeo) # Help me improve the AEO of my product Source: https://docs.promptingcompany.com/mcp/improve-aeo Ask your agent to find where your product falls short in AI answers and make the changes you approve in TPC. Ask your agent this, with `<product-name>` replaced by your product's name: ```text theme={null} Help me improve the AEO of my product <product-name> ``` The agent reads your analytics, prompts, content, and knowledge files, suggests changes, and makes the ones you approve. ## Before you ask * Connect the server and sign in. See [Connect the MCP server](/mcp/connect). * If you belong to more than one organization, put your organization slug in the same message. See [Find your organization slug](/mcp/connect#find-your-organization-slug). * Use the product name as it appears in TPC. * Decide how far the agent may go, for example drafts only, or drafts and publishing. * Generating content drafts needs an active or trial Pro or Enterprise subscription. ## What the agent does The agent chooses its own calls. A typical run follows these steps. **1. Find the product** `list_organizations` finds your organization slug if you did not give it. `list_products` returns the product's slug and ID, and `get_product` returns its description, keywords, differentiators, competitors, and product context. **2. Find the gaps** `explore_analytics` with `metric: "sov"`, `dimension: "prompt"`, `sortBy: "sov"`, and `sortDirection: "asc"` lists your tracked prompts from the lowest share of voice up. With `dimension` set to `topic` or `competitor`, it shows where you are weak and who ranks above you. With `metric: "citations"`, `dimension: "source"`, and `filters.productMentioned: "not_mentioned"`, it shows which sources answer engines cite when they leave your product out. `list_prompts` shows the prompts TPC tracks. **3. Check what exists** `list_content` lists your live pages, or drafts in review when the agent sets `status`. `get_content` reads one page or draft in full. `list_knowledge_files` and `get_knowledge_file` read the product's knowledge files. `list_prompt_suggestions` lists candidate prompts that are not tracked yet. **4. Propose and make changes** The agent proposes changes. After you approve them, it runs the write tools below. **5. Measure again** After the next prompt runs, the agent can repeat the same `explore_analytics` queries to see whether share of voice moved on those prompts. > [!TIP] > > The server tells the agent to write drafts for your lowest share-of-voice prompts with `generate_content_drafts` and their prompt IDs, so each draft stays linked to the prompt it targets. It uses `create_content_draft` only for text you already wrote. You can also say which prompts to write for, for example: "Generate drafts for my five lowest share-of-voice prompts." ## Write tools | Tool | What it changes | | - | - | | `create_content_draft` | Starts a draft from text you provide. It goes to review, not live. | | `revise_content_draft` | Replaces a review draft's text, or sends feedback for a rewrite. | | `generate_content_drafts` | Writes new drafts from tracked prompts. They go to review, not live. | | `cancel_content_generation` | Stops a generation that is still running. | | `update_content` | Edits a live page's copy, path, or settings. | | `approve_content_draft` | Approves a review draft and queues it for publishing. | | `reject_content_draft` | Sends a review draft back with a reason. | | `publish_content` | Publishes an approved draft. | | `unpublish_content` | Takes a published page back to review. | | `delete_content` | Removes a page or draft. Deleting a draft in review is permanent. | | `restore_content` | Brings an archived live page back. | | `create_prompt` | Creates a prompt for TPC to track across answer engines. | | `update_prompt` | A tracked prompt's text, topic, category, keywords, sources, or metadata. It also adds, removes, pauses, or resumes answer engines. A paused engine is hidden from every dashboard until you resume it, and nothing is deleted. | | `delete_prompt` | Archives a prompt. This tool cannot permanently delete prompts. | | `generate_prompt_suggestions` | Replaces the current prompt suggestions for the product, or for one topic, with a new batch. | | `update_prompt_suggestion` | A suggestion's text, persona, or answer engines. | | `approve_prompt_suggestions` | Approves suggestions. Approval creates tracked prompts and conversation queries. | | `reject_prompt_suggestions` | Rejects suggestions. | | `put_knowledge_file` | With `action: "put"`, creates or replaces a file in the product's [knowledge base](/guides/knowledge-base) on the live default branch. It cannot write `schema.md`. | | `update_product` | The product's name, domain, description, keywords, differentiators, or competitors. | ## Approval Your MCP client asks for your approval before it runs a write tool, unless you have allowed that tool to run without asking. The server marks each write tool as one that changes data. Its instructions also tell the agent to confirm with you first. That covers creating, updating, or deleting anything, writing a knowledge file, and approving prompt suggestions. > [!WARNING] > > Read these before you approve: > > * Deleting a draft in review with `delete_content` is permanent. You cannot restore it. > * `delete_prompt` archives a prompt. It cannot permanently delete one. > * `generate_prompt_suggestions` replaces the current suggestions. > * Approving prompt suggestions adds tracked prompts and may change future share of voice results. If a write tool times out, the change may still have gone through. Ask the agent to check before it retries. ## What you get back * The gaps the agent found and the changes it proposes * For each change you approve, the tool's result, such as new draft IDs and titles, the new or changed prompt, the number of suggestions approved or rejected, or the commit for a knowledge file * New drafts, which stay in review until you approve them. Generated drafts reach `pending_review` when generation finishes. You can also review drafts in TPC. See [Create content](/guides/create-content). # Advanced usage Source: https://docs.promptingcompany.com/ts-sdk/advanced-usage Advanced patterns and techniques for using The Prompting Company TypeScript SDK # Advanced usage Learn advanced patterns, error handling, and optimization techniques for The Prompting Company TypeScript SDK. ## Error Handling The SDK returns a structured response with an `ok` property to indicate success or failure. Always check this property before accessing data: ```typescript theme={null} import tpc from "@promptingcompany/sdk"; const client = new tpc({ productSlug: "your-product", organizationSlug: "your-org", }); async function getDocumentSafely(path: string) { try { const result = await client.document.getByPath(path); if (!result.ok) { // Handle API errors console.error('API Error:', result.error); throw new Error(`Failed to fetch document: ${result.error?.message || 'Unknown error'}`); } return result.data; } catch (error) { // Handle network errors, SDK errors, etc. console.error('SDK Error:', error); throw error; } } ``` ## Client Configuration ### Environment-Based Configuration Create different configurations for different environments: ```typescript theme={null} // lib/sdk-config.ts import tpc from "@promptingcompany/sdk"; interface SDKConfig { productSlug: string; organizationSlug: string; } function getSDKConfig(): SDKConfig { return { productSlug: process.env.TPC_PRODUCT_SLUG!, organizationSlug: process.env.TPC_ORG_SLUG!, }; } export const client = new tpc(getSDKConfig()); ``` ### Multiple Client Instances If you need to access multiple products or organizations: ```typescript theme={null} // lib/multi-client.ts import tpc from "@promptingcompany/sdk"; export const clients = { mainProduct: new tpc({ productSlug: "main-product", organizationSlug: "your-org", }), docsProduct: new tpc({ productSlug: "documentation", organizationSlug: "your-org", }), partnerOrg: new tpc({ productSlug: "shared-docs", organizationSlug: "partner-org", }), }; // Usage const mainDoc = await clients.mainProduct.document.getByPath("guide/intro"); const partnerdoc = await clients.partnerOrg.document.getByPath("api/reference"); ``` ## Caching Strategies ### Simple In-Memory Cache Implement caching to reduce API calls: ```typescript theme={null} // lib/cached-client.ts import tpc from "@promptingcompany/sdk"; class CachedSDKClient { private client: tpc; private cache = new Map<string, any>(); private ttl = 5 * 60 * 1000; // 5 minutes constructor(config: { productSlug: string; organizationSlug: string }) { this.client = new tpc(config); } async getDocumentByPath(path: string, useCache = true) { const cacheKey = `doc:${path}`; if (useCache && this.cache.has(cacheKey)) { const cached = this.cache.get(cacheKey); if (Date.now() - cached.timestamp < this.ttl) { return cached.data; } } const result = await this.client.document.getByPath(path); if (result.ok && useCache) { this.cache.set(cacheKey, { data: result, timestamp: Date.now(), }); } return result; } clearCache() { this.cache.clear(); } } export const cachedClient = new CachedSDKClient({ productSlug: process.env.PROMPTING_COMPANY_PRODUCT_SLUG!, organizationSlug: process.env.PROMPTING_COMPANY_ORG_SLUG!, }); ``` ### Next.js App Router with Caching Use Next.js's built-in caching with `unstable_cache`: ```typescript theme={null} // lib/cached-documents.ts import { unstable_cache } from 'next/cache'; import { client } from './prompting-company'; export const getCachedDocument = unstable_cache( async (path: string) => { const result = await client.document.getByPath(path); if (!result.ok) { throw new Error(`Failed to fetch document: ${path}`); } return result.data; }, ['document-by-path'], { revalidate: 300, // 5 minutes tags: ['documents'], } ); // Usage in Server Components export default async function DocumentPage({ params }: { params: { path: string } }) { const document = await getCachedDocument(params.path); return ( <div> <h1>Document: {params.path}</h1> <div>{document.content}</div> </div> ); } ``` ## Batch Operations If you need to fetch multiple documents efficiently: ```typescript theme={null} // lib/batch-operations.ts import { client } from './prompting-company'; export async function getMultipleDocuments(paths: string[]) { const results = await Promise.allSettled( paths.map(path => client.document.getByPath(path)) ); return results.map((result, index) => ({ path: paths[index], success: result.status === 'fulfilled' && result.value.ok, data: result.status === 'fulfilled' && result.value.ok ? result.value.data : null, error: result.status === 'rejected' ? result.reason : result.status === 'fulfilled' && !result.value.ok ? result.value.error : null, })); } // Usage const documents = await getMultipleDocuments([ 'en-us/contact', 'en-us/about', 'en-us/pricing', ]); documents.forEach(({ path, success, data, error }) => { if (success && data) { console.log(`✅ ${path}: ${data.content.substring(0, 50)}...`); } else { console.error(`❌ ${path}: ${error}`); } }); ``` ## React Hooks Create custom hooks for common patterns: ```typescript theme={null} // hooks/use-document.ts import { useState, useEffect } from 'react'; import { client } from '@/lib/prompting-company'; interface UseDocumentResult { document: any | null; loading: boolean; error: string | null; refetch: () => void; } export function useDocument(path: string): UseDocumentResult { const [document, setDocument] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const fetchDocument = async () => { try { setLoading(true); setError(null); const result = await client.document.getByPath(path); if (result.ok) { setDocument(result.data); } else { setError('Failed to fetch document'); } } catch (err) { setError(err instanceof Error ? err.message : 'Unknown error'); } finally { setLoading(false); } }; useEffect(() => { if (path) { fetchDocument(); } }, [path]); return { document, loading, error, refetch: fetchDocument, }; } // Usage in components export function DocumentViewer({ path }: { path: string }) { const { document, loading, error, refetch } = useDocument(path); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!document) return <div>Document not found</div>; return ( <div> <button onClick={refetch}>Refresh</button> <div>{document.content}</div> </div> ); } ``` ## TypeScript Utilities Create utility types for better type safety: ```typescript theme={null} // types/sdk.ts import tpc from "@promptingcompany/sdk"; // Extract the client type export type TPCClient = InstanceType<typeof tpc>; // Create a utility type for API responses export type APIResponse<T> = { ok: true; data: T; } | { ok: false; error: { message: string; code?: string; }; }; // Document type (adjust based on actual SDK response) export interface Document { content: string; path: string; title?: string; lastModified?: string; metadata?: Record<string, any>; } // Helper function with proper typing export async function safeAPICall<T>( apiCall: () => Promise<APIResponse<T>> ): Promise<T> { const result = await apiCall(); if (!result.ok) { throw new Error(result.error.message); } return result.data; } // Usage const document = await safeAPICall(() => client.document.getByPath("en-us/contact") ); ``` ## Development and Debugging ### Debug Mode Add debug logging during development: ```typescript theme={null} // lib/debug-client.ts import tpc from "@promptingcompany/sdk"; class DebugSDKClient { private client: tpc; private debug: boolean; constructor(config: { productSlug: string; organizationSlug: string }, debug = false) { this.client = new tpc(config); this.debug = debug || process.env.NODE_ENV === 'development'; } async getDocumentByPath(path: string) { if (this.debug) { console.log(`[SDK] Fetching document: ${path}`); console.time(`[SDK] ${path}`); } try { const result = await this.client.document.getByPath(path); if (this.debug) { console.timeEnd(`[SDK] ${path}`); console.log(`[SDK] Result for ${path}:`, result.ok ? 'SUCCESS' : 'ERROR'); if (!result.ok) { console.error(`[SDK] Error:`, result.error); } } return result; } catch (error) { if (this.debug) { console.timeEnd(`[SDK] ${path}`); console.error(`[SDK] Exception for ${path}:`, error); } throw error; } } } export const debugClient = new DebugSDKClient({ productSlug: process.env.TPC_PRODUCT_SLUG!, organizationSlug: process.env.TPC_ORG_SLUG!, }); ``` ## Performance Optimization ### Parallel Document Loading Load multiple documents in parallel for better performance: ```typescript theme={null} // components/multi-document-viewer.tsx import { useState, useEffect } from 'react'; import { getMultipleDocuments } from '@/lib/batch-operations'; interface MultiDocumentViewerProps { paths: string[]; } export function MultiDocumentViewer({ paths }: MultiDocumentViewerProps) { const [documents, setDocuments] = useState<any[]>([]); const [loading, setLoading] = useState(true); useEffect(() => { async function loadDocuments() { setLoading(true); const results = await getMultipleDocuments(paths); setDocuments(results); setLoading(false); } loadDocuments(); }, [paths]); if (loading) { return <div>Loading {paths.length} documents...</div>; } return ( <div className="space-y-6"> {documents.map(({ path, success, data, error }) => ( <div key={path} className="border rounded-lg p-4"> <h3 className="font-semibold mb-2">{path}</h3> {success && data ? ( <div className="prose"> {data.content.substring(0, 200)}... </div> ) : ( <div className="text-red-600"> Error: {error} </div> )} </div> ))} </div> ); } ``` ## Best Practices 1. **Always check the `ok` property** before accessing response data 2. **Use TypeScript** for better development experience and error catching 3. **Implement caching** for frequently accessed documents 4. **Handle errors gracefully** with user-friendly error messages 5. **Use environment variables** for configuration 6. **Consider rate limiting** if making many API calls 7. **Implement retry logic** for network failures 8. **Use batch operations** when possible to reduce API calls ## Troubleshooting ### Common Issues **Document not found errors:** * Verify the document path exists in your organization * Check that your product slug is correct * Ensure your API key has access to the document **Network timeouts:** * Implement retry logic with exponential backoff * Consider using shorter timeouts for better UX * Add loading states to improve perceived performance **Memory issues with large documents:** * Implement pagination if available * Use streaming responses if supported * Consider lazy loading for large document collections **TypeScript errors:** * Ensure you're using the latest SDK version * Check that your TypeScript configuration is compatible * Use proper type guards when checking response objects # Introduction Source: https://docs.promptingcompany.com/ts-sdk/index Access your agentic markdown documentation data with our powerful TypeScript SDK # The TypeScript SDK The official TypeScript SDK for accessing agentic markdown documentation data from The Prompting Company platform. Build powerful applications that leverage your organization's documentation with full type safety and excellent developer experience. ## Getting Started Get up and running with the SDK in just a few minutes. > [card] [Start with the SDK](/ts-sdk/installation) > > Install the SDK and configure your development environment. ## Key Features Everything you need to integrate your documentation data. > [card] [TypeScript SDK](/ts-sdk/introduction) > > Full TypeScript support with complete type safety and autocompletion. > [card] [Easy Installation](/ts-sdk/installation) > > Install with npm, yarn, or pnpm and configure in minutes. > [card] [Quick Start Guide](/ts-sdk/quickstart) > > Build your first integration with step-by-step instructions. > [card] [Advanced Usage](/ts-sdk/advanced-usage) > > Learn advanced patterns, caching, and optimization techniques. ## Simple Integration Access your documentation data with just a few lines of code: ```typescript theme={null} import tpc from "@promptingcompany/sdk"; const client = new tpc({ productSlug: "your-product-slug", organizationSlug: "your-organization-slug", }); const doc = await client.document.getByPath("en-us/contact"); if (doc.ok) { console.log(doc.data?.content); } ``` ## Next Steps > [card] [View the Complete Guide](/ts-sdk/introduction) > > Learn about all SDK features and capabilities. # Installation Source: https://docs.promptingcompany.com/ts-sdk/installation Install and configure The Prompting Company TypeScript SDK in your project # Installation Get up and running with The Prompting Company TypeScript SDK in your Next.js or Node.js project. ## Prerequisites Before installing the SDK, ensure you have: * **Node.js** version 18.0 or higher * **npm**, **yarn**, or **pnpm** package manager * A **Next.js** project (recommended) or Node.js application ## Install the SDK Choose your preferred package manager: > [tab] npm > > ```bash theme={null} > npm install @promptingcompany/sdk > ``` > [tab] yarn > > ```bash theme={null} > yarn add @promptingcompany/sdk > ``` > [tab] pnpm > > ```bash theme={null} > pnpm add @promptingcompany/sdk > ``` ## Environment Setup Create a `.env.local` file in your project root and add your configuration: ```bash theme={null} # The Prompting Company Configuration TPC_API_KEY=your_api_key_here # Automatically read by the SDK TPC_ORG_SLUG=your_organization_slug TPC_PRODUCT_SLUG=your_product_slug ``` > [!NOTE] > > The SDK automatically reads the `TPC_API_KEY` environment variable, so you don't need to pass it explicitly in your code configuration. ### Getting Your API Key You'll need to create an organization-scoped API key from The Prompting Company dashboard: 1. **Open your organization**: Sign in to [The Prompting Company](https://app.promptingco.com) and select the organization workspace for your integration. 2. **Go to API Keys Settings**: Visit `https://app.promptingco.com/{orgSlug}/settings/api-keys`, replacing `{orgSlug}` with your organization slug. 3. **Create New Key**: Click "New API key", name the key, and grant the minimum scopes your integration needs. 4. **Copy the Key**: Save the generated API key securely. It will only be shown once. ### Finding Your Organization and Product Slugs Your organization slug is part of the organization URL: `https://app.promptingco.com/{orgSlug}`. Product slugs are available from the product URL after opening a product in that organization. > [!WARNING] > > Never commit API keys to version control. Always use environment variables and add `.env.local` to your `.gitignore` file. ## TypeScript Configuration If you're using TypeScript, the SDK includes built-in type definitions. No additional configuration is required, but you can enhance your experience by adding these compiler options to your `tsconfig.json`: ```json theme={null} { "compilerOptions": { "strict": true, "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true } } ``` ## Verify Installation Create a simple test file to verify your installation: ```typescript theme={null} // test-sdk.ts import tpc from '@promptingcompany/sdk'; const client = new tpc({ organizationSlug: process.env.TPC_ORG_SLUG!, productSlug: process.env.TPC_PRODUCT_SLUG!, }); console.log('SDK installed successfully!'); ``` Run the test: ```bash theme={null} npx tsx test-sdk.ts ``` If you see "SDK installed successfully!" without errors, you're ready to proceed. ## Next.js Configuration For Next.js applications, you may want to configure the SDK in a utility file: ```typescript theme={null} // lib/prompting-company.ts import tpc from '@promptingcompany/sdk'; if (!process.env.TPC_API_KEY) { throw new Error('TPC_API_KEY is required'); } if (!process.env.TPC_ORG_SLUG) { throw new Error('TPC_ORG_SLUG is required'); } if (!process.env.TPC_PRODUCT_SLUG) { throw new Error('TPC_PRODUCT_SLUG is required'); } export const client = new tpc({ organizationSlug: process.env.TPC_ORG_SLUG, productSlug: process.env.TPC_PRODUCT_SLUG, // TPC_API_KEY is automatically read by the SDK }); ``` ## Troubleshooting ### Common Issues **Module not found error:** * Ensure you've installed the package correctly * Restart your development server after installation **Environment variable errors:** * Verify your `.env.local` file is in the project root * Check that variable names match exactly * Restart your development server after changing environment variables **TypeScript errors:** * Make sure you're using TypeScript 4.5 or higher * Verify your `tsconfig.json` includes the necessary compiler options ## Next Steps Now that you have the SDK installed, let's build your first integration: > [card] [Quick Start Guide](/ts-sdk/quickstart) > > Build your first integration and start accessing your documentation data. # Introduction Source: https://docs.promptingcompany.com/ts-sdk/introduction Get started with The Prompting Company TypeScript SDK to access agentic markdown documentation data # TypeScript SDK The Prompting Company TypeScript SDK provides developers with seamless access to agentic markdown documentation data stored on our platform. Whether you're building AI-powered applications, documentation sites, or content management systems, our SDK makes it easy to integrate our rich documentation data into your projects. ## What You Can Do With The Prompting Company TypeScript SDK, you can: * **Access Documentation Data**: Retrieve agentic markdown documentation from your organization's data store * **Query by Organization**: Scope your requests to specific organizations using organization slugs * **Filter by Product**: Access documentation for specific products using product slugs * **Simple Configuration**: Easy setup with just organization and product slugs * **TypeScript Support**: Enjoy full type safety and autocompletion in your development environment ## Key Features > [card] Type Safety > > Built with TypeScript for complete type safety and excellent developer experience. > [card] Simple Configuration > > Easy setup with just organization and product slugs - no API keys needed. > [card] Rich Data Access > > Access comprehensive agentic markdown documentation with full metadata. > [card] Next.js Optimized > > Designed to work seamlessly with Next.js applications and React components. ## Prerequisites Before you begin, you'll need: * A Node.js environment (version 18 or higher) * An account with The Prompting Company * Your organization slug and product slug(s) ## Next Steps Ready to get started? Follow our step-by-step guide: > [card] [Installation & Setup](/ts-sdk/installation) > > Install the SDK and configure your development environment. > [card] [Quick Start Guide](/ts-sdk/quickstart) > > Build your first integration in minutes with our quick start guide. # Quickstart guide Source: https://docs.promptingcompany.com/ts-sdk/quickstart Build your first integration with The Prompting Company TypeScript SDK in a Next.js application # Quickstart guide Get up and running with The Prompting Company TypeScript SDK using the **Next.js Agent MD pattern**. This guide will walk you through creating a dynamic markdown serving system that allows users to access your agentic documentation through clean `.md` URLs. ## What You'll Build By the end of this guide, you'll have: * **Clean URL routing**: Users can access documents like `yoursite.com/docs/guide.md` * **Dynamic content serving**: Documents are fetched from The Prompting Company platform * **Automatic middleware**: URL rewriting handles `.md` extensions transparently * **Scalable architecture**: Support for nested document structures ## How It Works The implementation uses a two-part system: 1. **Middleware**: Intercepts requests ending in `.md` and rewrites them internally 2. **API Route Handler**: Fetches the actual markdown content using the SDK **Example Flow:** ``` User visits: /docs/getting-started.md ↓ (middleware rewrites) Internal route: /md/docs/getting-started ↓ (API handler processes) Returns: Markdown content from your organization ``` ## Prerequisites Before starting, make sure you have: * ✅ [Installed the SDK](/ts-sdk/installation) * ✅ A Next.js 13+ application with App Router * ✅ Your API key, organization slug, and product slug ## Step 1: Create the Middleware First, create a middleware file to handle URL rewriting for `.md` extensions: ```typescript theme={null} // src/middleware.ts import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; export function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname; // Check if the URL ends with .md extension if (pathname.endsWith(".md")) { // Remove the .md extension from the path const pathWithoutMd = pathname.slice(0, -3); // Create the new URL with /md prefix const newUrl = new URL(`/md${pathWithoutMd}`, request.url); // Rewrite the request to the new path return NextResponse.rewrite(newUrl); } return NextResponse.next(); } export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ "/((?!api|_next/static|_next/image|favicon.ico).*)", ], }; ``` ### How the Middleware Works 1. **Intercepts Requests**: Captures all requests except API routes and static files 2. **Detects .md Extensions**: Checks if the URL ends with `.md` 3. **URL Rewriting**: Transforms `/docs/guide.md` → `/md/docs/guide` internally 4. **Transparent Process**: Users see clean URLs, but internal routing handles the logic ## Step 2: Create the MD Route Handler Create the API route handler that will process the rewritten URLs and fetch markdown content: ```typescript theme={null} // src/app/md/[[...path]]/route.ts import tpc from "@promptingcompany/sdk"; const client = new tpc({ productSlug: process.env.TPC_PRODUCT_SLUG!, organizationSlug: process.env.TPC_ORG_SLUG!, // TPC_API_KEY is automatically read by the SDK }); export async function GET( request: Request, { params }: { params: Promise<{ path?: string[] }> } ) { // Await the params promise (Next.js 15+ pattern) const { path } = await params; const pathArray = path || []; // Join the path segments to create a document path const documentPath = pathArray.join("/"); try { const document = await client.document.getByPath(documentPath); if (!document.ok || !document.data) { return new Response("Document not found", { status: 404 }); } return new Response(document.data.content, { headers: { "Content-Type": "text/markdown; charset=utf-8", }, }); } catch (error) { console.error('Error fetching document:', error); return new Response("Internal server error", { status: 500 }); } } ``` ### Understanding the Route Handler * **Dynamic Route**: `[[...path]]` captures multiple path segments (optional catch-all) * **Next.js 15+ Pattern**: `params` is now a Promise that must be awaited * **Parameter Destructuring**: `{ path } = await params` extracts the path segments * **Path Processing**: Joins segments like `['docs', 'api', 'auth']` → `"docs/api/auth"` * **SDK Integration**: Uses the TypeScript SDK to fetch documents * **Error Handling**: Returns proper HTTP status codes (404, 500) * **Content Type**: Sets correct MIME type (`text/markdown; charset=utf-8`) ## Step 3: Understanding the Complete Flow Here's how the entire system works together: ### 1. User Request ``` User visits: https://yoursite.com/docs/getting-started.md ``` ### 2. Middleware Processing ```typescript theme={null} // src/middleware.ts processes the request "/docs/getting-started.md" ↓ (removes .md extension) "/docs/getting-started" ↓ (adds /md prefix) "/md/docs/getting-started" ``` ### 3. Route Handler Execution ```typescript theme={null} // src/app/md/[[...path]]/route.ts receives: const { path } = await params; // Next.js 15+ requires await pathArray = ["docs", "getting-started"] ↓ (joins path segments) documentPath = "docs/getting-started" ↓ (calls SDK) client.document.getByPath("docs/getting-started") ``` ### 4. Response ``` Returns: Raw markdown content with proper MIME type Content-Type: text/markdown; charset=utf-8 ``` ## Step 4: Directory Structure Your project should have this structure: ``` src/ ├── middleware.ts # URL rewriting logic ├── app/ │ ├── md/ │ │ └── [[...path]]/ │ │ └── route.ts # Markdown handler │ ├── layout.tsx │ └── page.tsx └── (other files) ``` ### Key Points: * **Middleware Location**: Must be in `src/middleware.ts` (or root `middleware.ts`) * **Dynamic Route**: `[[...path]]` captures any number of path segments * **Route Handler**: Only needs the `GET` method for serving markdown * **Error Handling**: Proper HTTP status codes for missing documents ## Step 5: Testing Your Implementation ### 1. Start Your Development Server ```bash theme={null} npm run dev ``` ### 2. Test the URL Pattern Your implementation should now handle these URL patterns: **✅ Working URLs:** ``` http://localhost:3000/docs/getting-started.md http://localhost:3000/api/auth.md http://localhost:3000/guides/installation.md http://localhost:3000/nested/folder/structure/document.md ``` **How to Test:** 1. Visit any URL ending in `.md` 2. Check browser network tab - you should see: * Request to `yoursite.com/docs/guide.md` * Response with `Content-Type: text/markdown` * Raw markdown content displayed ### 3. Verify Document Paths The URL structure maps to your organization's document paths: ``` URL: /docs/getting-started.md ↓ Document Path: "docs/getting-started" ↓ SDK Call: client.document.getByPath("docs/getting-started") ``` Make sure your document paths in The Prompting Company platform match your intended URL structure. ### 4. Test Error Handling **404 Testing:** * Visit `/nonexistent/document.md` * Should return "Document not found" with 404 status **Path Testing:** * Root level: `/readme.md` → document path: `"readme"` * Nested: `/api/auth/oauth.md` → document path: `"api/auth/oauth"` ## Step 6: Command Line Testing (Optional) For debugging, you can test the SDK directly: ```typescript theme={null} // test-sdk.ts import tpc from "@promptingcompany/sdk"; const client = new tpc({ productSlug: process.env.TPC_PRODUCT_SLUG!, organizationSlug: process.env.TPC_ORG_SLUG!, // TPC_API_KEY is automatically read by the SDK }); const doc = await client.document.getByPath("docs/getting-started"); if (!doc.ok) { console.error('Error:', doc); process.exit(1); } console.log('Success! Document content:'); console.log(doc.data?.content?.substring(0, 200) + '...'); ``` Run with: ```bash theme={null} npx tsx test-sdk.ts ``` ## Benefits of This Pattern The Next.js Agent MD pattern provides several advantages: ### ✅ **SEO-Friendly URLs** Clean URLs like `/docs/guide.md` are easily indexed by search engines ### ✅ **Dynamic Content** Documents are fetched from your CMS in real-time, no static generation needed ### ✅ **Scalable Architecture** Supports unlimited nested document structures without additional routing ### ✅ **Proper MIME Types** Browsers receive correct `text/markdown` content type for proper handling ### ✅ **Error Handling** Built-in 404 handling for missing documents with proper HTTP status codes ## Next Steps Congratulations! You now have a working Next.js Agent MD implementation. Here are ways to enhance it: > [card] [Advanced Usage](/ts-sdk/advanced-usage) > > Learn about caching, error handling, and optimization techniques. > [card] [GitHub Repository](https://github.com/promptingcompany/nextjs-agent-md) > > View the complete reference implementation on GitHub. ## Troubleshooting ### Common Issues **Middleware not working:** * Ensure `middleware.ts` is in the correct location (`src/middleware.ts` or root `middleware.ts`) * Check that your Next.js version supports middleware (12.2+) * Verify the matcher configuration excludes necessary paths **404 errors for valid documents:** * Confirm document paths in your organization match URL structure * Check environment variables are set correctly (`TPC_API_KEY`, `TPC_ORG_SLUG`, `TPC_PRODUCT_SLUG`) * Verify API key has `read:documentation` permissions **Route handler not found:** * Ensure the directory structure is correct: `src/app/md/[[...path]]/route.ts` * Check that the route file exports a `GET` function * Verify Next.js App Router is enabled (Next.js 13+) **SDK connection issues:** * Test the SDK directly with the command line example * Check network connectivity and API endpoint availability * Verify organization and product slugs are correct Need help? Contact [support@promptingco.com](mailto:support@promptingco.com) or visit our [platform](https://app.promptingco.com).