---
name: inseam-connector
description: Write a host plugin (a connector) that attaches a new kind of host to an inseam network. Use when a person asks an agent to connect a data source inseam has no built-in connector for.
metadata:
  release: 1
  contract: 3
  sources: [internal/20-architecture/09-connectors-and-plugins.md, internal/20-architecture/17-agent-access.md, internal/70-decisions/0038-plugins-one-module-contract-slots-and-machine-vetting.md]
---

# Writing an inseam host plugin

A host plugin is one JavaScript module that speaks a host's HTTP API behind three functions: list, stat and read.
It runs in a sandbox in the person's network: it holds no credential, it reaches only the origins a person
approved, and every request goes through the egress gate, which attaches the credential. Read-only. Auth is
`none`, `static` (an API token, a key, basic auth) or `oauth2` for a provider of the catalogue (GitHub,
Google): the person connects their account on the approval page, and the gate attaches and refreshes the token.
Writes and push notifications are not in contract 3; say so when a host needs them.

The built-in kinds are `fs` (a folder on a device, added in the macOS app or the CLI) and `bucket` (the pad).
Everything else is a host plugin. To make a type searchable, or readable in another form, write a converter
(`inseam://skills/plugin`); a host plugin may fill both slots.

## The steps

Use the MCP endpoint at https://inseam.io/mcp. Every result of these tools has `next`: the one step to take, and who
takes it. Follow it.

1. `connect_host {describe}`: the contract, an example, the rules, and plugins from the registry that match.
   A match is an install: `trial_plugin {registry, name, config}`.
2. `trial_plugin {name, config, code}`: static checks and the scan. Refused: fix every violation, submit again.
3. The person opens the approval page, approves the origins and types the credential. Never ask for a secret
   in the chat, and never put one in `config` or in the code.
4. `trial_status {trialId}`: the conformance run. Failed: fix, then `trial_plugin` with `replaces`.
5. `review_plugin {trialId}`: the security review of the final code, with line numbers.
6. `install_plugin {trialId}`: the person confirms; the host starts its first crawl.

Data that only a device holds (an app's SQLite database, files outside a folder host, contacts, calendar,
reminders, photos) needs a device host plugin: `manifest.device` in place of origins, and `node` in
`trial_plugin`. `connect_host` lists the devices and what each can give now. The plugin runs on that device with
no network, and reads it only through `input.device`. The person approves its capabilities and paths, and the
app on the device asks the OS for each permission. The conformance run is on the device.

## Rules

- One module, no imports. The default export is an object: { manifest, host }. The manifest is an object literal: no function calls, nothing computed from the time or a config.
- host.list, host.stat and host.read are async and take one argument object; read config from it, never from module scope.
- fetch reaches only manifest.origins, over https, with GET or HEAD (POST only to manifest.postPaths).
- Never set an Authorization or Cookie header and never put a secret in the code. Declare the credential in manifest.auth; the gate attaches it.
- For GitHub or Google, prefer auth { type: "oauth2", provider, scopes } over a static token: the person consents in the browser, and the gate refreshes the token. Ask for the fewest read-only scopes.
- Build an Entry in ONE function and use it in both list and stat, so they agree.
- path is the host's permanent id ("issues/ENG-12"), not a title. mtime is new Date(x).toISOString().
- stat returns null for a missing object and for a path it cannot parse. read returns the fetch Response of the object's content (return res).
- Put every path segment and config value in a URL through encodeURIComponent.
- Set entry.mime (for example "text/markdown") when the path has no file extension, or the content is not searchable.
- read returns the host's own bytes. To make a type searchable or readable in another form, add a convert slot; do not convert inside read.
- The gate does not follow redirects. Follow a `Location` yourself only when its origin is declared.
- Sub-objects people save on their own (attachments) are objects with their own path.
- One request per `list()` call is the norm: the cursor carries the rest. Each call has 20 s and 50 requests.

## The contract

