Skip to content

Writing A Source

Vitor edited this page Dec 3, 2026 · 1 revision

botticelli

Writing a Source

Status: built (M0). The Source interface and the rules below are in src/. Pinterest is the only adapter today. Are.na is planned (M6, #7).

In one minute

A Source is a place Refs come from. To add one, you write one folder, src/sources/<id>/, that implements the Source interface and returns Refs. You test it with a fake Transport. You register it in src/server/index.ts. The pipeline, the Library and the MCP tools do not change. This page walks through each step with a small adapter you can copy.

Before you start

  1. Read CONTEXT.md and use its terms exactly.
  2. Read ADR 0001 (one adapter per source) and ADR 0003 (no native dependencies).
  3. Open an issue that says which Capabilities the adapter will have. If it makes a decision, such as how it logs in, write an ADR (Decisions).
  4. Branch from dev. Name the branch feat/<id>. The commit scope is the Source id (for example feat(arena): …).

Two constraints shape the code:

  • No native dependencies (ADR 0003). Use fetch-style calls through the Transport, and pure JS. A new runtime dependency needs a reason in the pull request.
  • Offline tests. No unit test touches the network (CONTRIBUTING.md).

The interface

The interface is in src/sources/types.ts. The shared types it uses are in src/core/types.ts.

export interface Source {
  readonly id: SourceId;
  capabilities(): Capabilities;

  search(query: string, opts?: PageOptions): Promise<Page>;
  related?(ref: string, opts?: PageOptions): Promise<Page>;
  collection?(url: string, opts?: PageOptions): Promise<CollectionPage>;
  get?(ref: string): Promise<Ref>;
  visualSearch?(imagePath: string, opts?: PageOptions): Promise<Page>;
  fetchImage(url: string, size: ImageSize): Promise<FetchedImage>;
}

search and fetchImage are required. The rest are optional.

capabilities() returns five booleans, one per optional method plus search:

interface Capabilities {
  search: boolean;
  related: boolean;
  collection: boolean;
  get: boolean;
  visualSearch: boolean;
}
Capability Method What it takes Returns
search search(query, opts) Free text Page
related related(ref, opts) A page URL, short link or the Source's own id Page
collection collection(url, opts) A collection URL or slug CollectionPage (a Page plus collection info)
get get(ref) A page URL or id One Ref
visualSearch visualSearch(imagePath, opts) A path to a local image Page

PageOptions has limit, cursor and media (any, image or video). A Page is { refs, next? }. next is absent at the end of a feed.

A Ref needs source (your id), key and imageUrl. Everything else is optional. Fill what the Source gives you. Do not fill palette or dhash: the pipeline does.

The rules

1. Report only what works right now

capabilities() says what the Source can do at this moment. The server checks it before it calls a method. requireCapability in src/server/context.ts throws a CapabilityError when the Capability is false or when the method is missing. Keep the two in agreement.

2. Leave a method out, or throw CapabilityError

  • The adapter has no implementation at all: leave the method out and report false. The object has no such property.
  • The implementation exists but is unavailable now (for example, it needs a login): report false, and if the method is still there, throw CapabilityError(source, capability, reason).

Do not return an empty page to mean "cannot". An empty page means "no results".

3. fetchImage only talks to your own CDN

fetchImage accepts only the Source's own CDN hosts, over HTTPS. Anything else throws RefusedError before any request is made. The server calls fetchImage for every thumbnail, with URLs that came from a Ref, and for URLs an agent pasted in. This check is the only thing that stops a request to a host the Source does not own.

  • Match the whole host name, not a suffix of the text. img.example.test.evil.test is not img.example.test.
  • Refuse a redirect off the allowed hosts. Pinterest sets redirect: 'error' for downloads.
  • Check the content type (image/*) and cap the size.
  • Map the four sizes (thumb, medium, large, original) onto the CDN's renditions. Fall back to the nearest one that answers. Thumbnails are what the pipeline works on (ADR 0003).

4. Cursors are opaque

Page.next is a string the caller passes back as cursor. Nothing outside your adapter parses it. Encode what you need (a page number, a bookmark, how many refs of a page were already returned) and validate it on the way back in. A cursor that does not decode throws RefusedError. Pinterest does this in decodeCursor in src/sources/pinterest/pinterest.ts.

5. Mark your own non-ref pages as final

When get or related gets a URL of your own Source that is not a ref, such as a board URL, throw RefusedError with { final: true }:

throw new RefusedError(`${url} is a board, not a ref`, { final: true });

The tools that take a ref (look, save, palette) first call get. If get refuses an http(s) URL without final, the server treats the URL as a plain image, and fetchImage then accepts or refuses it. final: true says "this is a page of mine, report the reason, do not retry it as an image". Without it, the agent sees a confusing error about hosts. A refusal of something that is not yours stays non-final.

6. Use the shared errors

Class Throw it when
CapabilityError The Source cannot do this right now
SourceError The Source answered with an error for one request. Pass the HTTP status when you have it
NetworkError The host could not be reached (DNS, TCP, TLS, timeout, a stalled body)
RefusedError An input is refused for safety: a bad cursor, an unknown CDN host, a path outside the Library, an empty query

Never put a cookie, token or other secret in a message. The server returns the message to the agent.

7. Map to Ref carefully

  • key is stable inside the Source. Use the Source's own id when it can be looked up again. Otherwise hash the image URL.
  • Set id and pageUrl only when the Source can look the ref up again. Pinterest's anonymous e1_… ids are not set.
  • Set lowRes when the largest image is under 500 px wide.
  • sourceLink and sourceDomain are where the image came from. They are not your Source.
  • Source-specific fields that do not fit Ref stay out of the public shape, until a second Source needs them (ADR 0001).

8. Leave the Pipeline's job to the Pipeline

Do not filter, dedupe, rank or build palettes in the adapter. Return what the Source gave you. If the adapter must drop something (Pinterest drops ads), say so in Sources.

A skeleton adapter

This adapter has search with a cursor, and fetchImage with the CDN check. It leaves out related, collection, get and visualSearch. Save it as src/sources/example/index.ts. The API behind it is made up.

import { NetworkError, RefusedError, SourceError } from '../../core/errors.js';
import type { Capabilities, FetchedImage, ImageSize, Page, PageOptions, Ref, Transport } from '../../core/types.js';
import type { Source } from '../types.js';

const ID = 'example';
const API = 'https://api.example.test';
const CDN_HOST = 'img.example.test';
const IMAGE_LIMIT = 30 * 1024 * 1024;
const DEFAULT_LIMIT = 20;

export interface ExampleOptions {
  /** The network seam. Tests pass a fake. */
  transport?: Transport;
}

interface ApiItem {
  id: string;
  image: string;
  width?: number;
  height?: number;
  title?: string;
}

/** The cursor is ours: base64url of `{ page }`. Callers pass it back and never read it. */
const encodeCursor = (page: number): string => Buffer.from(JSON.stringify({ page })).toString('base64url');

function decodeCursor(raw: string): number {
  try {
    const value: unknown = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
    const page = (value as { page?: unknown } | null)?.page;
    if (typeof page === 'number' && Number.isInteger(page) && page >= 1) return page;
  } catch {
    // fall through to the refusal
  }
  throw new RefusedError('Not a cursor from this source. Pass `next` back unchanged.');
}

function toRef(item: ApiItem): Ref {
  const ref: Ref = {
    source: ID,
    key: item.id,
    id: item.id,
    pageUrl: `https://example.test/items/${item.id}`,
    imageUrl: item.image,
  };
  if (item.title) ref.title = item.title;
  if (item.width !== undefined) ref.width = item.width;
  if (item.height !== undefined) ref.height = item.height;
  if (item.width !== undefined && item.width < 500) ref.lowRes = true;
  return ref;
}

export function createExampleSource(opts: ExampleOptions = {}): Source {
  const transport: Transport = opts.transport ?? ((url, init) => fetch(url, init));

  /** One request. A refused connection becomes a NetworkError; an HTTP error becomes a SourceError. */
  async function send(url: string): Promise<Response> {
    let res: Response;
    try {
      res = await transport(url);
    } catch (err) {
      const host = new URL(url).hostname;
      throw new NetworkError(host, `Network error reaching ${host}: ${err instanceof Error ? err.message : String(err)}`);
    }
    if (!res.ok) throw new SourceError(ID, `${url} answered HTTP ${res.status}`, res.status);
    return res;
  }

  return {
    id: ID,

    // Report only what works right now. The optional methods below are left out on purpose.
    capabilities(): Capabilities {
      return { search: true, related: false, collection: false, get: false, visualSearch: false };
    },

    async search(query: string, pageOpts: PageOptions = {}): Promise<Page> {
      const q = query.trim();
      if (!q) throw new RefusedError('A search needs a query');
      const page = pageOpts.cursor ? decodeCursor(pageOpts.cursor) : 1;
      const limit = pageOpts.limit ?? DEFAULT_LIMIT;
      const res = await send(`${API}/search?q=${encodeURIComponent(q)}&page=${page}&per_page=${limit}`);
      const body = (await res.json()) as { items?: ApiItem[]; has_more?: boolean };
      const refs = (body.items ?? []).map(toRef);
      return { refs, ...(body.has_more ? { next: encodeCursor(page + 1) } : {}) };
    },

    async fetchImage(url: string, _size: ImageSize): Promise<FetchedImage> {
      let parsed: URL;
      try {
        parsed = new URL(url);
      } catch {
        throw new RefusedError(`"${url}" is not a URL`);
      }
      // Only this Source's own CDN, over HTTPS. Anything else is refused before a request is made.
      if (parsed.protocol !== 'https:' || parsed.hostname !== CDN_HOST) {
        throw new RefusedError(`${url} is not an https ${CDN_HOST} URL. Only this source's CDN is allowed.`);
      }
      // A real adapter maps `_size` onto the CDN's renditions and falls back to the nearest one.
      const res = await send(parsed.href);
      const type = (res.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase();
      if (!type.startsWith('image/')) {
        throw new RefusedError(`${url} answered with ${type || 'no content type'}, not an image`);
      }
      const bytes = new Uint8Array(await res.arrayBuffer());
      if (bytes.byteLength > IMAGE_LIMIT) throw new RefusedError(`${url} is over the 30 MB limit`);
      return { bytes, mimeType: type, url: parsed.href };
    },
  };
}

Notes on the skeleton:

  • createExampleSource takes a transport. That is the test seam. The default is fetch.
  • send turns a failed connection into NetworkError and an HTTP error into SourceError.
  • It uses the Transport directly. A real adapter also needs a time limit on every request and a size cap on every body. Pinterest does this in createHttp in src/sources/pinterest/transport.ts. That helper is not shared between adapters yet.
  • fetchImage ignores _size. A real one maps it to renditions.
  • Export the factory and its option types from the adapter's index.ts.

Tests

Write the test first. Run it and see an assertion fail. If the test imports a symbol that does not exist yet, add the export as a stub (it throws, or returns a wrong value) so the test loads and fails on an assertion, not on a missing module.

Test the Source at its public seam, with a fake Transport, the way test/pinterest/ does:

  • A fake Transport is a function (url, init) => Promise<Response>. It records the URLs it was asked for, so a test can assert that a refused host caused no request. See cdn() in test/pinterest/image.test.ts and fake() in test/pinterest/failover.test.ts.
  • Real responses go in test/fixtures/<id>/, trimmed, with nothing personal in them. test/pinterest/helpers.ts has a fixture() loader and small builders (json, img).
  • Anything written to disk goes in a temporary folder (see tmpFile in the same helpers).
  • Use it.each for lists of refused inputs.

What to cover:

  1. capabilities() reports exactly what works, and the omitted methods are absent.
  2. search returns Refs with the fields you map, and a next cursor.
  3. The cursor fetches the next page, and a cursor that is not yours is refused with no request.
  4. Each optional method you implement, including a final: true refusal for your own non-ref pages.
  5. An HTTP error becomes SourceError with its status. A thrown transport becomes NetworkError.
  6. fetchImage refuses a plain-http URL, another host and a lookalike host, with no request. It accepts your CDN and returns the bytes.

A test file for the skeleton:

import { describe, expect, it } from 'vitest';
import { NetworkError, RefusedError, SourceError } from '../../src/core/errors.js';
import type { Transport } from '../../src/core/types.js';
import { createExampleSource } from '../../src/sources/example/index.js';

const item = (id: string) => ({ id, image: `https://img.example.test/${id}.jpg`, width: 1200, height: 1600, title: `Item ${id}` });
const json = (body: unknown, status = 200) =>
  new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });

