# Tokenz MCP Server

A [Model Context Protocol](https://modelcontextprotocol.io) server for **Tokenz** (a Merchant of Record checkout). It helps AI coding agents integrate Tokenz, and lets merchants query their own Merchant Dashboard data from Claude, Cursor or ChatGPT.

## Two endpoints — which one?

| URL | Auth | Use it when |
| --- | --- | --- |
| `https://mcp.tokenz.one/mcp` | none, or a `secret_test_` key in the `Authorization` header | You are **building an integration** — docs, test checkout, test refunds, webhooks. Never asks for OAuth. |
| `https://mcp.tokenz.one/merchant` | **Required**: sign in with your Merchant Dashboard account (OAuth), or a `secret_test_` key | You also want to **ask about your business** — sales, top items, orders, payouts, disputes, subscriptions, products and price plans, campaigns and codes, redemptions, creator payouts, webhook endpoints. Every request without a credential gets a 401 sign-in challenge, so anonymous docs use belongs on `/mcp`. |

`/merchant` offers every `/mcp` tool plus the dashboard tools. If you only use a `secret_test_` key, stay on `/mcp`: it never answers OAuth discovery, so clients that force OAuth whenever a server advertises it (Cursor does, even with a configured `Authorization` header) keep using your key. Dev uses `mcp.tokenz.pro`.

## Tools

| Tier | Auth | Tools |
| --- | --- | --- |
| **Docs** | none | `search_docs`, `get_doc`, `list_docs`, `get_openapi`, `list_test_cards` |
| **Diagnostics & webhooks** | none | `check_auth`, `verify_webhook_signature`, `sign_test_webhook_payload` |
| **Test actions** | `secret_test_` key, or a dashboard sign-in on `/merchant` | `create_test_checkout_session`, `get_checkout_session`, `get_order`, `cancel_test_order`, `create_test_refund`, `get_refund` |
| **Merchant Dashboard** (`/merchant` only) | dashboard sign-in (OAuth) | `get_merchant_info`, `get_sales_summary`, `get_top_items`, `get_top_regions`, `search_orders`, `export_orders`, `list_payouts`, `list_disputes`, `get_chargeback_rate`, `list_subscriptions`, `list_products`, `list_campaigns`, `list_campaign_codes`, `list_redemptions`, `get_creator_payouts`, `list_webhook_endpoints`, `create_test_api_key` |

The docs tools read the **live** documentation from `docs.tokenz.one` (`/llms.txt` + `/{lng}/md/...`), so they never go stale. The test tools call the real Tokenz API in **test mode only** — a live key is refused, so an agent can never create a real charge.

The dashboard tools are **read-only** (except `create_test_api_key`, which can only ever issue a TEST key):

| Tool | What it answers | Dashboard permission needed |
| --- | --- | --- |
| `get_merchant_info` | Account, tier (merchant / platform / project), payout settings, child projects, balance summary | `merchantGet`; payout settings and balances also `payoutGet` (omitted with a note otherwise) |
| `get_sales_summary` | Gross volume, payments, new customers, AOV vs the previous period — presets (`Today` = today vs yesterday, `Last7Days`, `MonthToDate`, …) or any date range; `aggregated: true` sums a platform's merchants | `orderGet` |
| `get_top_items` / `get_top_regions` | Best sellers / best buyer countries for a date range (complete days, up to yesterday) | `orderGet` |
| `search_orders` | Orders by id, your external id, status, date, buyer email or text, amount, currency, country (paginated) | `orderGet` |
| `export_orders` | The same filters as CSV (truncated with a note if huge) | `orderExport` |
| `list_payouts` | Payouts with their breakdown and a link to each payout's page in the dashboard, where the period's documents download once ready (after signing in) (signed download links are never given to an MCP session) — e.g. `months: ["2026-08", "2026-09"]` — or payout periods; defaults to the current and previous two months and spans at most 12 months per call (Minutely payout frequency: last 24 hours, at most 48 hours), lists at most 200 rows (totals cover all) | `payoutGet` only. With `merchantGet` too it also uses your payout timezone and frequency setting; without it, dates are read in UTC (with a note) and the frequency is inferred from your last 48 hours of payouts |
| `list_disputes` | Disputes with evidence deadlines | `disputeGet`; the related order also `orderGet` (omitted with a note otherwise) |
| `get_chargeback_rate` | This month's chargeback rate and fee tier | `billingSettingGet` |
| `list_subscriptions` | Subscriptions | `subscriptionGet` |
| `list_products` | Products: name per locale, type, SKU, status, category, stock, availability, bundle contents; with `withPricePlans: true` their price plans (Listed / Unlisted, default and per-country prices, subscriber count) | `catalogItemGet`; price plans also `pricePlanGet` |
| `list_campaigns` | Campaigns: status, schedule, redemption limits and use, budget usage, reward | `campaignGet` |
| `list_campaign_codes` | A campaign's discount codes or redemption codes (`kind`), with status, limits and, for redemption codes, times redeemed | `redemptionCodeGet` |
| `list_redemptions` | Code / free-item redemptions | `redemptionGet` |
| `get_creator_payouts` | Creator payout batches totalled separately per batch status (only Confirmed went ahead), per project and currency, optionally for a period (live-mode connections only) | `projectGet` + `splitBatchGet` |
| `list_webhook_endpoints` | Webhook endpoints: description, active, subscribed events, API version (never the URL or signing secrets) | `webhookGet` |
| `create_test_api_key` | Issue a new TEST API key (shown once) | `apikeyCreate` (also needed for the test-action tools on a signed-in connection) |

A tool whose permission your dashboard role lacks answers "not allowed (Unauthorized)". Tools that read plain dates (`search_orders`, `export_orders`, `list_disputes`, `get_top_items`, `get_top_regions`, `list_payouts`, `get_creator_payouts`) use your payout timezone when your role can read it (`merchantGet` + `payoutGet`); otherwise they use UTC and say so in the result — pass `timezone` to choose. On a signed-in connection the test-action tools need `apikeyCreate` (to create their test key). The permissions are the backend's role permissions; `yarn schema` checks this table's source of truth against the schema.

Money amounts are integers in the currency's minor unit (cents; JPY has none), each with a formatted string.

Typical flow: `search_docs` → write the integration → `check_auth` (confirm the connection & key) → `create_test_checkout_session` → open the URL and pay with `4242 4242 4242 4242` → `get_order` to confirm. Building webhook handling? `sign_test_webhook_payload` produces a correctly-signed request so you can test your handler locally before any real purchase.

## Connect

### Merchant Dashboard sign-in (OAuth) — `/merchant`

Add the server **without** an `Authorization` header. The very first request (connecting) gets an HTTP 401 that points your client (via `/.well-known/oauth-protected-resource/merchant`) at the Tokenz sign-in page, so you sign in while adding the server; nothing on `/merchant` works before that. After you sign in, your client refreshes the short-lived access tokens (15 minutes) automatically. (Operators: `/merchant` OAuth needs the backend's MCP OAuth support deployed first — see [DEPLOY.md](DEPLOY.md#deploy-order-merchant-oauth).)

- **Claude (claude.ai / Claude Desktop)**: Settings → Connectors → *Add custom connector* → URL `https://mcp.tokenz.one/merchant` → *Connect*, then sign in.
- **Claude Code**:
  ```bash
  claude mcp add --transport http tokenz https://mcp.tokenz.one/merchant
  ```
  Claude Code lists `tokenz` as needing authentication — run `/mcp`, choose `tokenz` → *Authenticate*, and sign in.
- **Cursor** (`~/.cursor/mcp.json`):
  ```json
  { "mcpServers": { "tokenz": { "url": "https://mcp.tokenz.one/merchant" } } }
  ```
  Cursor shows *Needs login* for `tokenz` — click it and sign in.
- **ChatGPT**: Settings → Apps & Connectors → *Create* (developer mode) → MCP server URL `https://mcp.tokenz.one/merchant`, authentication *OAuth* → sign in.

**What you grant on the consent screen**: read-only access to your Merchant Dashboard data (`dashboard:read`) and permission to create **test** API keys (`test_api_keys:create`) — nothing else; the MCP cannot change settings, refund, or issue live keys. You also choose **test or live mode**: a live-mode connection reads live data (and test data on request); a test-mode connection reads test data only, so sales analytics, top items/regions, payouts, the chargeback rate and creator payouts need a live-mode connection, and plain dates are read in UTC unless you pass a `timezone` (the payout timezone is not readable in test mode). What you can see is further limited by your dashboard role. If the app asks only for read access, the connection is read-only: the dashboard tools work, but it cannot create test API keys, so `create_test_api_key` and the test-action tools say so (use a `secret_test_` key for those, or reconnect and approve key creation); `check_auth` shows the granted scopes. Revoke access any time in the dashboard under **Settings → Account → Connected apps**.

On a signed-in connection the test-action tools work without you pasting a key: the first time one is used, the MCP creates a test API key named `MCP – <client name>` for the session (visible under Developers → API keys) and keeps it in memory. If you delete that key, the next test action creates a new one automatically.

### API key only — `/mcp`

```bash
claude mcp add --transport http tokenz https://mcp.tokenz.one/mcp \
  --header "Authorization: Bearer secret_test_your_key"
```

The `Authorization` header is optional — omit it to use only the docs tools; add it to unlock the test-action tools.

### Claude Desktop (config)

```json
{
  "mcpServers": {
    "tokenz": {
      "url": "https://mcp.tokenz.one/mcp",
      "headers": { "Authorization": "Bearer secret_test_your_key" }
    }
  }
}
```

### Local / stdio

```json
{
  "mcpServers": {
    "tokenz": {
      "command": "npx",
      "args": ["-y", "@tokenz.one/mcp-server", "--stdio"],
      "env": { "TOKENZ_SECRET_KEY": "secret_test_your_key" }
    }
  }
}
```

## Configuration (env)

| Var | Default | Purpose |
| --- | --- | --- |
| `PORT` | `8080` | HTTP port (Cloud Run sets this) |
| `TOKENZ_DOCS_ORIGIN` | `https://docs.tokenz.one` | Where docs are fetched from |
| `TOKENZ_API_ORIGIN` | `https://api.tokenz.one` | API for the test tools (REST `/v2/*`) and the dashboard tools (`/graphql`); use `https://api.tokenz.pro` for dev |
| `TOKENZ_MCP_ORIGIN` | `https://mcp.tokenz.one` | This server's public origin; the OAuth resource is `<origin>/merchant` (use `https://mcp.tokenz.pro` for dev) |
| `TOKENZ_DASHBOARD_ORIGIN` | from `TOKENZ_API_ORIGIN` (`api.tokenz.*` → `dashboard.tokenz.*`) | Merchant Dashboard origin for links into it, such as each payout's page; none for another API origin |
| `TOKENZ_AUTH_ISSUER` | = `TOKENZ_API_ORIGIN` | OAuth authorization server advertised in the `/merchant` protected-resource metadata |
| `TOKENZ_SECRET_KEY` | — | `secret_test_` key for **stdio** mode (HTTP uses the request header) |
| `MCP_TRANSPORT` | `http` | `stdio` to run over stdio |

## Develop

```bash
yarn install
yarn build
yarn start          # HTTP on :8080  → POST /mcp, POST /merchant, GET /healthz
yarn stdio          # stdio mode
yarn smoke          # unit tests
yarn schema         # validate every GraphQL document against the backend schema snapshot
yarn dashboard      # dashboard tools (GraphQL stubbed, no network)
yarn merchant       # HTTP: /merchant auth paths + the /mcp regression pin
```

## Deploy (GCP / GKE via ArgoCD)

Deploys the standard Tokenz way — Cloud Build → Artifact Registry → `argocd-apps` (GitOps) → ArgoCD → GKE, behind Istio + a managed cert. Dev on `mcp.tokenz.pro`, prod on `mcp.tokenz.one`. The server is stateless with no secrets of its own (OAuth tokens are validated against the Tokenz API per request, cached ~30 s in memory). See **[DEPLOY.md](DEPLOY.md)** for the full runbook (Cloud Build triggers, GitOps manifests, DNS). `cloudbuild.dev.main.yaml` (push→dev) and `cloudbuild.prod.tag.yaml` (tag→prod) are in this repo.

## Keeping content fresh

Everything is read **live** from the docs site (`docs.tokenz.one`), the single source of truth — nothing in this repo to sync or redeploy when docs change:

- **Guides & API reference pages**: fetched from `/llms.txt` + the clean-markdown routes.
- **OpenAPI specs**: fetched from `/en/v2/api/list` (discovery) and `/en/v2/api/{key}/raw` (per-service JSON). Add a service in the docs repo and it shows up here automatically.

The **action tools** (`create_test_checkout_session`, …) hand-mirror the API contract, so they *can* drift — the nightly `contract` CI job drives them against the live test-mode API to catch that (see `.github/workflows/ci.yml`).

The **dashboard tools** send the GraphQL documents in `src/dashboard/documents.ts`; `yarn schema` validates each against `src/test/fixtures/backend-schema.graphql`, a snapshot of the backend's `golden/schema.graphql`. The fixture is a verbatim copy of the backend's generated schema; refresh it whenever the backend schema changes.

## Architecture

```
src/
  index.ts            entry — picks HTTP or stdio
  server.ts           builds the McpServer, registers all tools
  http.ts             Streamable HTTP transport (stateless): /mcp (keys) and /merchant (OAuth gate + metadata)
  stdio.ts            stdio transport
  config.ts           env
  docs/               docs tier — live client + tools + live OpenAPI fetch
  checkout/           test tier — API client, auth guard (test-mode only), tools
  webhooks/           verify + sign test webhook signatures (pure crypto)
  dashboard/          /merchant: OAuth token validation, GraphQL client + documents, dashboard tools,
                      lazy test-key minting for signed-in sessions
```