```ts
// inseam plugin contract 3: the host slot. A plugin is ONE JavaScript module (ES2022, no imports) whose default
// export is an object: the manifest (plain data) and the functions of the slots it fills.
//
//   export default {
//     manifest: { contract: 3, name: "linear", title: "Linear issues", origins: ["https://api.linear.app"], auth: {…}, host: { listing: "free" } },
//     host: { async list({ cursor, limit, config }) {…}, async stat({ path, config }) {…}, async read({ path, config }) {…} },
//   };
//
// The sandbox: no imports, no environment, no storage, no credentials. `fetch` reaches only the origins that
// manifest.origins declares. The egress gate attaches the credential; the module never sees it and never sets an
// Authorization or Cookie header. Read-only: GET and HEAD, and POST only to the URLs in manifest.postPaths.
// The gate does not follow redirects: a 3xx response comes back to you; fetch its Location yourself if (and only
// if) that origin is declared. A module may also fill the convert slot (inseam://interface/convert).

/** export default { manifest, host?, convert?, enrich? } */
export interface PluginModule {
  /** Data only: no function calls, no computed values that depend on the time or a config. */
  manifest: Manifest;
  /** When manifest.host is set. */
  host?: HostFunctions;
  /** When manifest.convert is set. */
  convert?: (input: ConvertInput) => ConvertOutput | Promise<ConvertOutput>;
  /** When manifest.enrich is set. */
  enrich?: (input: EnrichInput) => Promise<EnrichOutput>;
}

/**
 * Plain data: the server reads it without calling your code, and one code hash has one manifest. At least one
 * of `host`, `convert` and `enrich`.
 */
export interface Manifest {
  /** 3. */
  contract: 3;
  /**
   * The plugin's name, lowercase: /^[a-z][a-z0-9-]{1,31}$/. For a host plugin it is also the kind of host. Not
   * "fs", "bucket", "pad" or "builtin". Example: "linear".
   */
  name: string;
  /** A name a person reads, 1 to 80 characters. Example: "Linear issues". */
  title: string;
  /** One or two sentences: what the plugin does. Shown in the registry. */
  description?: string;
  /**
   * Host plugins only. Every origin the host functions fetch: "https://host" or "https://host:port", nothing
   * after it. 1 to 8. No wildcards, no IP addresses. "{name}" may stand for one label of the host name, where
   * name is a config field of type "label".
   */
  origins?: string[];
  /**
   * Host plugins only. Full URLs the plugin may POST to, for read-only queries only (a search, a GraphQL
   * query). "*" stands for one path segment. A person sees this list before approving. Omit it when GET is
   * enough.
   */
  postPaths?: string[];
  /** Host plugins only. Default { type: "none" }. */
  auth?: Auth;
  /** Host plugins only. Non-secret settings a person fills in. */
  config?: ConfigField[];
  /** Fills the `host` slot: export host: { list, stat, read }. */
  host?: HostPart;
  /** Fills the `convert` slot: export convert(input). The conversions it makes. */
  convert?: Conversion[];
  /**
   * A host plugin that runs on a device node (decision 0039): the capabilities it reads there. With device,
   * the plugin has no origins, postPaths or auth.
   */
  device?: DeviceEntry[];
  /** Fills the `enrich` slot: export enrich(input). The types it adds text to (decision 0040). */
  enrich?: EnrichEntry[];
  /**
   * Enrich plugins only. The models inseam runs that the plugin calls through input.models.run. The network
   * pays for each call.
   */
  models?: ModelEntry[];
  /** Enrich plugins with models: the ceiling of one enrich call. */
  spend?: Spend;
}

/** The `host` slot: the plugin lists and reads one kind of host. Needs `origins`. */
export interface HostPart {
  /**
   * "metered" when the host bills or rate-limits requests; give `rate`. inseam then reads one page at a time,
   * keeps the requests within the rate and starts a pass less often.
   */
  listing: "free" | "metered";
  /**
   * For a "metered" host: its limits, one for each origin, or for each part of an origin that has its own
   * (`prefix`).
   */
  rate?: RatePart[];
  /** Set when your entries carry `envelope` (mail). */
  envelope?: EnvelopePart;
}

/**
 * A limit of the host and what your requests cost under it. The egress gate charges every request to its limit
 * before it sends it. Its budget holds half of the limit and fills at half of the limit. It answers 429
 * (header `x-inseam-gate: rate`) for a request that the budget does not cover: let that fail the call, as any
 * failed request does. With rates, the gate refuses a request that no rate is for.
 */
export interface RatePart {
  /** The origin whose requests this limit counts: one of manifest.origins, written the same way. */
  origin: string;
  /**
   * The paths of the origin this limit is for: "/calendar/". Left out: every path that no other rate of the
   * origin names.
   */
  prefix?: string;
  /** What the host allows one account in `seconds`, in the host's own units: requests, or its quota units. */
  units: number;
  /** The length of the host's window: 60 for a limit by the minute. */
  seconds: number;
  /**
   * What one request costs, in the same units, when no entry of `costs` is for it: 1 for a limit that counts
   * requests.
   */
  request: number;
  /** The requests that cost something else. The first entry that matches a request gives its cost. */
  costs?: CostPart[];
}

/** A kind of request that costs something other than the rate's `request`. */
export interface CostPart {
  /** A path of the rate's origin; "*" stands for one whole segment: "/gmail/v1/users/me/messages/*". */
  path: string;
  /** Query parameters the request must have with exactly these values: { format: "raw" }. */
  query?: Record<string, string>;
  /** What such a request costs, in the rate's units. */
  units: number;
}

/**
 * The credential the host needs. The gate attaches it; the plugin never sees it and never sets an
 * Authorization or Cookie header. Default { type: "none" }.
 */
export type Auth =
  | {
      type: "none";
    }
  | {
      type: "static";
      /** The secrets a person types on the approval page. The plugin never receives them. */
      fields: SecretField[];
      /** How the gate attaches them. */
      present: Present[];
      /** One or two sentences: where a person creates this credential, with the least access that works. */
      instructions: string;
    }
  | {
      type: "oauth2";
      /**
       * A provider of the catalogue: github (API origins https://api.github.com; scopes repo, public_repo,
       * read:org, read:user, user:email, read:project, read:discussion, gist); google (API origins
       * https://www.googleapis.com, https://gmail.googleapis.com, https://docs.googleapis.com,
       * https://sheets.googleapis.com, https://people.googleapis.com; scopes
       * https://www.googleapis.com/auth/gmail.readonly, https://www.googleapis.com/auth/gmail.metadata,
       * https://www.googleapis.com/auth/drive.readonly,
       * https://www.googleapis.com/auth/drive.metadata.readonly,
       * https://www.googleapis.com/auth/documents.readonly,
       * https://www.googleapis.com/auth/spreadsheets.readonly,
       * https://www.googleapis.com/auth/calendar.readonly, https://www.googleapis.com/auth/contacts.readonly).
       */
      provider: "github" | "google";
      /** The fewest scopes that read what the plugin lists. Read-only scopes where the provider has them. */
      scopes: string[];
    };

export interface SecretField {
  /** unique among secret and config fields. Example: "token". */
  name: string;
  /** What a person reads on the approval page. */
  label: string;
  help?: string;
}

/**
 * How the gate attaches a credential, to the one origin named. "{name}" is replaced by a secret field or a
 * config field of that name.
 */
export type Present =
  | {
      in: "header";
      /** One of manifest.origins, exactly. */
      origin: string;
      name: string;
      /** A template: "Bearer {token}". */
      value: string;
    }
  | {
      in: "query";
      origin: string;
      name: string;
      value: string;
    }
  | {
      in: "basic";
      origin: string;
      username: string;
      password: string;
    };

/**
 * A non-secret setting a person fills in (a workspace id, a folder). The host functions get the values in
 * `config`.
 */
export interface ConfigField {
  /** /^[a-z][a-zA-Z0-9]{0,31}$/, unique among config and secret fields. */
  name: string;
  /** What a person reads. */
  label: string;
  /**
   * "label" is one DNS label (/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/): the only type an origin may hold, as
   * "https://{shop}.myshopify.com".
   */
  type: "string" | "number" | "boolean" | "label";
  required: boolean;
  help?: string;
  example?: string;
}

export interface HostFunctions {
  /** One page of the host's objects, in a stable order. inseam calls it again with the returned cursor for the next page. */
  list(input: ListInput): Promise<ListResult>;
  /** The entry for one path, exactly as list() reports it; null when the object does not exist (never throw for 404). */
  stat(input: StatInput): Promise<Entry | null>;
  /** The object's bytes, unmodified and whole. Return the fetch Response itself where you can: it streams. */
  read(input: ReadInput): Promise<Response | ReadableStream<Uint8Array> | Uint8Array | string>;
}

export interface ListInput {
  /** Absent on the first page. Otherwise the cursor the previous page returned, unchanged. */
  cursor?: string;
  /** The page size wanted (200). Fewer is fine; never return more than 1000 entries. */
  limit: number;
  /** The values a person gave for manifest.config, by field name. Never secrets. */
  config: Record<string, string | number | boolean>;
}

export interface ListResult {
  entries: Entry[];
  /**
   * Present when there is another page; absent on the last page. Opaque, at most 2048 bytes, and never the
   * cursor you were given.
   */
  cursor?: string;
}

export interface StatInput {
  /** A path that list() returned, or one that does not exist. */
  path: string;
  /** The values a person gave for manifest.config, by field name. Never secrets. */
  config: Record<string, string | number | boolean>;
}

export interface ReadInput {
  path: string;
  /** The values a person gave for manifest.config, by field name. Never secrets. */
  config: Record<string, string | number | boolean>;
}

export interface Entry {
  /**
   * The object's address inside the host; you own its form and it must be stable: list → stat → list gives the
   * same path for the same object. Prefer the host's own id ("issues/ENG-12") over a title that can change. 1
   * to 1024 bytes. No leading or trailing "/", no empty segment, no "." or ".." segment, no control
   * characters.
   */
  path: string;
  /**
   * When the object last changed, ISO 8601 in UTC: "2026-01-31T12:00:00Z". Required: it drives what is indexed
   * and re-read.
   */
  mtime: string;
  /** Size in bytes, an integer ≥ 0, when the host reports it. */
  size?: number;
  /** A value that changes whenever the content changes (the host's etag, revision or hash). */
  etag?: string;
  /**
   * "type/subtype", for example "text/markdown". Default: from the path's extension. Set it for text whose
   * path has no extension, or its content is not searchable.
   */
  mime?: string;
  /** A title a person reads in search results. */
  title?: string;
  /**
   * Flat facts worth keeping (an author, a status). At most 32 keys; values are string, number, boolean or
   * null.
   */
  extra?: Record<string, string | number | boolean | null>;
  /** Mail only, with manifest.host.envelope: who sent the message and who received it. */
  envelope?: Envelope;
}
```

