# Moreflow API guide

> Issue an account-bound token, discover the current public API, and make your first safe integration call.

## Documentation links

- [Agent quickstart (Markdown)](https://docs.moreflow.io/quickstart.md): The complete machine-readable onboarding guide.
- [Getting-started guide (HTML)](https://docs.moreflow.io/): The same guide rendered for people and browser-based agents.
- [Interactive API reference](https://docs.moreflow.io/reference): Try the API and inspect the live OpenAPI surface.
- [OpenAPI JSON](https://api.moreflow.io/operations/openapi.json): The generated contract for tools and client generation.
- [MCP Streamable HTTP endpoint](https://api.moreflow.io/mcp): Connect an MCP client to the dedicated API host.
- [OAuth protected-resource metadata](https://api.moreflow.io/.well-known/oauth-protected-resource): RFC 9728 metadata that names the API host as the OAuth 2.1 authorization server for /mcp.
- [OAuth authorization-server metadata](https://api.moreflow.io/.well-known/oauth-authorization-server): RFC 8414 metadata: authorize, token, registration, and JWKS endpoints with PKCE (S256) required.
- [API token settings](https://app.moreflow.io/settings/integrations/api-key): Create and rotate account-bound integration tokens.
- [Webhook correlation and verification follow-up (moreflow-hjbpv.21)](https://github.com/valie-media-gmbh/moreflow-v2/issues?q=is%3Aissue+moreflow-hjbpv.21): History of per-event versions, correlation fields, and the signature contract.

## Use the live contract

This guide explains the workflow, not a copied operation catalog. Start with the authenticated `operations.discovery.list` and `operations.discovery.get` operations, then use the [live OpenAPI document](https://api.moreflow.io/operations/openapi.json) for the exact fields, validation, examples, error codes, and agent-safety metadata available to your account. The OpenAPI agent annotations derive from each operation’s `agent.effect` and its declared confirmation and reversibility.

> Public operation ids begin with `resource.action` (for example `clients.list`). Integration tokens grant exact operation ids, never prefixes or wildcards.

Canonical public operation ids use `module.resource[.subresource].verb`. New ids end in `list`, `detail`, `create`, `update`, or `delete`. Lists return `{ items, nextCursor }`; detail reads return one resource; mutations use the matching write scope and the standard success/error envelope plus idempotency rules. Existing documented grandfathered ids remain authoritative when discovered.

## 1. Choose a credential: OAuth for hosted clients, a token for headless agents

For a direct API integration, sign in as an account owner or admin and open the [API token settings page](https://app.moreflow.io/settings/integrations/api-key) (Settings → Integrations → API tokens). Choose a read or write scope bundle, review its operation picker, and create the token. The token stores the selected bundle ids, and each request expands them against the live operation catalog, so an operation added to a bundle later becomes callable by every existing token and OAuth grant that holds it.

A newly created secret is shown once—store it in a secret manager. Never paste a secret into a URL, source repository, or log. The token capability and usage reads behind this page (`account.apiTokens.capabilities.get, account.apiTokens.usage.*`) are never grantable to a credential.

Headless agents can manage their own credentials without the settings page. An owner or admin issues one bootstrap API token with the `admin:tokens` scope bundle. That credential may call `account.apiTokens.create` to mint narrower tokens, `account.apiTokens.rotate` to rotate one, `account.apiTokens.revoke` to revoke one, and `account.apiTokens.list` to find token ids. Scopes never widen: every exact operation id a minted or rotated token receives must already be held by the calling credential, so a token can only include `admin:tokens` when its issuer holds it, and a credential can never revoke or rotate itself. Every mint is audited and listed on the settings page with its origin credential, and `admin:tokens` is the only bundle that can grant these operations. OAuth grants never carry it, so an MCP or OAuth client cannot manage credentials.

```bash
curl --silent --show-error -X POST "$MOREFLOW_API_BASE/operations/account.apiTokens.create" \
  -H "Authorization: Bearer $MOREFLOW_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: nightly-sync-2026-09-03" \
  -d '{"label":"Nightly sync agent","scopes":["clients:read"]}'
```

Every integration token is bound to the account that issued it. Do not include `accountId`, `account_id`, or `x-moreflow-account-id` to select another account: the API derives the account from the verified bearer token.

OAuth 2.1 is the default path for hosted MCP clients such as Claude.ai, ChatGPT, and Claude Desktop. Point the client at the [Moreflow MCP endpoint](https://api.moreflow.io/mcp). A 401 response points it at the [protected-resource metadata](https://api.moreflow.io/.well-known/oauth-protected-resource), which names the API host as the authorization server. The API serves [authorization-server metadata](https://api.moreflow.io/.well-known/oauth-authorization-server), `/oauth2/authorize`, `/oauth2/token`, `/oauth2/register`. Authorization codes require PKCE (S256). Moreflow uses revocable opaque access tokens, so authorization-server metadata intentionally does not advertise a `jwks_uri`. During consent you sign in, pick the Moreflow account the grant is bound to, and approve one scope bundle; the issued access token carries exactly that account and bundle, and every token can be revoked from the API token settings page. No manual bearer is needed for a client that completes OAuth. Moreflow does not advertise or accept the OAuth `client_credentials` grant: this server has no service-principal/account-binding model, so use a static account-bound token or a user-consented OAuth grant instead.

Client identity: clients may present an HTTPS client-id metadata URL (CIMD, MCP profile 2026-07-28) without prior registration, or use RFC 7591 dynamic registration. Unauthenticated dynamic registration is only open on the development API host (`dev-api.moreflow.io`) and on local loopback runtimes; on production, registration requires an authenticated Moreflow session, so a production client without CIMD support must be registered while signed in as an account admin or fall back to a pre-issued token. In every environment, verify that the requested resource is exactly the API host’s `/mcp` URL (for production `https://api.moreflow.io/mcp`) and never approve a different audience.

Static account-bound tokens remain the path for headless agents, servers, CLIs, and any client that cannot complete a browser consent. Both credential kinds resolve to the same account binding, the same exact-operation scopes, and the same rate limits.

## 2. Send your first public API call

Use the bearer token in the `Authorization` header. This read uses the public `clients.list` operation; its exact input and output evolve through the live contract linked above.

```bash
export MOREFLOW_API_BASE="https://api.moreflow.io"
export MOREFLOW_API_TOKEN="mfo_replace_with_your_secret"

curl --silent --show-error "$MOREFLOW_API_BASE/operations/clients.list" \
  -H "Authorization: Bearer $MOREFLOW_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"limit":25}'
```

Successful public API calls return the operation output directly as the JSON response body. There is no `{ success: true, data }` success wrapper; for this list operation, the top-level body follows the discovered output schema:

```json
{
  "items": [],
  "nextCursor": null
}
```

_The token needs the exact `clients.list` scope. Add `operations.discovery.list` and `operations.discovery.get` when your integration or agent will discover contracts at runtime._

## 3. Discover before you invoke

Do not hardcode a catalog from this guide. List the public surface, inspect one operation, and construct requests from its returned schema and examples. A token can discover only the exact operation ids it is allowed to use.

```bash
# Find public operations that the token can discover.
curl --silent --show-error "$MOREFLOW_API_BASE/operations/operations.discovery.list" \
  -H "Authorization: Bearer $MOREFLOW_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{}'

# Inspect one live input/output/error contract and its safety metadata.
curl --silent --show-error "$MOREFLOW_API_BASE/operations/operations.discovery.get" \
  -H "Authorization: Bearer $MOREFLOW_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"id":"clients.list"}'
```

Use `operations.discovery.search` for a keyword search and `operations.modules.list` to narrow the browse path. The [interactive API reference](https://docs.moreflow.io/reference) renders the same public surface, while the [OpenAPI JSON](https://api.moreflow.io/operations/openapi.json) is suitable for generated clients.

## 4. Follow the error envelope and recovery

Failures use the canonical `{ error: { category, code, message, recovery, details, requestId } }` envelope. Treat `error.recovery` as the next navigational action instead of matching human-readable messages. Preserve its operation id and safe arguments when they are present.

```json
{
  "error": {
    "category": "PERMISSION_DENIED",
    "code": "FORBIDDEN",
    "message": "Integration token does not include the requested operation scope.",
    "recovery": {
      "operation": "operations.discovery.list",
      "args": {}
    },
    "details": { "operationId": "clients.create" },
    "requestId": "req_01J8Z6Q2V4X7N3K5M9P1R2S3T4"
  }
}
```

| Signal | Meaning | Recovery |
| --- | --- | --- |
| `401 AUTH_ERROR` | The bearer is missing, invalid, expired, or revoked. | Create or rotate an account-bound token and send it as Authorization: Bearer. |
| `403 FORBIDDEN` | The token or session cannot use this operation or account. | Discover the allowed public operation ids; request the missing exact scope from an account administrator. |
| `404 NOT_FOUND` | The operation is unknown or not externally discoverable. | Call operations.discovery.list, then describe a returned id instead of guessing. |
| `402 UPGRADE_REQUIRED` | The account monthly api_requests allowance is exhausted. | Follow the pricing recovery in the error and check billing.entitlements.get. |
| `429 RATE_LIMIT` | A short-window protective limit was reached. | Honor Retry-After and RateLimit-* headers, then retry safely. |

## 5. Cursor pagination

Public list contracts return `{ items, nextCursor }`. Their input uses an optional `cursor` and a `limit` from 1 to 100, defaulting to 25. Send the opaque cursor returned by the previous page as the next request’s `cursor`; never decode, construct, or reuse a cursor with different filters.

1. Start without a cursor and choose a limit within the discovered range.
2. Read items from the response and continue only when `nextCursor` is not null.
3. Send that exact opaque value with the same filters; stop when `nextCursor` is null.

```json
{"limit":25,"cursor":"opaque-next-cursor"}
```

<a id="idempotency"></a>

## 6. Mutation idempotency

Every idempotent public mutation has one durable lifecycle: **one key = one logical request**. Generate a key for a new payload, reuse it only for a byte-identical retry, and generate a new key when the user edits the payload. Send the key in the required `Idempotency-Key` header; it is the only idempotency input (a JSON body field is not accepted) and responses never echo it.

### Created

The request claimed the key and executed. Store the successful result if the user needs it; clear the local pending attempt only after success.

### Replayed

The identical request reused a stored terminal result. HTTP responses include `Idempotency-Replayed: true`; MCP responses expose `replayed: true` in structured content.

### Conflict

`409 IDEMPOTENCY_CONFLICT` means the key already belongs to another fingerprint. Rotate the key for the edited/new payload; never clear a key and retry a changed request under that same value.

### Idempotency recovery table

| Signal | Meaning | Next action |
| --- | --- | --- |
| `IDEMPOTENCY_KEY_REQUIRED (400)` | A mutation or job was called without an Idempotency-Key header (a JSON body idempotencyKey is ignored). | Resend the same request with a unique non-empty Idempotency-Key header. |
| `IDEMPOTENCY_CONFLICT (409)` | The key is bound to a different request. | Use a new key for the new payload. Reuse the old key only if restoring the exact original payload. |
| `IDEMPOTENCY_IN_PROGRESS (409)` | An identical request is still running or its `600-second pending lease` has not expired. | Honor Retry-After and retry the identical request with the same key. After the lease expires, use the documented safe re-execution option if available. |
| `Idempotency-Replayed: true` | The stored terminal success or failure was returned. | Treat the response as the result of the original attempt. Do not submit again with another key. |

Successes and terminal failures are retained for `30 days`. A failed request therefore replays the same failure during that window; rotate only when the request itself is being changed. After expiry the key may be reused. Pending claims have a `600-second lease`; an active claim returns the exact remaining delay in `Retry-After`, while an expired claim reports unknown outcome unless safe re-execution is explicitly enabled.

### Copy-paste browser recipe

This framework-agnostic helper keeps the key and its payload fingerprint together in `sessionStorage`. It reuses a key for a timeout retry, rotates it for an edited payload, and clears it after success. It calls the API directly from the page, with no token: the public form endpoints answer CORS requests from any site, and the form’s allowed domains decide which sites may submit.

```javascript
async function sha256(value) {
  const bytes = new TextEncoder().encode(value);
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
}

async function submitPublicForm(formId, data) {
  const storageKey = 'moreflow:idempotency:' + formId;
  const payload = { formId, data };
  const payloadHash = await sha256(JSON.stringify(payload));
  const previous = JSON.parse(sessionStorage.getItem(storageKey) || 'null');
  const key = previous && previous.payloadHash === payloadHash
    ? previous.key
    : crypto.randomUUID();
  sessionStorage.setItem(storageKey, JSON.stringify({ key, payloadHash }));

  const response = await fetch('https://api.moreflow.io/forms/' + encodeURIComponent(formId) + '/submissions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
    body: JSON.stringify({ data })
  });
  if (response.ok) sessionStorage.removeItem(storageKey);
  if (response.headers.get('Idempotency-Replayed') === 'true') {
    console.info('Moreflow returned the stored result for this retry.');
  }
  if (!response.ok) throw new Error('Moreflow submission failed: ' + response.status);
  return response.json();
}
```

For production clients, preserve the same request body and key across network retries, and inspect the structured `error.code`/`error.recovery` envelope instead of matching messages. For a new custom browser form, install [@moreflow/forms@0.10.0](https://www.npmjs.com/package/@moreflow/forms) and call `submitWithRetry({ formId, input: { data }, acquisitionTracking: () => consentGiven })`; use `normalizePhoneNumber()` only for phone fields. The helper supplies replay-safe idempotency without imposing a UI framework. Browser forms call https://api.moreflow.io directly with no API token; configure their allowed domains.

<a id="webhook-signature-verification"></a>

## 7. Verify webhook signatures

Create a webhook endpoint with `webhooks.endpoints.create` and store the signing secret exactly once. Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com/): each request carries `webhook-id` (the event id, identical on every retry, so deduplicate on it), `webhook-timestamp` (Unix seconds), and `webhook-signature` with one or more space-separated `v1,<base64>` values. The signature is the base64 HMAC-SHA256 of `webhook-id + "." + webhook-timestamp + "." + rawBody`, keyed with the base64-decoded part of the secret after `whsec_`. Standard Webhooks libraries verify it directly. Verify before JSON parsing, compare in constant time, reject timestamps outside the 300-second replay window, and accept any listed signature: during a secret rotation overlap the header carries one per active secret.

Subscriptions pin an event version: `subscriptions: [{ type, version }]`. Omit `version` to pin the type’s current version; a later version never changes what an existing subscription receives. Every envelope carries its `version` and its causing invocation’s `requestId`, `operationId`, and `actor: { type, id }`. Call `webhooks.events.list` with `{ level: 2 }` for each event’s versions, occurrence key, and payload schema. New event types can appear at any time; treat event names as open strings.

> Test vector (Standard Webhooks reference): secret `whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw`; webhook-id `msg_p5jXN8AQM9LWM0D4loKWxJek`; timestamp `1614265330`; raw body `{"test": 2432232314}`; expected `v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=`.

### Node.js

```javascript
import { createHmac, timingSafeEqual } from 'node:crypto';

const REPLAY_WINDOW_SECONDS = 300;

export function verifyMoreflowWebhook(rawBody, headers, secret, nowSeconds = Math.floor(Date.now() / 1000)) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatureHeader = headers['webhook-signature'];
  if (!id || !/^\d+$/u.test(timestamp ?? '') || !signatureHeader) return false;
  if (Math.abs(nowSeconds - Number(timestamp)) > REPLAY_WINDOW_SECONDS) return false;

  const key = Buffer.from(secret.replace(/^whsec_/u, ''), 'base64');
  const expected = createHmac('sha256', key)
    .update(Buffer.concat([Buffer.from(id + '.' + timestamp + '.', 'utf8'), rawBody]))
    .digest();
  return signatureHeader.split(' ').some((part) => {
    if (!part.startsWith('v1,')) return false;
    const received = Buffer.from(part.slice(3), 'base64');
    return received.length === expected.length && timingSafeEqual(expected, received);
  });
}

// Read the request bytes once, verify them, then JSON.parse(rawBody.toString('utf8')).
// Or use @moreflow/api: verifyWebhook({ payload, headers, secret }).
```

### Python

```python
import base64
import hashlib
import hmac
import time

REPLAY_WINDOW_SECONDS = 300

def verify_moreflow_webhook(raw_body: bytes, headers, secret: str, now_seconds: int | None = None) -> bool:
    msg_id = headers.get('webhook-id')
    timestamp = headers.get('webhook-timestamp', '')
    signature_header = headers.get('webhook-signature')
    if not msg_id or not timestamp.isdigit() or not signature_header:
        return False
    current = int(time.time()) if now_seconds is None else now_seconds
    if abs(current - int(timestamp)) > REPLAY_WINDOW_SECONDS:
        return False

    encoded = secret.removeprefix('whsec_')
    # Secrets issued before 2026-11 use the URL-safe alphabet; both decode to the same key.
    key = base64.b64decode(encoded.replace('-', '+').replace('_', '/') + '=' * (-len(encoded) % 4))
    signed = f'{msg_id}.{timestamp}.'.encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()
    return any(
        part.startswith('v1,') and hmac.compare_digest(expected, base64.b64decode(part[3:]))
        for part in signature_header.split(' ')
    )

# Flask: raw_body = request.get_data(cache=False, as_text=False)
```

### curl / OpenSSL test

```bash
secret='whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw'
id='msg_p5jXN8AQM9LWM0D4loKWxJek'
timestamp='1614265330'
raw_body='{"test": 2432232314}'
key_hex=$(printf '%s' "$secret" | sed 's/^whsec_//' | base64 -d | xxd -p -c 256)
expected=$(printf '%s' "$id.$timestamp.$raw_body" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key_hex" -binary | base64)
test "v1,$expected" = 'v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE='
# This shell equality is a test-vector assertion only; receivers must compare in constant time.

curl --request POST 'https://receiver.example/webhooks/moreflow' \
  --header 'Content-Type: application/json' \
  --header "webhook-id: $id" \
  --header "webhook-timestamp: $timestamp" \
  --header "webhook-signature: v1,$expected" \
  --data-binary "$raw_body"
```

## 8. Limits, allowance, and retries

### 402 UPGRADE_REQUIRED

The account’s monthly `api_requests` allowance is exhausted. It is an account plan entitlement, consumed when an external operation is admitted and not refunded if that operation later fails. Follow the returned pricing recovery.

### 429 rate limited

A short-window protective rate limit was reached. It is independent from the monthly allowance: honor `Retry-After`, `RateLimit-Policy`, and `RateLimit` (remaining `r` and `t`, the seconds until reset), then retry safely.

Discovery calls are unmetered. A successful `operations.discovery.list`, `operations.discovery.get`, `operations.discovery.search`, or `billing.entitlements.get` call does not consume the monthly API-request allowance; invoking a business operation does.

<a id="mcp"></a>

## 9. MCP Streamable HTTP quickstart

Moreflow exposes a stateless Streamable HTTP MCP server at `/mcp` on the dedicated API host. Configure a remote MCP client with the same account-bound bearer token and API base URL:

```json
{
  "mcpServers": {
    "moreflow": {
      "url": "https://api.moreflow.io/mcp",
      "headers": { "Authorization": "Bearer mfo_replace_with_your_secret" }
    }
  }
}
```

The server exposes exactly eleven meta-tools: `list_operations`, `list_modules`, `describe_operation`, `query_operation`, the write tools `create_record`, `update_record`, `delete_record`, and `run_action`, and `get_entitlements`, plus `search` and `fetch`. It does not generate one MCP tool per API operation.

`https://app.moreflow.io/mcp` is deliberately `404`; only the API host's `/mcp` endpoint is live. The API host also serves host-derived protected-resource metadata at `/.well-known/oauth-protected-resource` and authorization-server metadata at `/.well-known/oauth-authorization-server`, so hosted clients complete OAuth 2.1 with PKCE and account selection; CLI, desktop, and headless clients can configure a static account-bound bearer directly instead.

Use list, search, fetch, and describe to obtain the current public contract. Call `query_operation` for a read-only operation and the write tool that `describe_operation` names in its `tool` field for a mutation, with its `operationId`, `input`, and a caller-generated `idempotencyKey`. Each write tool accepts only its own operations (create, update in place, delete or irreversible removal, or an action such as sending, publishing, or a job); a mismatch is rejected with structured recovery naming the right tool. When the discovered agent metadata says `confirmation: "always"`, the invocation must include `confirm: true` after explicit user confirmation. An OAuth connection approves by person, not by a flag: a write that needs approval returns CONFIRMATION_REQUIRED with an approvalId and an approvalToken in its error context, and the person who connected the agent approves that approvalId at /settings/integrations/connected-agents/approvals. Then retry the same write with the same input, the same idempotencyKey and the approvalToken argument; the approved action runs once, and a second retry with the same token replays its result.

Listing, describing, searching, and entitlement reads are unmetered. The write tools delegate to the same API dispatcher as HTTP calls, so they apply token scopes, account binding, rate limits, audit records, canonical recovery failures, and the monthly `api_requests` meter.

Besides tools, the server advertises MCP resources and prompts. `resources/list` returns the quickstart (`moreflow://docs/quickstart`), the OpenAPI document (`moreflow://openapi`), and one contract document per module; `resources/templates/list` exposes `moreflow://operations/{operationId}/contract` and `moreflow://operations/{operationId}/output-schema`. Reading a resource is unmetered and needs no tool call. `prompts/list` offers the canonical workflows `onboard_client`, `quote_to_invoice`, and `schedule_meeting`. The tool list can change when the account policy changes: `initialize` advertises `tools.listChanged`, and a client that opens `GET /mcp` with `Accept: text/event-stream` receives `notifications/tools/list_changed` and should then call `tools/list` again.

Result envelope: a successful `query_operation` or write tool call returns the operation output itself as `structuredContent` (never wrapped in `{ success, data }`), and a failure returns the canonical `{ error: { category, code, message, recovery, details, requestId } }` envelope with `isError: true`. Every result carries `_meta.operationId` and `_meta.outputSchema.uri`, the resource whose JSON Schema the successful structuredContent conforms to, so a client can validate results without calling `describe_operation` first.

## 10. Per-client MCP setup

Use the client-specific installation option below. OAuth clients complete Moreflow OAuth 2.1 in the client; bearer clients use the secret-free placeholder in the generated snippet. Never commit a bearer token to a config file.

### Claude.ai

Add the Moreflow MCP URL and complete the OAuth 2.1 consent flow; no bearer token is pasted. `https://api.moreflow.io/mcp` Or use the one-click install link: [Claude.ai](https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=Moreflow&connectorUrl=https%3A%2F%2Fapi.moreflow.io%2Fmcp)

### Claude Code

Use this static bearer installation snippet and replace the token placeholder locally: `claude mcp add --transport http moreflow https://api.moreflow.io/mcp --header "Authorization: Bearer {{MOREFLOW_API_TOKEN}}"`

### ChatGPT

Add the Moreflow MCP URL and complete the OAuth 2.1 consent flow; no bearer token is pasted. `https://api.moreflow.io/mcp`

### Cursor

Use this static bearer installation snippet and replace the token placeholder locally: `{
  "mcpServers": {
    "moreflow": {
      "url": "https://api.moreflow.io/mcp",
      "headers": {
        "Authorization": "Bearer {{MOREFLOW_API_TOKEN}}"
      }
    }
  }
}` Or use the one-click install link: [Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=moreflow&config=eyJ1cmwiOiJodHRwczovL2FwaS5tb3JlZmxvdy5pby9tY3AiLCJoZWFkZXJzIjp7IkF1dGhvcml6YXRpb24iOiJCZWFyZXIge3tNT1JFRkxPV19BUElfVE9LRU59fSJ9fQ%3D%3D)

### VS Code

Use this static bearer installation snippet and replace the token placeholder locally: `{
  "servers": {
    "moreflow": {
      "type": "http",
      "url": "https://api.moreflow.io/mcp",
      "headers": {
        "Authorization": "Bearer {{MOREFLOW_API_TOKEN}}"
      }
    }
  }
}` Or use the one-click install link: [VS Code](vscode:mcp/install?%7B%22name%22%3A%22moreflow%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fapi.moreflow.io%2Fmcp%22%2C%22headers%22%3A%7B%22Authorization%22%3A%22Bearer%20%7B%7BMOREFLOW_API_TOKEN%7D%7D%22%7D%7D)

After connection, initialize the session, call `list_operations`, use `query_operation` for reads, and call `describe_operation` for the exact operation you need before using the write tool it names for a mutation. Preserve the canonical error envelope, safety metadata, and idempotency rules inside MCP just as you would for HTTP.

<a id="file-uploads"></a>

## Attach files: upload, then reference

Operations never take file bytes in JSON. Upload each file once with the storage operations (scope `integrate:write`), then pass the returned `storageObjectId` values to the operation that uses the files, for example `attachmentStorageObjectIds` on `communications.messages.send`.

1. Call `storage.uploads.start` with `contentType`, the exact `byteSize`, a `fileName` and a `purpose` (use `communication_attachment` for email files). It returns `storageObjectId` and a signed `upload` request.
2. Send the bytes with `upload.method` to `upload.url` and exactly the `upload.headers` before `upload.expiresAt`. Send no Moreflow token to the storage URL; it is already signed and only accepts the declared size.
3. Call `storage.uploads.complete` with the `storageObjectId`. A file larger than declared is deleted and the call fails; start the upload again with the real size.
4. Pass the ids to the operation. Email attachments are read from storage when the message is sent: up to 20 files, each up to 10 MB and together up to 25 MB.
5. If the transfer fails, call `storage.uploads.cancel` with the `storageObjectId` to remove the partial upload and release its quota.

```javascript
const api = 'https://api.moreflow.io/v1/operations/';
async function call(operationId, input) {
  const response = await fetch(api + operationId, {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + process.env.MOREFLOW_API_TOKEN,
      'Content-Type': 'application/json',
      'Idempotency-Key': crypto.randomUUID()
    },
    body: JSON.stringify(input)
  });
  if (!response.ok) throw new Error(operationId + ' failed: ' + response.status);
  return response.json();
}

const file = await fs.promises.readFile('angebot.pdf');
const { storageObjectId, upload } = await call('storage.uploads.start', {
  contentType: 'application/pdf',
  byteSize: file.byteLength,
  fileName: 'angebot.pdf',
  purpose: 'communication_attachment'
});
const stored = await fetch(upload.url, { method: upload.method, headers: upload.headers, body: file });
if (!stored.ok) {
  await call('storage.uploads.cancel', { storageObjectId, reason: 'transfer_failed', failure: { httpStatus: stored.status } });
  throw new Error('Upload failed: ' + stored.status);
}
await call('storage.uploads.complete', { storageObjectId });

await call('communications.messages.send', {
  channel: 'email',
  toAddress: 'lena.fischer@example.com',
  subject: 'Ihr Angebot',
  bodyText: 'Anbei das Angebot.',
  attachmentStorageObjectIds: [storageObjectId]
});
```

The inline base64 `attachments` field of `communications.messages.send` is deprecated and limited by the 2 MiB request body; use uploaded files instead.

<a id="sdks"></a>

## SDKs and agent plugins

The browser SDKs call the same public operations as this guide and contain no UI, so you keep your own markup and styles. Each README has a complete example. They call https://api.moreflow.io directly from the visitor’s browser: the public form, chatbot, and booking endpoints answer CORS requests from any site, so you need no proxy and no API token. Never put an API token in browser code; `@moreflow/api` is a server-only client for token-authenticated calls.

Route the browser SDKs through your own server only when your Content Security Policy cannot list the API host. Preserving per-visitor rate limiting would require forwarding the real client IP through infrastructure Moreflow trusts. Cloudflare currently rejects caller-supplied CF-Connecting-IP and the public API does not trust X-Forwarded-For, so all visitors share one rate limit at your server’s IP. Forward the browser’s `Origin` header unchanged: dropping or spoofing it defeats Allowed Domains enforcement (forms reject a missing Origin; chatbots skip the allowlist without Origin or Referer). Never set a fixed Origin or add an API token in the proxy.

| Package | Purpose | Install | Docs |
| --- | --- | --- | --- |
| [@moreflow/forms](https://www.npmjs.com/package/@moreflow/forms) | Load, validate, and submit a custom Moreflow form, including Turnstile, the honeypot, and phone verification. | `npm install @moreflow/forms@0.10.0` | [README](https://github.com/moreflow-io/forms#readme) |
| [@moreflow/meetings](https://www.npmjs.com/package/@moreflow/meetings) | Build a native booking widget: meeting type, slots, reservation, and booking. | `npm install @moreflow/meetings@0.3.0` | [README](https://github.com/moreflow-io/meetings#readme) |
| [@moreflow/chatbots](https://www.npmjs.com/package/@moreflow/chatbots) | Build a native chatbot client with visitor and thread continuity. | `npm install @moreflow/chatbots@0.5.0` | [README](https://github.com/moreflow-io/chatbots#readme) |
| [@moreflow/tracking](https://www.npmjs.com/package/@moreflow/tracking) | Capture acquisition data (click ids, UTM, referrer, Meta and TikTok cookies); forms, meetings, and chatbots use it only with acquisitionTracking consent and otherwise send just the page URL's UTM parameters and click ids, without cookies or storage. | `npm install @moreflow/tracking@0.3.0` | [README](https://github.com/moreflow-io/tracking#readme) |
| [@moreflow/api](https://www.npmjs.com/package/@moreflow/api) | SERVER-ONLY typed client for every public operation, generated from the contract snapshots. Never ship its token to browsers. | `npm install @moreflow/api@0.2.0` | [README](https://github.com/moreflow-io/api#readme) |
| [@moreflow/analytics](https://www.npmjs.com/package/@moreflow/analytics) | Website analytics and A/B testing: loads the moreflow tracker, queues events, and reads experiment variants, with optional React bindings. | `npm install @moreflow/analytics@0.1.0` | [README](https://github.com/moreflow-io/analytics#readme) |

Use `baseUrl` for the API origin and `fetchImpl` for a custom transport across SDKs. Browser clients default to https://api.moreflow.io; use `baseUrl: ''` only for the optional CSP proxy described above. Their acquisition override is `trackingCapture`: an options object or a callback returning that SDK’s tracking metadata, called only while `acquisitionTracking` allows capture. Explicit payload tracking remains independent. Forms can bind these defaults once with `createFormsClient({ baseUrl, acquisitionTracking, trackingCapture, fetchImpl })`. Server code passes a static bearer or OAuth access token through `createMoreflowApiClient({ token, fetchImpl, baseUrl })`; never expose that token to a browser. A server client using an empty base URL needs a custom fetch implementation that resolves relative URLs to a trusted origin.

The agent plugins connect the [hosted MCP server](https://docs.moreflow.io/#mcp) and add skills for reading records, onboarding a client, quote to invoice, and scheduling a meeting. Install the Claude Code plugin with `claude plugin install moreflow --marketplace moreflow-io/agent-plugins`, then run `/mcp` to sign in. For Codex run `codex plugin marketplace add moreflow-io/agent-plugins` and `codex plugin add moreflow@moreflow`. Source and issues: [moreflow-io/agent-plugins](https://github.com/moreflow-io/agent-plugins).