/** Records every URL and answers with `reply`. */
function fake(reply: (url: string) => Response | Promise<Response>) {
  const asked: string[] = [];
  const transport: Transport = async (url) => {
    asked.push(url);
    return reply(url);
  };
  return { asked, src: createExampleSource({ transport }) };
}

describe('search', () => {
  it('returns Refs and an opaque next cursor, and the cursor fetches page 2', async () => {
    const t = fake((url) => json({ items: [item(url.includes('page=2') ? 'b' : 'a')], has_more: !url.includes('page=2') }));
    const first = await t.src.search('poster', { limit: 1 });
    expect(first.refs.map((r) => r.key)).toEqual(['a']);
    expect(first.next).toBeTypeOf('string');
    const second = await t.src.search('poster', { limit: 1, cursor: first.next });
    expect(second.refs.map((r) => r.key)).toEqual(['b']);
    expect(second.next).toBeUndefined();
    expect(t.asked[1]).toContain('page=2');
  });

  it('refuses a cursor that is not ours', async () => {
    const t = fake(() => json({ items: [] }));
    await expect(t.src.search('poster', { cursor: 'nope' })).rejects.toBeInstanceOf(RefusedError);
    expect(t.asked).toEqual([]);
  });

  it('turns an HTTP error into a SourceError with the status', async () => {
    const t = fake(() => json({}, 503));
    await expect(t.src.search('poster')).rejects.toMatchObject({ name: 'SourceError', status: 503 });
    await expect(t.src.search('poster')).rejects.toBeInstanceOf(SourceError);
  });

  it('turns a transport failure into a NetworkError', async () => {
    const t = fake(() => {
      throw new Error('ECONNREFUSED');
    });
    await expect(t.src.search('poster')).rejects.toBeInstanceOf(NetworkError);
  });
});

