# Wihyu API authentication

Wihyu's API (https://api.wihyu.com) and MCP server (https://api.wihyu.com/v1/mcp) use one of:

1. **OAuth 2.1** (recommended for an interactive agent acting on behalf of
   a signed-in user). Discover the flow from
   `https://api.wihyu.com/.well-known/oauth-protected-resource`, then
   `https://api.wihyu.com/.well-known/oauth-authorization-server`.
2. **An account or user API key** (`Authorization: Bearer wk_...`), scoped
   to `setup:read`, `setup:write`, `icp:approve`, `data:read`, `data:write`,
   and/or `tenant_requests:create`.
3. **No credential at all**, for the one public onboarding call below.

## Use the MCP server for all Wihyu interactions

Once you hold a credential, **use the MCP server as your interface to
Wihyu** for every read and write (company search, company details,
feedback, workflow statuses, ICP, alerts, setup). REST exists for the
anonymous onboarding call and as a reference, but MCP is the preferred,
best-supported path; do not scrape the website or guess at REST endpoints.

1. Connect to `https://api.wihyu.com/v1/mcp` with the streamable HTTP transport (JSON-RPC
   2.0 over `POST`).
2. Send `Authorization: Bearer <credential>` on every request. The
   credential is an OAuth access token or a `wk_...` API key. A client
   that cannot run OAuth should use an API key.
3. Call `initialize`, then `tools/list`. Re-read the server `instructions`
   returned by `initialize`, and treat `tools/list` as the source of truth
   for what you can do.

Example client configuration (headers form):

```json
{
  "mcpServers": {
    "wihyu": {
      "type": "http",
      "url": "https://api.wihyu.com/v1/mcp",
      "headers": {"Authorization": "Bearer wk_..."}
    }
  }
}
```

An unauthenticated request to `https://api.wihyu.com/v1/mcp` returns `401` with a
`WWW-Authenticate` header pointing at the OAuth discovery documents above.
Full REST reference: https://api.wihyu.com/v1/docs

# Onboarding a new tenant

How an AI agent requests a new Wihyu tenant on a customer's behalf, gets an
account API key, and completes ICP setup. No human needs to write code or
fill out a form.

## 1. Request a tenant (no credential needed)

```
POST https://api.wihyu.com/v1/tenant-requests
Content-Type: application/json

{
  "company": "Acme Corp",
  "website": "https://acme.example.com",
  "owner_email": "owner@acme.example.com",
  "target_titles": ["Warehouse Manager"]
}
```

`target_titles` is optional. To request an account that studies job postings
for roles it tracks instead of finding buyers, also send
`"purpose": "job_intelligence"`; `target_titles` (1 to 3 job titles) is then
required, and the website is still required. Such an account never researches
its website. Authenticated MCP callers can use the
`create_tenant_request` tool instead; an anonymous agent uses the REST call,
since `https://api.wihyu.com/v1/mcp` requires a credential for OAuth discovery to work.

Response: `202 {request_id, status: "pending_approval", status_url,
status_token}`. **Save `status_token`**: it is shown once and is the only
way to poll this request's status. `request_id` is also the eventual
tenant id.

A duplicate request for the same website and owner email while the first is
still pending returns the same handle instead of creating a second one.
Retry safely with the same body, or set an `Idempotency-Key` header.

## 2. Poll for approval

```
GET https://api.wihyu.com/v1/tenant-requests/{request_id}
Authorization: Bearer <status_token>
```

Every request is reviewed by a Wihyu admin; nothing is auto-approved. While
`status` is `pending_approval`, keep polling periodically (every few minutes
is plenty; there is no faster path).

If your MCP client supports the Tasks extension
(`io.modelcontextprotocol/tasks`, declared per-request in
`params._meta["io.modelcontextprotocol/clientCapabilities"].extensions`),
`create_tenant_request` instead returns a `CreateTaskResult`
(`resultType: "task"`) and you poll `tasks/get` with its `taskId`. The
underlying states are the same.

