Skip to main content
Glama
README.md
# scour-mcp

A remote MCP server that lets an AI assistant furnish a room: search a catalog of furniture and design pieces by dimensions, material, maker, period, location and stock status, then save, compare, swap and cost the results in the user's own projects.

It runs against a mock catalog of 249 listings from 18 fictional galleries, stood up as its own service so it can be built and demoed without touching a real platform. The seam to a real backend is one module (`src/catalog/store.ts`); everything above it works against a `Piece` type, not an API response.

Tools are designed around what a designer is trying to get done, not mapped one-to-one from endpoints. The test case throughout is the sentence a designer actually types:

> Find me a walnut sideboard under 180 cm wide for under $4,000.

which the assistant turns into one call:

```json
{
  "name": "search_pieces",
  "arguments": {
    "category": ["sideboard"],
    "materials": ["walnut"],
    "max_width_cm": 180,
    "price_max": 4000
  }
}
```

and gets back, in about 400 tokens:

```
7 matches, showing 7.
Included related categories: credenza.
Excluded: sold listings.

1. Drava Sideboard — Drava Werkstatt (Vienna)
   drava-sideboard · walnut, oak · W 168 × D 44 × H 75 cm · $3,250 · in stock (3)
   Solid walnut; 168 cm wide, 12 cm under the limit; $3,250; 3 in stock
...
6. Ferrier Enfilade — Atelier Ferrier (Paris)
   ferrier-enfilade · walnut, patinated brass · W 175 × D 43 × H 74 cm · price on request · made to order, 16 wk
   note: price on request — budget fit unconfirmed
7. Marchetti Credenza, c. 1962 — Unattributed (Italian) (Milan)
   marchetti-credenza-1962 · walnut, glass · D 45 × H 82 cm (width not published) · $3,200 · one of a kind, available [partial dimensions]
   note: gallery did not publish a width (listed as "D 45 × H 82 cm")

If none of these work:
  · drop the category filter → 6 more
  · include similar materials (teak, rosewood, elm, cherry) → 3 more
  · widen to 200 cm → 1 more
```

## Quick start

```bash
npm install
npm run build
AUTH_MODE=token DEMO_BEARER_TOKEN=dev-token npm start
```

Then, against the running server:

```bash
curl -s localhost:3000/mcp \
  -H 'Authorization: Bearer dev-token' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
        "name":"search_pieces",
        "arguments":{"category":["sideboard"],"materials":["walnut"],
                     "max_width_cm":180,"price_max":4000}}}'
```

`npm run smoke` does the whole thing end to end — starts the server, connects a real MCP client over HTTP, walks the designer's workflow from brief to costed project, then completes a full OAuth authorization-code flow with PKCE and calls a tool with the issued token. It prints a transcript and exits non-zero on failure.

## Connecting it to an assistant

Deploy it (see below), then add `https://your-host/mcp` as a custom connector in Claude or ChatGPT. With `AUTH_MODE=oauth` the client discovers the authorization server through `/.well-known/oauth-authorization-server`, registers itself dynamically, and sends the user through the login page. No client id to paste, no secret to configure.