describe('capabilities', () => {
  it('reports search only and leaves the other methods out', () => {
    const { src } = fake(() => json({}));
    expect(src.capabilities()).toEqual({ search: true, related: false, collection: false, get: false, visualSearch: false });
    expect('related' in src).toBe(false);
  });
});

describe('fetchImage', () => {
  it.each([
    ['plain http', 'http://img.example.test/a.jpg'],
    ['another host', 'https://evil.test/a.jpg'],
    ['a lookalike host', 'https://img.example.test.evil.test/a.jpg'],
  ])('refuses %s without a request', async (_name, url) => {
    const t = fake(() => new Response(new Uint8Array(4), { headers: { 'content-type': 'image/jpeg' } }));
    await expect(t.src.fetchImage(url, 'thumb')).rejects.toBeInstanceOf(RefusedError);
    expect(t.asked).toEqual([]);
  });

  it('downloads from its own CDN', async () => {
    const t = fake(() => new Response(new Uint8Array(4), { headers: { 'content-type': 'image/jpeg' } }));
    const img = await t.src.fetchImage('https://img.example.test/a.jpg', 'thumb');
    expect(img.mimeType).toBe('image/jpeg');
    expect(img.bytes.byteLength).toBe(4);
  });
});

Run only your file while you work:

npx vitest run test/example

