Skip to main content
Glama
Atelier Finder MCP

Atelier Finder MCP

by RaulGGdev
README.md
# Atelier Finder MCP

A **remote MCP server in TypeScript** that lets an AI assistant (Claude, ChatGPT, any MCP client) search a catalog of design furniture, shortlist a room within a budget, and keep private per-user projects. It runs on **Cloudflare Workers**, speaks **Streamable HTTP**, signs users in with **OAuth** (GitHub as identity provider), and reads from a **mock catalog backend that runs as its own service**.

All data is fictional: the makers, pieces, prices and the "Meridian Inventory" distributor do not exist. Images are SVG placeholders generated by the API.

Author: Raul Garcia Grifoll. MIT license.

## Architecture

```mermaid
flowchart LR
  C["MCP client<br/>(Claude / ChatGPT / Inspector)"] -- "Streamable HTTP + OAuth 2.1" --> M
  subgraph CF["Cloudflare"]
    M["furniture-mcp-server<br/>OAuthProvider + stateless MCP handler<br/>tools, resource, prompt"]
    K[("KV: OAuth clients,<br/>grants, state")]
    CAT["furniture-catalog-api<br/>REST over the mock catalog<br/>NO public route"]
    DO[("Durable Object per user<br/>projects")]
    M -- "service binding CATALOG<br/>(+ authenticated user header)" --> CAT
    M --- K
    CAT --- DO
  end
  M -. "sign-in only" .-> G["GitHub OAuth"]
```

| Part | Responsibility |
| --- | --- |
| `apps/mcp-server` | OAuth endpoints (`/authorize`, `/token`, `/register`), the `/mcp` endpoint, tool design, response shaping. Holds no business data. |
| `apps/catalog-api` | Mock backend: ~60 deterministic pieces, search/filter/sort/cursor pagination, SVG images, per-user projects with demo currency conversion. Only reachable through a **Workers service binding**: no routes, `workers_dev: false`, no preview URLs. |

Design decisions:

