# Hyperchat MCP

Hyperchat ships an MCP server using the official TypeScript SDK. It supports stdio for locally launched agents and stateless Streamable HTTP at `/api/mcp` for remote clients. Both transports use the same workspace API, tool definitions, resources and prompts.

## Connect

Create a key in **Settings → Developer API** with the permissions the agent needs. The key is limited to one workspace, has an expiry, and can be revoked. Store it as a secret in the client; never paste a real key into a prompt, repository or exported configuration.

For a local installation, replace the path and configure these environment variables through the MCP client's secret settings:

```json
{
  "mcpServers": {
    "hyperchat": {
      "command": "pnpm",
      "args": ["--dir", "/absolute/path/to/hyperchat", "--silent", "mcp"],
      "env": {
        "HYPERCHAT_API_URL": "https://YOUR-DEPLOYMENT.convex.site/api/v1",
        "HYPERCHAT_API_KEY": "YOUR_WORKSPACE_KEY"
      }
    }
  }
}
```

`--silent` keeps package-manager output out of the JSON-RPC stdout stream. The process checks the workspace connection at startup. Startup failures write a generic diagnostic to stderr, without the secret. Run `pnpm install --frozen-lockfile` before starting a new installation.

For a remote client, use Streamable HTTP:

- Endpoint: `https://YOUR-HYPERCHAT-SITE/api/mcp`
- Header: `Authorization: Bearer YOUR_WORKSPACE_KEY`
- Transport: Streamable HTTP

Configure `NEXT_PUBLIC_CONVEX_SITE_URL` on the web server. `NEXT_PUBLIC_SITE_URL` (or a server-side `SITE_URL`) sets the allowed web origin; `MCP_ALLOWED_ORIGIN` can permit one additional origin. Absent Origin headers are accepted for server clients. Origins that are present must be allowlisted. This is a pre-issued workspace-key connection, not an OAuth flow.

Each HTTP request gets a fresh authenticated server instance. Tools recheck permissions at the backend. There are no shared cross-workspace sessions or resumable SSE notifications. GET and DELETE are answered with 405 after authentication. Clients can poll job tools to follow durable generation work.

## Permissions and tools

| Permission | Tools |
| --- | --- |
| Any valid workspace key | `get_workspace` |
| `campaigns:read` | `get_campaign_schema`, `list_campaigns`, `get_campaign`, `list_campaign_images`, `view_campaign_image`, `get_campaign_readiness`, `list_brand_kits`, `get_campaign_results` |
| `campaigns:write` | `create_campaign`, `update_campaign_ad`, `update_campaign_funnel`, `apply_campaign_image`, `save_brand_kit`, `apply_campaign_brand`, `update_campaign_artwork`, `duplicate_campaign` |
| `creative:generate` | `generate_campaign_images`, `cancel_campaign_image` |
| `funnels:publish` | `publish_campaign_funnel` |
| `ads:write` | `prepare_campaign_ads` |
| `contacts:read` | `list_contacts`, `get_contact` |
| `fields:read` | `list_contact_fields` |
| `events:read` | `list_events` |

Tools outside the key's scopes are not advertised. Revoked or expired keys also fail existing connections; queued generation claims and returned image results recheck the key. The same behavior applies to owner/admin membership changes for generations started in the app.

Resources: `hyperchat://campaigns/schema`, `hyperchat://campaigns/{campaignId}`, and `hyperchat://brand-kits`. The campaign resource lists up to 20 recent campaigns; use the paginated tool for more. The `build-lead-generation-campaign` prompt supplies a reusable workflow. Tool responses include structured JSON; completed-image previews use MCP resource links.

## Image-to-ad workflow

