# MCP setup

A local **stdio** MCP server that wraps the same shared services as the UI and
REST API via `/api/v1`. The adapter sends your product key only to the configured AiVideoEditor API.
No Supabase or provider credentials are used.

## Prerequisites

This is a source-checkout adapter, not a published package or hosted connection.
Obtain authorized access to the AiVideoEditor repository, install Node 22+, and run
`npm ci` at the repository root. Create a workspace product key in
`/app/developers` with only the needed scopes and destination access. A draft-only
key cannot publish or schedule. Never paste the key into a chat prompt.

## Run it

```bash
export PUBLISHER_API_URL=https://app.example.com   # HTTPS; http://localhost is allowed for dev
export PUBLISHER_API_KEY=pk_v1_…                   # create in /app/developers
node packages/mcp/bin/publisher-mcp.mjs            # or: npm start --workspace packages/mcp
```

The bin is a real executable launcher (TypeScript + extensionless imports are
resolved through `tsx`). All diagnostics go to **stderr**; stdout carries
protocol traffic only. `PUBLISHER_API_URL` must be HTTPS (plain HTTP only for
loopback development) and must not carry credentials, queries or fragments.

## Generic client configuration

```json
{
  "mcpServers": {
    "autoposted": {
      "command": "node",
      "args": ["/absolute/path/to/packages/mcp/bin/publisher-mcp.mjs"],
      "env": {
        "PUBLISHER_API_URL": "https://app.example.com",
        "PUBLISHER_API_KEY": "pk_v1_…"
      }
    }
  }
}
```

The launcher requires Node 22+ and the workspace dependencies (`tsx`,
`@modelcontextprotocol/sdk`). A hosted MCP transport with OAuth is future work;
do not assume every desktop or hosted client supports pasted bearer keys.

## Tools

| Tool | Read/Mutate | Notes |
|---|---|---|
| `list_accounts` | read | Honors the key's account allowlist |
| `get_capabilities` | read | Formats, limits, consent requirements |
| `create_upload_intent` | mutate | Returns direct upload instructions; media bytes never flow through tools |
| `finalize_upload` | mutate | Session id (+ multipart part receipts); the server observes bytes/MIME itself |
| `create_draft` | mutate | Source + destination variants |
| `validate_post` | read | Structured per-destination issues |
| `schedule_post` | mutate | One instant, ≤90 days ahead, `expectedVersion` required |
| `publish_post` | mutate | 202 semantics; not proof of publication |
| `get_post_status` | read | Per-destination states and native links |
| `list_posts` | read | Cursor pagination |
| `cancel_delivery` | mutate | Only while safely unclaimed |
| `retry_delivery` | mutate | Only known failures; never duplicates |
| `get_usage` | read | No remaining-post counter exists |

### Required tool arguments

| Tool | Required arguments |
|---|---|
| `list_accounts` | None |
| `get_capabilities` | None |
| `create_upload_intent` | `filename`, `declaredMime`, `declaredBytes` |
| `finalize_upload` | `assetId`, `sessionId` |
| `create_draft` | `caption`, `destinations` |
| `validate_post` | `postId` |
| `schedule_post` | `postId`, `scheduledAt`, `timezone`, `expectedVersion` |
| `publish_post` | `postId` |
| `get_post_status` | `postId` |
| `list_posts` | None |
| `cancel_delivery` | `deliveryId` |
| `retry_delivery` | `deliveryId` |
| `get_usage` | None |

Optional arguments include pagination on list tools, `idempotencyKey` on mutations,
`multipart.parts` for multipart finalization, and draft media and destination
variants. The runtime tool schema returned by `tools/list` is authoritative for
optional fields, nested shapes and validation limits.

Mutating tools accept an optional `idempotencyKey` argument. When omitted, the
server generates one and **echoes it in every result: including transport
failures**, where the operation may already have reached the API (the error
carries `transport_outcome_unknown` plus the key). Tools never auto-retry
mutations; retry with the SAME idempotency key to avoid creating a duplicate
operation.

## Agent workflow example

1. `list_accounts` + `get_capabilities` → choose valid destinations.
2. `create_upload_intent` → upload bytes directly → `finalize_upload`.
3. `create_draft` → `validate_post` → fix or deselect invalid destinations.
4. `publish_post` (or `schedule_post`) → note the delivery IDs.
5. `get_post_status` (bounded polling or customer webhooks): treat
   `requires_action` responses as actionable instructions, e.g. TikTok consent.

## Tested clients

- **Official `@modelcontextprotocol/sdk` TypeScript client, real subprocess
  stdio** against the documented bin (`initialize → tools/list → tools/call`):
  tested in `packages/mcp/tests/stdio.test.ts`, including clean-stdout and
  startup-failure checks.
- **Official SDK client over in-memory transport**: also covered.
- Desktop clients (Claude Desktop, Cursor, etc.): **not yet tested**: configure
  per the generic snippet above and report results before claiming support.

## Client compatibility

| Client or transport | Status | Setup |
|---|---|---|
| Official TypeScript SDK subprocess stdio | Automated test coverage | Repository launcher shown above |
| Official SDK in-memory transport | Automated test coverage | Test harness only |
| Claude Desktop / other desktop clients | Not manually verified | Local stdio-capable client; use absolute launcher path |
| ChatGPT hosted connection | Not provided by this adapter | Requires a hosted transport; local stdio JSON is not a hosted connector |
| Hosted MCP with OAuth | Not implemented | Separate product work |

## Troubleshooting

- Launcher cannot resolve dependencies: run `npm ci` in the authorized source
  checkout and check Node version. Do not substitute an unrelated public package.
- Client never initializes: use the absolute launcher path and inspect stderr.
  Do not write debugging output to stdout.
- `401`: verify the configured product key is current; create a replacement in
  the UI if revoked. `403`: check scopes and account restrictions.
- `transport_outcome_unknown`: retain the returned idempotency key and retry
  the identical operation with that key, never a new one.
- `requires_action`: hand the provided instructions to an authorized person;
  an agent cannot supply TikTok human consent.

## Credential handling

The product key is sent **only** to your configured AiVideoEditor API
(`Authorization: Bearer`). It is never sent to model providers or social
networks, never logged, and URLs are validated so the key cannot follow a
redirect or escape the configured origin.