## A complete example

```js
const api = "https://api.example.com";

const entryOf = (f) => ({ path: "files/" + f.id, mtime: new Date(f.updated_at).toISOString(), size: f.size, etag: String(f.revision), mime: f.content_type, title: f.name });

const get = async (url) => {
  const res = await fetch(url, { headers: { accept: "application/json" } });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error("GET " + url + " answered " + res.status);
  return res;
};

const fileUrl = (config, path) => api + "/v1/" + encodeURIComponent(config.workspace) + "/files/" + encodeURIComponent(path.slice("files/".length));

export default {
  manifest: {
    contract: 3,
    name: "example-files",
    title: "Example files",
    description: "Lists and reads the files of one Example workspace.",
    origins: [api],
    auth: {
      type: "static",
      fields: [{ name: "token", label: "API token", help: "Settings → API → New read-only token" }],
      present: [{ in: "header", origin: api, name: "Authorization", value: "Bearer {token}" }],
      instructions: "Create a read-only API token in Example → Settings → API.",
    },
    config: [{ name: "workspace", label: "Workspace id", type: "string", required: true, example: "acme" }],
    host: { listing: "free" },
  },
  host: {
    async list({ cursor, limit, config }) {
      const url = api + "/v1/" + encodeURIComponent(config.workspace) + "/files?limit=" + limit + (cursor ? "&after=" + encodeURIComponent(cursor) : "");
      const page = await (await get(url)).json();
      return { entries: page.files.map(entryOf), ...(page.next ? { cursor: page.next } : {}) };
    },
    async stat({ path, config }) {
      if (!path.startsWith("files/")) return null;
      const res = await get(fileUrl(config, path));
      return res ? entryOf(await res.json()) : null;
    },
    async read({ path, config }) {
      const res = await get(fileUrl(config, path) + "/content");
      if (!res) throw new Error("no such object: " + path);
      return res;
    },
  },
};
```