1. Read `get_campaign_schema`, ask for missing business facts, and create a draft with a stable request ID.
2. Generate one to three images. Supply the variation index, original art direction, image shape, and optionally an existing workspace image as a product/style reference.
3. Poll `list_campaign_images`. States distinguish queued, generating, completed, failed, unknown and cancelled. Do not regenerate an unknown outcome automatically; the provider may have charged for it.
4. Review the image with `view_campaign_image`. Apply it using current ad/graphic revisions. Applying updates both the native graphic and ad template. An optional funnel image element can be replaced in the same transaction, with its own revision check. The image shape sets the graphic's square, portrait, story or landscape size.
5. Review the complete funnel. The publishing tool requires the separate `funnels:publish` scope, the exact current revision, `confirmPublish: true`, and explicit user authorization in the agent workflow.
6. Read readiness, supply a connected Meta account, advertising account ID, countries, currency and daily budget per ad. Prepare selected ad drafts using current revisions. The returned budget is the total across selected ads.
7. Review and approve delivery in Hyperchat's existing Ads workflow.

Generated images are illustrative artwork; prompts must not invent testimonials, results or unprovided product claims. OpenRouter generation uses the workspace's configured image model, rate limits and credits. Images are imported into workspace storage and retain their job, prompt, model and reported cost. Generation calls are never automatically replayed after an ambiguous result. API request IDs also deduplicate queueing after the normal API receipt expires.

Prepared ads use the applied image as their image asset and the saved headline/body as Meta copy. They do not include the graphic's text overlay. The app shows these image assets before preparation; use the existing PNG export for branded text-overlay versions. Every prepared ad has a variation-specific tracking URL and is saved locally with `state: draft` and provider status `PAUSED`. Preparation makes no advertising provider request and does not start spending.

## REST equivalents

| Method / path | Permission | Behavior |
| --- | --- | --- |
| GET `/agent` | Valid workspace key | Workspace ID, scopes and expiry |
| GET `/campaigns/{id}/images` | campaigns:read | Generation history and completed media |
| POST `/campaigns/{id}/images` | creative:generate | Queue up to three image jobs |
| POST `/campaigns/{id}/images/{jobId}/cancel` | creative:generate | Cancel unfinished work |
| POST `/campaigns/{id}/apply-image` | campaigns:write | Apply completed image with revision checks |
| PATCH `/campaigns/{id}/ads` | campaigns:write | Update ad copy and native graphic text |
| PATCH `/campaigns/{id}/funnel` | campaigns:write | Update native funnel draft |
| GET `/campaigns/{id}/preflight` | campaigns:read | Model, connection, image, publication and prepared-ad state |
| POST `/campaigns/{id}/publish` | funnels:publish | Publish the reviewed revision |
| POST `/campaigns/{id}/ad-drafts` | ads:write | Atomically prepare paused local ad drafts |

All writes require `Idempotency-Key`. Most REST requests are limited to 64 KB. Native funnel updates allow 650,000 encoded bytes with a 300,000-character document limit. MCP messages use a 650,000-byte limit and API responses a 2 MB limit. No keys, provider credentials or auth tokens are returned in resources or error messages. Existing pagination and rate limits still apply.

## Validation and sources

Local validation passes: 79 unit tests, 336 backend tests, the production build, compiled demo browser acceptance, and a connected UI fixture at 1440/390/320px. Captures and machine-readable browser results are in the task worktree’s ignored `artifacts/campaign-studio/` and `artifacts/campaign-production/` directories.

The tests exercise the official SDK client over stdio, in-memory and Streamable HTTP, permission-based discovery, resources, prompts, origin/body limits and errors. A connected fixture test runs MCP → real Convex functions → mocked image provider → image storage → application → funnel publication → three paused ad drafts. Additional tests cover revocation during generation, cancellation, unknown outcomes, cross-workspace references, stale revisions and atomic capacity failures.

No paid live generation, provider advertising action, deployment or customer publication is part of these tests. Backend/schema changes must be deployed before connecting to the new tools on a running site.

References: [official MCP SDK server guide](https://ts.sdk.modelcontextprotocol.io/server), [MCP transport specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), and [OpenRouter image API](https://openrouter.ai/docs/guides/overview/multimodal/image-generation).

The server now exposes 25 tools. See [campaign reuse and results](CAMPAIGN_REUSE.md) for brand-kit versions, duplication boundaries, visual editing, and the attributed results contract.