- **Stateless MCP handler** (`createMcpHandler` from `agents/mcp/server`, the pattern in Cloudflare's current `remote-mcp-github-oauth` demo) instead of a Durable Object per MCP session. All state lives in the catalog service, so the MCP worker scales without session affinity.
- **Identity never comes from tool input.** The user id is `gh-<numeric GitHub id>` from the OAuth session; the immutable id is used instead of the login, because logins can be renamed and re-registered by someone else, who would otherwise inherit the old projects. The MCP worker forwards it in a header that only it can set (the catalog has no public route), and the catalog enforces `header == :uid` again. Projects live in one Durable Object per user, so isolation holds even if a check were missed.
- **The tools are shaped for models, not mirrored from endpoints** (see below).

## Tools

| Tool | Purpose |
| --- | --- |
| `search_pieces` | Structured filters + free text. Compact cards, filters echo, self-contained pagination cursor, relaxation suggestions on zero results. |
| `get_piece` | Full details for 1-5 ids, with thumbnail and full-size image URLs. |
| `compare_pieces` | Side-by-side table for 2-5 ids plus cheapest / narrowest / fastest-delivery takeaways. |
| `shortlist_for_brief` | Room type, style keywords, total budget, room or piece size limits, categories: one pick plus 2 alternates per category that fit the budget. Deterministic scoring, no LLM inside. |
| `list_projects`, `create_project`, `add_to_project`, `remove_from_project`, `swap_in_project`, `project_summary` | Private per-user projects. The summary gives totals per category in the requested currency and flags sold-out pieces. |

Also exposed: resource `catalog://makers` and prompt `furnish_room`. The server sends an `instructions` string explaining when to use which tool, and every tool carries read-only / destructive annotations.

Everything under `/mcp` requires sign-in (the OAuth provider rejects unauthenticated calls with `401`). Project tools additionally scope all data to the signed-in user.

## Tool design: "a walnut sideboard under 180 cm wide for under $4,000"

The model maps the request to one call. Field names carry their units and every filter is optional:

```json
{
  "category": "sideboard",
  "material": "walnut",
  "max_width_cm": 180,
  "max_price": 4000,
  "currency": "USD"
}
```

Result (default page size 8; sold-out pieces are excluded unless asked for):

```text
Found 4 pieces (showing 1-4, prices in USD). Filters: category=sideboard, material=walnut, max_price=4000 USD, max_width_cm=180, sold-out excluded.
1. [sb-01] Halden Sideboard — Studio Halvard | W172×D45×H78 cm | $3,450 | in stock | Copenhagen, DK | https://<worker>/images/sb-01.svg?w=320
2. [sb-02] Vesper Sideboard — Kasuga Atelier | W160×D42×H70 cm | $2,890 | made to order (~6 wk) | Kyoto, JP | …
3. [sb-03] Maren Credenza — Casa Olmedo | W178×D48×H80 cm | $3,980 | in stock | Barcelona, ES | …
4. [sb-05] Brisa Sideboard — Atelier Sorel | W150×D40×H85 cm | $2,268 (listed €2,100) | in stock | Brussels, BE | …
Use get_piece for full specs, compare_pieces to weigh options, add_to_project to save one.
```

Choices behind it:

- **One line per piece**: id, title, maker, `W×D×H cm`, price, availability, location, thumbnail. Enough to choose; full records are one `get_piece` away. The same data is returned as `structuredContent`.
- **Prices are converted to the requested currency** with fixed demo rates, and the listed price is shown when it differs, so the model never compares USD with EUR by accident.
- **Pagination is one value.** `next_cursor` encodes the original filters, so the model calls `search_pieces({ cursor })` and cannot drift from the original query. The cursor is validated like any other input.
- **Zero results never dead-end.** If the same query had `max_price: 1500`, the result is:

  ```text
  No pieces match: category=sideboard, material=walnut, max_price=1500 USD, max_width_cm=180, sold-out excluded.
  Closest options if you relax one constraint:
  - raise max_price from 1500 to 2268 USD → 5 matches, e.g. [sb-05]
  Tell the user what you relaxed, then call search_pieces again with the changed filter.
  ```

  Each suggestion (up to 3, best first) re-runs the search without one filter, keeps only those that return results, and computes the nearest value to move to from the data.
- **Errors tell the model how to recover** (invalid cursor, unknown ids, sold-out replacement, project limits, sign-in required) and never expose internals.

## Local development

Requirements: Node 20+.

```bash
npm install

# 1. GitHub OAuth App for local dev: callback URL http://localhost:8788/callback
# 2. Local secrets (gitignored):
cp apps/mcp-server/.dev.vars.example apps/mcp-server/.dev.vars   # then fill in the values

npm run dev   # starts both workers; MCP endpoint: http://localhost:8788/mcp
```

Try it with the MCP Inspector:

```bash
npx @modelcontextprotocol/inspector
# Transport: Streamable HTTP, URL: http://localhost:8788/mcp, then run the OAuth flow
```

`wrangler dev` runs both workers locally and wires the `CATALOG` service binding between them.

## Deploy

1. **Create a GitHub OAuth App** (GitHub > Settings > Developer settings > OAuth Apps). Homepage `https://<mcp-worker>.<subdomain>.workers.dev`, callback `https://<mcp-worker>.<subdomain>.workers.dev/callback`. Note the client id and generate a client secret.
2. **Deploy the catalog first** (the MCP worker binds to it):

   ```bash
   npx wrangler deploy -c apps/catalog-api/wrangler.jsonc
   ```

3. **Create the KV namespace** and paste the printed id into `apps/mcp-server/wrangler.jsonc` (`kv_namespaces[0].id`):

   ```bash
   npx wrangler kv namespace create OAUTH_KV
   ```

4. **Set `MCP_RESOURCE`** in `apps/mcp-server/wrangler.jsonc` to `https://<mcp-worker>.<subdomain>.workers.dev/mcp`.
5. **Set the secrets** and deploy:

   ```bash
   cd apps/mcp-server
   npx wrangler secret put GITHUB_CLIENT_ID
   npx wrangler secret put GITHUB_CLIENT_SECRET
   npx wrangler secret put COOKIE_ENCRYPTION_KEY   # e.g. the output of: openssl rand -hex 32
   npx wrangler deploy
   ```

`npm run deploy` runs both deploys in order once the KV id and `MCP_RESOURCE` are set.

## Connect a client

- **Claude** (claude.ai, Desktop, mobile): Settings > Connectors > Add custom connector, URL `https://<mcp-worker>.<subdomain>.workers.dev/mcp`. Claude registers itself via dynamic client registration and opens the sign-in page.
- **ChatGPT**: enable developer mode (Settings > Connectors > Advanced), create a connector with the same URL and OAuth authentication. Availability depends on the plan.
- **Claude Code**: `claude mcp add --transport http atelier-finder https://<mcp-worker>.<subdomain>.workers.dev/mcp`, then authenticate with `/mcp`.

Try: "Find me a walnut sideboard under 180 cm wide for under $4,000", or "Furnish my living room in a japandi style for 12000 USD and save it as a project".

## Testing

```bash
npm test            # vitest, both apps, no network or Cloudflare account needed
npm run typecheck   # tsc --noEmit in every workspace
npx wrangler deploy --dry-run -c apps/catalog-api/wrangler.jsonc   # validates config and bundle
npx wrangler deploy --dry-run -c apps/mcp-server/wrangler.jsonc
```

Coverage: catalog filtering, currency conversion, sorting, pagination and input validation; project lifecycle, totals and **cross-user authorization**; tool response shaping (compactness, cursor, zero-result suggestions); budget shortlist logic; and an in-memory MCP client/server round trip (tools, annotations, resource, prompt, unauthenticated errors). The MCP tests run against the real catalog app in memory, standing in for the service binding.

Not covered by automated tests: the live GitHub sign-in and the Durable Object storage adapter (`projects-do.ts`, a thin wrapper over `ctx.storage`). Both were exercised manually with `wrangler dev`.

## Security notes

- **OAuth**: the MCP worker is an OAuth 2.1 authorization server (`@cloudflare/workers-oauth-provider`, PKCE, dynamic client registration) that delegates identity to GitHub. The consent flow follows Cloudflare's reference implementation: CSRF token, one-time state in KV bound to the browser by a `__Host-` cookie, and an HMAC-signed cookie for approved clients (`COOKIE_ENCRYPTION_KEY`).
- **Least data**: GitHub is asked for no scopes; only the numeric id (identity) plus login and display name (display only) are kept in the encrypted session, and the GitHub access token is discarded. Logs contain error class names and status codes, not user data.
- **Secrets** only through `wrangler secret` or the gitignored `.dev.vars`.
- **Catalog isolation**: no route, no `workers.dev` URL, no preview URLs. Ownership is checked in the Worker, in the per-user Durable Object routing, and by the header/path match.
- **Input validation** with zod on every tool and every endpoint: unknown query parameters are rejected, id arrays and string lengths are capped, request bodies are limited to 8 KB, pages to 50 items, and projects to 20 per user with 50 pieces each.
- Images are generated with escaped text and served with a restrictive `Content-Security-Policy`.

## Known limitations

- Fictional data and **fixed demo exchange rates** (1 EUR = 1.08 USD); only USD and EUR.
- No application-level rate limiting; put Cloudflare rate limiting rules in front for a public deployment.
- Sign-in is GitHub only; the user id is `gh-<numeric GitHub id>`.
- The catalog is in code, so changing it means redeploying `catalog-api`.
- `swap_in_project` validates first, then adds and removes in two calls, so a crash between them could leave both pieces in the project (the project stays consistent and the call can be retried).

## Credits

The OAuth handlers in `apps/mcp-server/src/{github-handler,utils,workers-oauth-utils}.ts` are adapted from Cloudflare's `remote-mcp-github-oauth` demo ([cloudflare/ai](https://github.com/cloudflare/ai), MIT).

## License

MIT, see `LICENSE`.