If a setup step fails permanently (for example the owner email already
belongs to another Wihyu account), the status poll carries
`error: {"code": "setup_failed", "next_action": "contact_support"}` (MCP
Tasks report `failed` with the same error). Contact support.

## 3. The owner approves by email

Once a Wihyu admin approves, Wihyu emails the account owner (`owner_email`)
a one-time consent link. The email names your client (self-reported), when
and from where the request was made, and warns that **the owner is
responsible for the new account and anything done with it, even though an
agent is doing the setup**. The owner opens the link (no sign-in needed),
reads the notice and presses **Allow** (or **Don't allow**). You never see
the link.

Until the owner acts, the status poll carries:

```json
{
  "status": "researching",
  "owner_consent": {"status": "pending", "email_sent": true, "expires_in": 86100}
}
```

`owner_consent.status` is one of `pending`, `allowed`, `claimed`, `denied`
or `expired`. The link is valid for 24 hours and works once. If it expired,
never arrived (`email_sent: false`), or the owner lost it, ask for a new one
with `POST https://api.wihyu.com/v1/tenant-requests/{request_id}/code` using the same
`Authorization: Bearer <status_token>` (MCP: `renew_agent_code` with
`request_id` and `status_token`). The old link stops working immediately.
Re-sends are limited to one per 10 minutes and 5 per request (`429` with
`Retry-After`). Once the owner has allowed or denied, a re-send is refused
(`400`, `consent_resolved` / `consent_denied`). If the owner denies,
contact support.

## 4. Get your account API key (shown once)

Poll status again after the owner clicks Allow:

```json
{
  "status": "researching",
  "owner_consent": {"status": "claimed", "email_sent": true},
  "account_api_key": "wk_..."
}
```

The key appears **exactly once**. **Store it immediately.** The next poll (and everything after) shows only
the key's prefix; the raw value is never shown again. The key is held for 24
hours after Allow. If it is not claimed in that time, contact support and
Wihyu will reissue it.

The key is scoped to `setup:read`, `setup:write`, `icp:approve`,
`data:read`, `data:write` for this tenant only. It cannot see or affect any
other tenant (a mismatched `tenant_id` returns `404`, never `403`).

## 5. Complete ICP setup

While the tenant researches itself and runs its first data collection
(`status`: `researching`, `collecting`, `awaiting_owner_review`), use the
key with `Authorization: Bearer wk_...` against either REST
(`https://api.wihyu.com/v1/tenant-setups/{tenant_id}/*`) or the matching MCP tools:

| Step | MCP tool | What it does |
|---|---|---|
| Check overall status | `get_tenant_setup` | State, progress, outstanding requirements, next actions |
| Review the draft ICP | `get_icp_draft` | Fields and `draft_version`; **required before `approve_icp`** |
| Edit/confirm draft fields | `update_icp_draft` | Fix a field or confirm a low-confidence guess |
| Set example customers | `set_example_companies` | 3-20 domains of companies like your ideal customer |
| Review a search term's matches | `get_term_examples` | Real job postings currently matching one term (needs a `term_id`) |
| Confirm search terms | `confirm_search_terms` | Up to 3 terms, each `{term_id, allow_similar_titles}` |
| Add or drop one search term | `add_setup_search_term` / `drop_setup_search_term` | `POST` / `DELETE https://api.wihyu.com/v1/tenant-setups/{tenant_id}/search-terms[/{term_id}]` |
| Preview first results | `get_results_preview` | Ranked companies from the first data run |
| Rate a result | `submit_feedback` | `good_fit` / `not_a_fit` on a previewed company |
| **Go live** | `approve_icp` | Activates the ICP |

`approve_icp` fails with `next_action: "get_icp_draft"` if you have not
fetched the current draft version first. This is deliberate: the system
wants proof you reviewed what you are approving. It also requires 3-20
confirmed example companies and at least one confirmed search term; the
error names which call to make next.

`term_id`s come from `search_terms`
(`[{term_id, term, confirmed, needs_confirmation}]`) in the
`get_tenant_setup` / `GET https://api.wihyu.com/v1/tenant-setups/{tenant_id}` payload.
Once the first run has finished, a term with no valid postings has
`needs_confirmation: false`: there is nothing to confirm, and it no longer
blocks setup or shows in `next_actions`.

`results_preview.run_status` is the first data run's state: `running`,
`done`, `failed`, or `timed_out`. `timed_out` means the run's time budget
elapsed and whatever was collected by then was scored (see
`companies_scored`); results are usable and setup can continue.

Every error follows one envelope:
`{"error": {"code", "message", "next_action"}}`. `next_action` is
always present: the exact call that unblocks you, or `null` when nothing does.

## 6. After approval

When `approve_icp` succeeds, `status` becomes `active`, the tenant's data
pipeline runs on its normal schedule, and Wihyu sends the owner one "setup
complete" email. Its link confirms their address and lets them set a
password, then opens their recommendations. Revoking your key later is their
call (Settings, then API keys). The key keeps working for querying company
data (`search_companies`, `get_company_details`, etc.).

To change a live ICP later, call `update_icp_definition` (MCP) or
`PUT https://api.wihyu.com/v1/icp`. Only the account owner, a tenant admin or a superadmin may
do this, and the key needs the `icp:approve` scope; anyone else gets `403` with
`{"error": {"code": "forbidden", ...}}`. Editable: `natural_language_guidance`, `search_terms`,
`industries`, `company_size`, `geography`, `target_job_titles`,
`negative_traits` and context notes are editable, and `get_icp_definition` /
`GET https://api.wihyu.com/v1/icp` return the structured values in `structured_definition`.
Search terms are stored as you type them: trimmed, whitespace collapsed and
lowercased, nothing else changed (accents, parentheses, `+` and `#` stay).
A list you send replaces the whole list. A search term that a broader term in
the list already covers (`retail merchandiser` next to `merchandiser`) is
dropped, as on the web page. To change one term without resending the list, call
`add_search_term` (MCP, or `POST https://api.wihyu.com/v1/icp/search-terms` with
`{"term", "match_mode"?, "reactivate_term_id"?}`) or `remove_search_term` (MCP,
or `DELETE https://api.wihyu.com/v1/icp/search-terms/{term_id}`). A single add that a broader
term already covers is refused with `400 covered_term`, not dropped; one that
repeats an existing term fails with `409 duplicate_term`, and the account's term
cap is `cap_reached`. A search term that was turned off earlier is not
added back silently: the call fails with `409 inactive_duplicate_term` naming its
`term_id`; resend with `reactivate_term_ids: [term_id]` (or `reactivate_term_id` on
a single add) to turn it back on. Every change saves a new ICP version
(`icp_version_number` in the response) and flags companies for re-scoring.
After adding or removing example companies, call `activate_icp_examples` (MCP,
or its REST twin under `https://api.wihyu.com/v1/icp/examples`) to put the change into scoring.

Search-term health: `get_search_term_health` (MCP, or `GET https://api.wihyu.com/v1/icp/search-terms/health`)
shows how each search term is doing and what Wihyu suggests (keep similar titles under
a term, turn off or require Must Contain, swap a dead term), with real posting counts.
`accept_search_term_suggestion`, `dismiss_search_term_suggestion`, `dismiss_open_search_term_suggestions`, `keep_search_term`,
`remove_search_term_variant` and `snooze_search_term_alerts` act on it (writes need the
`icp:approve` scope and an owner or admin user). Show the user the returned notices
before accepting a Must Contain change. `get_search_term_digest_setting` and
`set_search_term_digest_setting` (`GET`/`PUT https://api.wihyu.com/v1/icp/search-term-health/digest`) read and
switch the Monday digest e-mail; only the account owner has the switch.