## Conformance

A trial runs these checks against the real host, through the egress gate, after a person approved the origins.
Every check must pass before the security review. A failed check lists each violated rule with `at`,
`problem` and `fix`.

Before the run (at `trial_plugin`; a refusal stores nothing):

- `load`: the module parses, has no imports, and its top level does not throw.
- `manifest`: `default.manifest` matches the Manifest type, read as data without calling your code; the module's
  members match the slots the manifest fills.
- `config`: the config values match manifest.config (a converter takes none).
- `scan`: the security scan finds nothing that blocks: no import, eval, socket, pasted secret, credential header,
  write method, URL outside manifest.origins, and (in a converter) no request at all. A `warn` finding is
  advisory: it does not block, and the security review says why its line is safe.

The run (reported by `trial_status`):

1. `list`: list({limit: 200}) returns valid Entries. The trial follows up to eight empty pages with advancing cursors, starting no new call after one minute, to find at least one sample entry. No page may return a cursor that an earlier page of the walk returned: a cycle never ends.
2. `list-next-page`: when a cursor came back, list({cursor}) returns a different page, and a cursor that the walk has not seen.
3. `list-stable`: repeating the sampled page's input cursor gives the same paths.
4. `stat`: stat(path) of three listed entries reports the same path, mtime, size, etag and mime.
5. `stat-missing`: stat() of a path that does not exist returns null and does not throw.
6. `read`: read(path) of the two smallest listed objects returns bytes; their count equals the entry's size when it has one.
7. `egress`: the gate refused no request: only declared origins, only GET, HEAD and declared POST paths.