Then add a live test in test/live/<id>.test.ts and run it by hand with npm run test:live. It is not part of npm test or CI.

Register the Source

The server is wired in one place, the composition root, src/server/index.ts. Add your factory to sources:

import { createExampleSource } from '../sources/example/index.js';

const server = createBotticelliServer({
  sources: [createPinterestSource(), createExampleSource()],
  // …
});

Nothing else in src/server/ names a Source. It only sees Sources (ADR 0001). The order of the array matters in two places:

  • search goes to every Source whose search Capability is true, unless the call lists sources.
  • related and get given a Handle go to the Source of that Ref. Given any other input (a URL or an id), they go to the first Source in the array that has the Capability. collection always goes to the first Source that has it, and look, save and palette resolve a URL or id through the first Source that has get.

If the new Source must take inputs the first one also accepts, discuss the routing in the issue before you code it.

Documentation to update

In the same pull request:

File Change
Sources A section for the Source: Capability table, accepted inputs, limits, hosts. A row in the capability matrix
CONTEXT.md Add the Source to the Source row
Glossary The same, in the Source entry
Architecture The module map, if the Source is built
Configuration A line for each new environment variable
Privacy and terms Every new host the code talks to, and what is sent
CONTRIBUTING.md The Source id in the commit scope table. This is part of the pull request
SECURITY.md The allowed hosts, if the SSRF scope lists them
CHANGELOG.md An entry under ## [Unreleased]
Roadmap The milestone status

A built feature says built (Mx). Planned work says planned. Describe as working only what exists in src/.

Checklist

  • An issue names the Capabilities. An ADR exists if the Source decides something.
  • A test failed first. npm run typecheck, npm run lint and npm test pass.
  • capabilities() matches the methods that exist.
  • fetchImage refuses every host that is not the Source's own, before a request.
  • Cursors are opaque and validated.
  • Your own non-ref pages are refused with { final: true }.
  • No secret in a message, a log, a fixture or the diff.
  • No native dependency.
  • The pipeline, Library and server work with the Source without a change.
  • The docs in the table above are updated.

Troubleshooting / FAQ

Can I skip related? Yes. Leave the method out and report related: false. The tool answers with an error that names the Source and the Capability.

My Source needs a login for one method. Report false while there is no session. Throw CapabilityError with the reason if the method is still on the object. Login is opt-in and the secret never goes through a chat (ADR 0004).

The server says visualSearch is not available. No MCP tool calls visualSearch yet (visual_search is planned, M5). Implement it only when the tool exists.

Where do I put code two adapters share? There is no shared adapter helper yet. Open an issue before you import from another adapter's folder.

Where is a worked adapter? src/sources/pinterest/. Start with pinterest.ts (the Source), transport.ts (timeouts and retries), extract.ts (turning JSON into Refs) and the tests in test/pinterest/.

Clone this wiki locally