The login page accepts any email and no password — see [OAuth](#oauth) for exactly what is real and what is mocked.

## Tools

| Tool | What it is for |
| --- | --- |
| `search_pieces` | Turn a brief into a shortlist. Structured filters for dimensions, material, maker, period, location, price, stock. Returns one line per piece. |
| `get_piece` | One piece in full — construction, provenance, lead time, high-res image URLs. Three verbosity levels. |
| `compare_pieces` | Two to five finalists aligned on the attributes a designer decides on. |
| `catalog_facets` | The exact category, material, period, maker and location values that exist, so the model stops guessing at enums. |
| `list_projects` | The signed-in user's projects and what is saved to each. |
| `create_project` | Start a project for a client, room or wishlist. |
| `add_pieces_to_project` | Save a whole shortlist in one call. `replace_piece_id` makes it a swap. |
| `remove_piece_from_project` | Remove a piece, optionally only from one room. |
| `project_cost_summary` | Total a project by room, category or maker, with lead times. |

One prompt, `client_brief`, carries the intended tool order for the full workflow.

## Design notes

Three decisions do most of the work. They are the difference between a search tool an assistant can hold a conversation with and one that dead-ends.

**Results are sized for a context window, not for completeness.** A page of search results is one line per piece and the five fields a designer decides on. Full specs, provenance and image URLs live behind `get_piece`, and its description tells the model not to come back to `search_pieces` for them. Ten full listings would be several thousand tokens the assistant then cannot spend on the conversation. `limit` is capped server-side at `MAX_PAGE_SIZE` regardless of what the caller asks for, because a model that asks for 100 results is a model about to lose the thread. `MCP_RESPONSE_MODE` controls whether a result carries the text rendering, the structured payload, or both — on a client that reads structured output, `structured` halves the cost of every call.

**Missing data is surfaced, not hidden.** Independent galleries publish inconsistently: about one listing in ten omits a dimension and one in fourteen withholds a price. A width-constrained search cannot verify a listing with no published width, so that listing comes back ranked lower and flagged `dimension_confidence: "partial"`, with a caveat naming what the gallery left out. A designer would rather see a near-miss with a note than lose a piece that was actually right. `include_partial_dimensions: false` is there for the case where the constraint is a built-in alcove and a maybe is useless. Price-on-request listings are treated the same way, because "no public price" is not "over budget". Non-USD listings are converted before the budget is applied and the result says so.

**A short result set explains what would help.** Every search also computes what loosening one constraint would buy, and returns the counts: widen the width by 10%, raise the budget by 20%, include adjacent woods, include sold pieces that a gallery might re-commission. Only relaxations with something behind them are returned, each with the exact arguments to apply, so the assistant can offer a real next step instead of reporting a dead end. Three hits and "6 more at 195 cm" is a usable answer; three hits alone is a conversation that stops.

Smaller things in the same spirit: a sideboard search includes credenzas and says so in the response, because a designer asking for one will look at the other; relevance rewards a piece that uses the available width rather than the smallest thing that fits, since a 120 cm piece on a 180 cm wall reads as undersized; sold pieces are excluded by default, because a shortlist a client cannot buy is not a shortlist; and errors name what went wrong and what to do next — an unknown project id comes back with the projects that do exist, so the model recovers instead of guessing.

## OAuth

`AUTH_MODE=oauth` runs a real OAuth 2.1 authorization server: authorization code flow with PKCE (S256 required), dynamic client registration, refresh token rotation with replay refused, token revocation, audience pinning to the server's resource identifier, and the `.well-known` metadata documents clients discover all of it through. Unauthenticated calls get a `401` with a `WWW-Authenticate` header pointing at the protected-resource metadata, which is how a connector knows to start the flow. Tool handlers receive the authenticated user id, and projects are scoped to it — that is why this server needs OAuth at all rather than an API key: the assistant saves into the designer's own account.

What is mocked is only the identity step. The login page accepts any email, checks no password, and uses the email as the user id. Swapping it for the platform's own login or an upstream IdP touches `authorize` and `completeAuthorization` in `src/auth/provider.ts` and nothing else.

Tokens, codes and clients are held in memory. The records already have the shape the Redis or Postgres tables would, but a restart signs everyone out and more than one instance will not share sessions, so that is the first thing to replace before this carries real traffic.

Two other auth modes exist for development: `token` (static bearer from `DEMO_BEARER_TOKEN`, for curl and CI) and `none` (single shared demo user, local only).

## Architecture

```
src/
  index.ts              Express app: /mcp, OAuth router, /healthz
  config.ts             Environment, validated at startup
  auth/provider.ts      OAuth 2.1 authorization server + static-token verifier
  mcp/
    server.ts           McpServer factory, one per request (stateless)
    tools.ts            Tool and prompt definitions
    format.ts           Result rendering and context-size policy
  catalog/
    types.ts            Piece, Dimensions, Price, Availability
    store.ts            Catalog loading — the seam to the real platform
    search.ts           Filtering, ranking, relaxations
    generate.ts         Deterministic mock-catalog generator
  projects/store.ts     Per-user projects
data/catalog.json       Generated; regenerate with `npm run seed`
```

The transport is stateless Streamable HTTP: a fresh `McpServer` and transport per request, no session id, nothing to clean up between calls and no client pinned to one instance. That makes it deployable to a container, a worker, or anything that can serve HTTP, and horizontally scalable the moment the in-memory stores move out of process.

## Tests

```bash
npm test     # unit: search semantics, ranking, pagination, project store
npm run smoke  # end-to-end over HTTP, including the full OAuth flow
```

The unit tests are written against the behaviour that matters rather than the implementation: that a partial-dimension listing surfaces flagged, that a relaxation the server suggests actually reaches the piece it promised, that a rotated refresh token cannot be replayed, that `limit` is capped, that a malformed cursor falls back to the first page instead of throwing.

## Deploy

Any of these work as-is. Set `PUBLIC_URL` to the deployed HTTPS URL afterwards — OAuth metadata, redirect handling and the resource identifier all derive from it, and a wrong value breaks the connector flow with a confusing error.

- **Docker**: `docker build -t scour-mcp . && docker run -p 3000:3000 -e PUBLIC_URL=https://your-host scour-mcp`
- **Railway**: `railway.json` is included; set `PUBLIC_URL` and `AUTH_MODE`.
- **Render**: `render.yaml` is included; set `PUBLIC_URL` after the first deploy.

`GET /healthz` returns catalog and auth status for a load balancer to probe.

## What is mock

The catalog, the galleries, the makers and the prices are invented. Image URLs point at a `scour.mock` host and do not resolve — they are there to show the shape and resolutions a mood-board or render pipeline would be handed, not to serve pictures. The login page authenticates nobody. Projects, tokens and registered clients live in memory and do not survive a restart.

Everything else — the MCP protocol surface, the transport, the OAuth flow, the search semantics — is real.

## Licence

MIT.