# same.lens for AI agents

same.lens (https://samelens.hails.info) is a visual search engine over image datasets where
you choose what "similar" means. A search ranks images by a query (words, an image already
on the site, or an image you upload). A **lens** narrows similarity to one concept, such as
color, art style, garment or designer, so results match the query on that concept only.

The site, its HTTP API and its MCP server all run the same typed operations, so anything a
person can find on the site, you can find too. Every result carries links: show a person the
`url` of a search or an item and it opens in their browser.

## Connect

**MCP** (recommended): a stateless streamable-HTTP endpoint; no sign-in needed.

```sh
claude mcp add --transport http samelens https://samelens.hails.info/mcp
```

Any other MCP client: add a server whose transport is streamable HTTP and whose URL is
`https://samelens.hails.info/mcp`. It accepts POST only; a GET returns 405 because there is no
event stream to open. The server's instructions and each tool's JSON schema describe
everything below.

**HTTP**: plain JSON over HTTPS; no sign-in needed either. The OpenAPI schema is at
[`/openapi.json`](https://samelens.hails.info/openapi.json), browsable at
[`/docs`](https://samelens.hails.info/docs).

```sh
curl -s https://samelens.hails.info/api/collections
curl -s https://samelens.hails.info/api/search -H 'content-type: application/json' \
  -d '{"collections": ["fashion"], "query": {"text": "a red evening gown"},
       "lenses": [{"preset": "dress-color"}], "limit": 5}'
```

**CLI**: in a checkout of the project, `samelens <command> --url https://samelens.hails.info`
calls this server, one command per operation (`samelens search --help`). It prints JSON.

### Acting as a person (optional)

Everything above works without signing in, over public sources. To act as a person (to
see their private sources too, keep the images you upload, and save to their collections),
send one of their API tokens. They create it on the site,
signed in: their picture, then **API tokens**. The secret is shown once and can be revoked
there at any time.

```sh
claude mcp add --transport http samelens https://samelens.hails.info/mcp \
  --header "Authorization: Bearer $SAMELENS_TOKEN"
curl -s https://samelens.hails.info/api/collections -H "Authorization: Bearer $SAMELENS_TOKEN"
samelens list-sources --url https://samelens.hails.info --token "$SAMELENS_TOKEN"  # or set SAMELENS_TOKEN
```

A token that isn't valid (mistyped or revoked) gets a 401, never a quiet signed-out answer.
Tokens can't create or list tokens; that takes the site.

## A first session

1. `list_sources`: see each source's `id`, `count`, lenses (their `id`s) and suggested
   searches, plus the browse themes.
2. `search` with a query and, optionally, lenses. Read the hits' `title`, `score`, `clear`
   and `labels`; give the person the search's `url`, or a hit's `url` or `image_url`.
3. Refine: search from a hit (`{"item": hit.id, "collection": hit.collection}`), combine
   terms, add or weight lenses, or write a lens from words with `describe_lens`.

## Concepts

- **Source**: a dataset, named by `id` (`ui`, `laion-pop-xl`, `fashion`, `keaton`,
  `midjourney`, `illustrations:met`, ...; `list_sources` has the current list). A search
  covers the sources in `collections` as one pool; leave it out to search every source.
  `keaton` is a video source: its items are four-second moments of silent films. Its
  `films` in `list_sources` give each film's `slug`, length and major `scenes` (start, end,
  and a `label` where someone named it). Pass a `slug` as `film` to search or list only that
  film's moments.
- **Item**: one image or film moment, named by `id` together with its `collection`.
- **Query**: one term, or a list of up to 8 combined terms. A term is exactly one of
  `{"text": "..."}`, `{"item": "<id>", "collection": "<source>"}` or
  `{"upload": "<token>"}`, with an optional `weight`. Only the ratios between weights matter,
  and a negative weight ranks what is *unlike* that term higher (for example
  `[{"item": ...}, {"text": "dark mode", "weight": -1}]`).
- **Lens**: `{"preset": "<lens id>"}` from a source's `lenses`, or a custom lens
  `{"groups": [{"template": "a photo of a {x} dress", "classes": ["silk", "denim", ...]}]}`.
  - A *prompt* lens projects the embedding onto the space its prompts span.
  - A *feature* lens (`kind: "feature"`, e.g. Midjourney's `texture` or `palette`) compares
    features of the images themselves, and ranks only sources whose `lenses` list it, so
    search those. Every query term must be an image. One with `reads_any_image: true`
    computes the query's features from its pixels, so any image term works, an upload
    included; one with `false` (the neural `resnet`, `siglip` and `shape`) needs every term
    to be an item of a source that lists it.
  - The *doodle* feature lens (`doodle`) matches where outlines fall in the frame, on a 16 ×
    16 grid, after [Doodle Archive](https://doodle-archive.novia-chao.workers.dev/). To search
    by a sketch, draw dark lines on a light square (a PNG you render, from SVG say), upload
    it with `upload_image`, and search `{"upload": "<token>"}` through
    `[{"preset": "doodle"}]` alone. A photo works as a query too: only its outlines count.
  - Several lenses combine by their `weight`s; a negative lens weight counts against a
    match. With no lens, the whole embedding ranks ("Everything" on the site).
- **Scores**: each hit has `score`, `z` (standard deviations above the searched pool's
  mean) and `clear`, true when the hit clears the query's clear-match threshold (`clear.z`).
  Treat clear hits as real matches and the rest as the nearest available. `labels` names,
  for each prompt lens, the prompt the hit reads as; a lens's `query_reading` says how it
  reads the query (for example red 99.98%).

## Links

Every response links back into same.lens:

| object | field | opens |
|---|---|---|
| search result | `url` | the search on the site (query, lenses and sources) |
| item / hit | `url` | the item's page: a search from it |
| item / hit | `thumbnail_url`, `image_url` | its thumbnail and its largest stored image (WebP) |
| film moment | `video_url` | the film's MP4, with `#t=start,end` for the moment |
| source | `url` | the site, browsing that source |
| film | `url`, `video_url` | the film laid out by its scenes; the MP4 |
| theme | `url` | the theme's browse page |

A search's link has no `k`, `method` or paging. The site shows only weights of ±¼, ½, 1, 2
and 4. An upload term made signed out only works while the server still holds its token;
a stored upload's term keeps working for the person who uploaded it. Items also
carry `source` (where the image came from) and `credit`; when an item has `creator`,
`license`, `license_url` and `attribution`, credit it when you show the image. An item
rated above general carries `rating`; over these interfaces that is only ever `sensitive`
(see Limits).

## Operations

Each operation is an MCP tool and an HTTP route. GET routes take their input as query
parameters (repeat a list: `?collections=ui&collections=fashion`); POST routes take a JSON
body.

| tool | HTTP | does |
|---|---|---|
| `list_sources` | `GET /api/collections` | sources, their lenses and suggestions, browse themes |
| `search` | `POST /api/search` | rank items by a query, through lenses |
| `explore` | `GET /api/explore` | seeded pages of a curated browse theme |
| `sample` | `GET /api/random` | a seeded random sample, taking turns between sources |
| `fit_lens` | `POST /api/lens` | how much of a lens's prompt variance each `k` keeps |
| `describe_lens` | `POST /api/lens/describe` | write a custom lens from a description (an LLM) |
| `upload_image` | `POST /api/upload` | embed your own image; returns a token, and signed in a stored item |
| `upload_image_url` | `POST /api/upload-url` | the same for a public image URL, plus a preview |
| `remove_upload` | `POST /api/uploads/remove` | delete one of your stored uploads (signed in) |
| `import_video` | `POST /api/videos/import` | import a video into your private source (signed in) |
| `video_job` | `GET /api/videos/job` | how an import or removal stands |
| `list_videos` | `GET /api/videos` | your imported films and your video jobs |
| `remove_video` | `POST /api/videos/remove` | remove one of your films |
| `share_videos` | `POST /api/videos/share` | make your videos public under a title, or private |
| `capabilities` | `GET /api/capabilities` | whether text search, uploads and `describe_lens` work |

### `search`

| field | default | |
|---|---|---|
| `query` | required | a term or a list of 1 to 8 terms (see Concepts) |
| `collections` | every source | source ids, searched as one pool |
| `lenses` | `[]` | up to 14 lenses; at most one custom |
| `limit`, `offset` | 60, 0 | paging; `limit` ≤ 200, `offset` ≤ 5000 |
| `film` | none | a film's slug: rank only its moments; `collections` must be its one video source |
| `k`, `method` | the lens's own | tuning for a single prompt lens; rarely needed |

The response includes `url`, `total` (items ranked), `query` (each term as resolved, an
item term with its item), `clear`, `lenses` (each lens's reading of the query) and `hits`.
An abridged example:

```json
{
  "url": "https://samelens.hails.info/?c=fashion&q=text:a%20red%20evening%20gown&lens=dress-color",
  "query": {"text": "a red evening gown"},
  "total": 26971,
  "clear": {"z": 3.082, "count": 211},
  "lenses": [{"k": 32, "query_reading": [{"label": "red", "p": 0.9998}]}],
  "hits": [
    {
      "id": "rc_57fc3fa51858",
      "collection": "fashion",
      "title": "Isabelle Huppert-63577",
      "source": "https://commons.wikimedia.org/wiki/File:Isabelle_Huppert-63577.jpg",
      "url": "https://samelens.hails.info/?q=item:fashion/rc_57fc3fa51858",
      "thumbnail_url": "https://samelens.hails.info/img/fashion/thumb/rc_57fc3fa51858.webp",
      "image_url": "https://samelens.hails.info/img/fashion/full/rc_57fc3fa51858.webp",
      "score": 0.8641,
      "z": 3.8,
      "clear": true,
      "labels": ["red"]
    }
  ]
}
```

### The others

- `explore`: `theme` (an id from `list_sources`'s `themes`; default `variety` mixes them
  all), `collections`, `seed`, `limit` (≤ 200), `offset`. Returns `items` and `total`.
- `sample`: `collections`, `seed`, `limit` (≤ 200), `offset`. Returns `items` and `total`.
  Change `seed` for a different sample; use it to find items to search from. With `film`
  (and `collections` naming its one video source) it lists that film's moments in the order
  the film runs instead.
- `fit_lens`: `preset` or `groups`. Returns `max_k` and `variance_kept`, a list holding the
  variance kept at each `k` from 1.
- `describe_lens`: `description` (3 or more characters, e.g. "the mood of the lighting") and
  optionally `collection`. Returns `name` and `groups`; search with
  `{"groups": <groups>}` as a lens. It calls an LLM, so use it when no preset fits.
- `upload_image`: over HTTP, a multipart `file`; over MCP, `image` as base64. Images up to
  15 MB. Returns a `token`; search with `{"upload": "<token>"}`. Signed out, nothing is
  stored: the token lives in that server process's memory and can expire, so search with
  it soon. Signed in, it also returns the stored `item` (see Your uploads).
- `upload_image_url`: `url`, a public HTTP(S) image URL. The server downloads it (up to 15
  MB, within 20 seconds) and uploads it like `upload_image`. URLs that resolve to private
  networks, carry a login or use a custom port are refused, redirects included. Returns
  the `token`, the stored `item` when signed in, and a `preview`: the image as embedded, as
  a JPEG `data:` URL (tens of kilobytes, so skip it unless you need it).
- `capabilities`: `embed` (text search and uploads work) and `describe` (`describe_lens`
  works). When `embed` is false, search from items only.

### Your uploads

Signed in (an API token), every image you upload is kept: `upload_image` and
`upload_image_url` store it in your own uploads source, private to you, and return it as
an `item` with its `collection` (that source's id), `id`, `url`, `thumbnail_url` and
`image_url`. It stays until you remove it, across restarts.

- Search from it as any item, `{"item": item.id, "collection": item.collection}`; its token
  does the same for you. It is never a hit of its own search.
- Search or list all your uploads with `collections: [item.collection]` (`search`,
  `sample`); `list_sources` shows the source to you, as "Your uploads". Searching every
  source includes it, for you alone.
- Save it to one of your saved collections (below), like any item.
- Uploading the same image again returns the same item. Each person keeps up to 2,000
  uploads; `remove_upload` with an item's `id` deletes one, and the last takes the source.

Your uploads are private: no one else can see, search or open them, even in a saved
collection you made public. There they count as `unavailable` to everyone but you.

### Saved collections

Saved collections are the images a person saves on the site. They are HTTP only (no MCP
tool or CLI command yet), and every route but reading a public one needs a token:

| HTTP | does |
|---|---|
| `GET /api/saved` | your collections, each with `id` (`col_…`), `name`, `public` and `count` |
| `POST /api/saved` | create one: `{"name": "...", "public": false}`, optionally with a first `item` |
| `GET /api/saved/<id>?limit=200` | a collection's `items`, newest first, and how many are `unavailable` |
| `POST /api/saved/<id>/items` | save an item: `{"collection": "<source>", "item": "<id>"}` |
| `DELETE /api/saved/<id>/items?collection=<source>&item=<id>` | take an item out |

A private collection is a 404 to anyone but its owner. The site shows a collection at
`https://samelens.hails.info/?p=<id>`.

```sh
up=$(curl -s https://samelens.hails.info/api/upload -H "Authorization: Bearer $SAMELENS_TOKEN" \
  -F file=@design.png)
curl -s https://samelens.hails.info/api/saved/col_…/items -H "Authorization: Bearer $SAMELENS_TOKEN" \
  -H 'content-type: application/json' \
  -d "$(jq '{collection: .item.collection, item: .item.id}' <<<"$up")"
```

### Your videos

Signed in (an API token), you can import videos into your own source. It is private, seen
by you alone, until you share it.

1. `import_video` with `url`, the public URL of the video **file** (MP4, WebM, MOV...; not a
   page that plays it, so not YouTube), and optionally a `title`. It returns a job at once.
2. Poll `video_job` with the job's `id` every few seconds. It passes `queued`,
   `downloading`, `building` and `embedding`, then ends `ready` (with a `film_url`) or
   `failed` (with an `error`).
3. Search it: `search` with `collections: [<job.source>]`, and `film: <job.film>` to stay
   within that one film. Its moments are four seconds each, and hits carry `video_url`s
   that seek to them.

`list_videos` lists your films (with their scenes), whether they are shared, and recent
jobs. `remove_video` with a film's slug deletes it, also as a job. `share_videos` with
`public: true` and a `title` (what others see them as) lets everyone see and search all
your videos; `public: false` makes them private again, at once. Each person has up to 20
videos, each up to 15 minutes and 500 MB.

## Errors

- **HTTP**: a failed request has a 4xx/5xx status and a JSON body `{"detail": ...}`. The
  detail is a message, or for 422 a list of validation errors naming the bad field.
  - 400: an unknown source, theme or lens, a lens that doesn't fit the query, or a `film`
    without its one video source. Also an image URL that is refused or can't be downloaded,
    or a file that isn't an image.
  - 401: an API token that isn't valid, or an `Authorization` header that isn't
    `Bearer <token>`; or a video operation or `remove_upload` without one.
  - 404: an unknown item, film, video job or stored upload.
  - 409: already 20 imported videos, or 2,000 stored uploads; remove some first.
  - 413: an image over 15 MB.
  - 422: invalid input, or text that is empty.
  - 429: the lens writer, or the video queue, is busy; retry shortly.
  - 503: embedding, lens writing or video import is unavailable on this server, or it is
    short of space to store uploads or videos.
- **MCP**: the tool result has `isError: true` and the text
  `<tool> failed (<status>): <detail>`, or `invalid arguments for <tool>: ...`.
  Read the detail: an unknown source lists the sources there are.

## Limits

- Without an API token, public sources only, and uploads are not kept; with one, its
  person's private sources too, and their uploads are stored.
- No restricted items by default: an item rated `questionable` or `explicit` is shown only
  to a person who turned the restriction off in their account menu on the site, signed in
  there. A token cannot change that setting; it follows its person's. To everyone else it is
  absent: no listing, count or ranking includes it, a search from it is a 404, and so are
  its images.
- A query has at most 8 terms; a search has at most 14 lenses, with at most one custom;
  `limit` ≤ 200 and `offset` ≤ 5000.
- `describe_lens`, `upload_image`, `upload_image_url`, `remove_upload`, `import_video`,
  `remove_video` and `share_videos` do real work on the server (an LLM call, embedding,
  storing, downloading, building video), so call them only when you need them; every other
  operation is read-only.