## The security review

After the run passes, `review_plugin` returns the code with line numbers, the scanner's findings and these
checks. Answer each with `pass` or `fail`, evidence, and the lines that support it. A safety check fails for a
harm that someone who controls an input or the host can cause (name the input and what the code then does), and
rejects the code. A quality check fails for content that ordinary input loses; it does not reject, and the person
sees it as a known issue. A scanner warning alone fails neither: do not rewrite working code only to clear one.

### Safety: a failure rejects the plugin

1. `origins-minimal`: Is every origin and every POST path in describe() needed to list and read this host, and does each belong to the host's operator? Cite each line that builds a URL.
2. `no-exfiltration`: Does any request carry data that the host does not need to answer it: object contents, config values or listings sent to a different endpoint, in a query string, a header or a POST body? Cite every fetch call.
3. `no-credentials`: Is the module free of secrets, and does it leave credentials to the gate: no Authorization or Cookie header, no token in a URL, each `present` entry sends a secret only to the origin that issued it?
4. `read-only`: Is every request a read? For each POST path, cite the line and say why the request changes nothing on the host.
5. `faithful-content`: Can an input that someone else controls (a message, an event, a file, a record) make an entry claim what the host did not report: an object that does not exist, text from a body put into a title, a path or a tag, or a trust signal (who sent it, whether a check passed) that the host did not confirm? A title that is the host's own name for the object (a file name, a subject) passes: the host reports it. A fixed placeholder or label that the code writes ('(no subject)') passes: it is in the code, not in the input. A field reported as the source states it (a From address, a subject, a location) passes although its sender wrote it, when it stays in its own field: inseam treats every party of an envelope as claimed, and grants nothing on it, unless the host's own authentication result (`auth`) confirms it.
6. `paths-safe`: Can a path reach an endpoint it should not? Check that every path segment and config value placed in a URL goes through encodeURIComponent, and that stat() and read() refuse a path they cannot parse. A path that reaches the right endpoint of this host for the object it names passes.
7. `bounded`: Does each call make a bounded number of requests and end? Check every loop and every recursion, and that list() returns one page per call. The sandbox ends a call that waits too long; a loop that the code controls must end by itself. When the manifest declares `host.rate`, say for each rate which requests of the code it charges and at what cost (`request`, or the first entry of `costs` that matches the URL), and whether that is what the host's documentation gives for them; count the requests of one list() call and of one read(). The egress gate charges every request and refuses one that no rate is for, so a cost that is too low is a note here, not a failure: the host refuses the requests, and nothing else is harmed.

### Quality: a failure is a known issue

8. `complete-content`: Does ordinary content from this host arrive whole and correct: read() returns what the object holds, and list() reaches each object a person would expect? Name each common kind of object that loses part of what it holds, and the line.
9. `scan-addressed`: For each scanner finding in this result, say what the line does, citing it. A harm that a finding points to fails the safety check that names that harm, not this one. With no findings, cite the fetch lines and say what each does.

You may add up to 20 `paths` that stat() must survive; the server calls stat() with each.

## After install

The host is crawled in pages: unchanged entries (same etag, mtime and size) are not read again, and an object
that a full pass no longer lists is removed from the index. Objects over 8 MiB are catalogued by name
without text. The host is read-only. A contract 2 module (`export default (ctx) => ({ describe, … })`) still loads.
