# Connectors (https://docs.neuralisapp.com/package-system/connectors)

A source connector contributes a new **source kind** to the URI-addressed
filesystem. Once registered, admins can create sources of that kind, and the
platform's filesystem tools, sync runners, and UI route through the connector
transparently — the URI is the unit of authorization, not the connector kind.
The runtime contract is `ConnectorPort`, versioned as
`CONNECTOR_PORT_VERSION = 4` and bumped on any breaking change. Version 4 adds
`isRuntimeActive?()` and the factory's `projectId` and `packageState()`, so a
runtime-gated connector answers its enabled state per binding without starting
its runtime.

## The capability set [#the-capability-set]

Capabilities form a closed list. `list` and `read` are mandatory; every other
capability gates an optional method on the port:

| Capability | Method | Purpose |
| --- | --- | --- |
| `list` | `list(uri)` | Directory listing (required) |
| `read` | `read(uri)` | File content (required) |
| `rawRead` | `readRaw(uri, { maxBytes })` | The original bytes as `{ bytes, size, mimeType }`. Cap = the smaller of `maxBytes` and the connector's ceiling, enforced before buffering; a larger (or growing) file throws `ConnectorRawReadTooLarge`, never a prefix. Undeclared, it is refused, not approximated |
| `stat` | `stat(uri)` | Existence plus `isDirectory`, `size?`, `modifiedAt?`, **no content**. `null` when the store was reached and the artifact is absent; otherwise THROWS with `read`'s errors, so "gone" differs from "could not ask" |
| `write` | `write(uri, content, mimeType?)` | Create/overwrite — accepts `string` or `Uint8Array` |
| `delete` | `delete(uri)` | Remove a file |
| `move` | `move(fromUri, toUri)` | Rename/move |
| `mkdir` | `mkdir(uri)` | Create an empty directory (recursive, `mkdir -p` semantics); a no-op when it already exists |
| `rmdir` | `rmdir(uri)` | Remove an **empty** directory. A recursive delete is orchestrated one level up (files, then empty shells bottom-up) |
| `exec` | `exec(request, { session, signal? })` | Run a command in the source |
| `execDetached` | the `detached` facet — `start`, `status`, `output`, `kill`, `release` | Run a command that OUTLIVES the call. Requires `exec`, and all five verbs are required |
| `scanDelta` | `scanDelta(request)` | Changed files since a checkpoint, for sync. Honour `request.signal` at batch boundaries; prune `request.excludeGlobs` **during the walk**, so `node_modules` does not spend the scan cap. `request.includeInventory` asks for the same scan's complete file set as `inventory` (optional; else the caller scans twice): `files` ⊆ `inventory`, one `checkpoint` for both |
| `walk` | `walk(rootUri, opts?)` | Recursive enumeration with excludes |
| `count` / `peekCount` | `count(rootUri)`, `peekCount(rootUri)` | Async exact count / sync cached estimate |
| `scanContent` | `scanContent(rootUri, query, opts?)` | Content search with match previews |
| `subscribeEvents` | `subscribeEvents(rootUri, listener, opts?)` | Change events (`created`/`modified`/`deleted`/`moved`/`overflow`). `overflow` = delivery is no longer trustworthy, the consumer runs a full reconcile; it may carry a closed `reason` (`watcher_error`, `watcher_exhausted`, `watcher_restarted`, `watcher_capped`) and an errno-name `code`, never free text or a path. `opts.excludeGlobs` keeps trees out of the OS watcher, `opts.maxFolders` caps the folders one watch enters (then one `watcher_capped` overflow; every file in a watched folder still streams); a `deleted` event may carry `entry: 'dir'`, one event for a whole removed folder; the subscription may report `watchState()` — `starting` (the first walk is running), `full`, `partial` or `off` |
| `resolveOsUri` | `resolveOsUri(uri)` | Host-OS absolute path for a URI |

The instance's `capabilities()` set must **exactly** match the manifest's
`capabilities[]`; the loader cross-checks at instantiation and throws
`ConnectorCapabilityMismatch` on any divergence, more or less. `execDetached`
without the `detached` facet, or the facet without the capability, is the same
error.

**Detached runs.** `detached.start(request, context)` is a second exec ENTRY:
it runs under the caller's session, and the platform enforces the kind's entry
feature(s) exactly as on `exec`. The other four verbs are identity-free
transport keyed on the returned run id — `status(runId, waitMs?)` (bounded long
poll allowed), `output(runId, since)`, `kill(runId, actor?)`, `release(runId)` —
so a caller who has since lost the entry feature can still read and stop a run
they own (ownership is the platform's stored record). `actor` is for your audit
row, never a gate. A `kill` is an acknowledgement; report the real end through
`status`.

Three contract obligations deserve emphasis:

- **Binary reads.** `ConnectorReadResult.bytes` is optional base64, emitted for
  `image/*`, `video/*` and `application/pdf` within the connector's per-MIME
  inline cap. Over it, leave `bytes` unset and return a short text marker.
  Whether bytes reach the model is gated downstream on the model's image/video
  capability — connectors never peek at the runtime.
- **`resolveOsUri` never fabricates.** A host-backed store returns the real
  host path. One with no host path picks one honest answer: throw
  `OsUriUnresolvableError` (the UI and vector store propagate it, no stale
  fallback), or, for a sandbox with its own absolute paths, return that internal
  path — as container-backed desktop sources do; the host/container translators
  only re-map host-anchored kinds. Never invent a plausible-looking host path.
- **Containment is the connector's own job — nothing checks it.** Map a
  relative path onto a root through the real filesystem, never `path.resolve` +
  `startsWith`: a symlink planted inside the root serves whatever it points at.
  From `@neuralis/package-system/paths`: `resolveContained` checks lexically,
  then `realpath`s both sides, answering a fixed error code, never a path;
  `openContainedHandle` reads through the descriptor it opened, so check and use
  are one open; `listContained` is a `readdir` on the resolved path with no such
  guarantee.

### Optional liveness probe [#optional-liveness-probe]

`probeConnection?(): Promise<{ connected, reason? }>` is an optional
non-capability health method. When present, a disconnected source is dimmed in
the UI and marked offline in the agent's runtime view — never blocking
already-synced content. `reason` is a fixed enum (`runtime_offline`, `fs_unreachable`, `fs_permission`, `store_unreachable`, `broker_outdated`, `devices_disabled`, `device_not_ready`)
(never a raw path). Only `device_not_ready` may add `notReady`, the device's
fixed readiness codes (`ceiling_missing_or_empty`, `sandbox_helper_missing`, `socket_isolation_failed`,
`secret_file_missing_or_too_short`, `scratch_root_missing`). Keep it cheap: a
network-backed connector returns a cached reachability flag.

## Error taxonomy [#error-taxonomy]

Throw the typed errors from `@neuralis/package-system/contracts`; tools and the
admin UI depend on the taxonomy, not message strings:

| Error | Meaning |
| --- | --- |
| `ConnectorNotFoundError` | No connector registered for the kind |
| `ConnectorOrphanError` | A source config references a kind whose package is gone — admin sees a "remove source" call to action |
| `ConnectorCapabilityMissing` | Caller used a capability the connector does not advertise |
| `ConnectorRuntimeError` | Wraps a connector-thrown exception with source + operation context |
| `ConnectorRootAccessError` | Abstract base for `ROOT_MISSING` / `ROOT_PERMISSION_DENIED` on the source root — surfaced as a structured warning instead of an empty folder |
| `ConnectorTrustRejected` | An untrusted package tried to contribute a source connector |
| `ConnectorCapabilityMismatch` | Declared vs. runtime capability sets differ |
| `ConnectorRawReadTooLarge` | `readRaw` refused a file over the effective cap (`code: 'raw_read_too_large'`, the binding `limit`, and `planeLimit` when the connector's own ceiling was the one that applied) |

## Registering a source kind [#registering-a-source-kind]

A connector ships as a `connectors[]` entry with `type: "source"` in the
manifest, plus a factory in the package's compiled code:

```json
{
  "id": "my-notion",
  "type": "source",
  "kind": "notion",
  "transport": "in-process",
  "name": "Notion Workspace",
  "category": "api",
  "configSchema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "workspaceId": { "type": "string", "minLength": 1 },
      "apiKey": { "type": "string", "minLength": 1 }
    },
    "required": ["workspaceId", "apiKey"]
  },
  "capabilities": ["list", "read", "write", "walk", "scanContent"],
  "defaultPermissions": { "default": { "read": true, "write": true, "exec": false } },
  "defaultScope": "project",
  "scopeSelectable": true,
  "allowedScopes": ["project", "user", "agent"],
  "connectorFactory": "./dist/connectors/NotionConnector.js#createNotionConnector"
}
```

- **`configSchema`** is a JSON Schema the admin form renders and the registry
  validates configs against. The checker is a **hand-rolled subset** (object
  properties, `required`, types, enum, basic string/number constraints); other
  keywords are ignored. **Omit `additionalProperties: false` and unknown keys
  are accepted silently** — a typo reaches your factory as a missing field.
  Declare it explicitly.
- **Secrets do not live in `configSchema`.** Declare an API key **once** in
  `neuralis.credentials[]` and resolve it at runtime through the
  `CredentialResolver` injected into `init(ctx)` —
  `ctx.credentials.resolveCredential(id, { projectId })`; the factory closes
  over that port. See [Credentials](https://docs.neuralisapp.com/package-system/credentials.md).
- **`connectorFactory`** is a `modulePath#exportName` reference: the MODULE is
  imported once when the kind registers, the FACTORY called once per source
  binding. An installed package's entry added later appears after the
  deployment's package-swap loop; a project `_packages/` drop re-loads on scan
  and rescan.
- **`defaultScope` / `scopeSelectable` / `allowedScopes`** choose project-,
  user- or agent-owned sources; `allowedScopes` must include the default, and
  project scope is forced when selection is disabled.
- **`defaultPermissions`** seeds the source's permission tree — the same
  hierarchical shape evaluated by [URI policies](https://docs.neuralisapp.com/package-system/uri-policies.md).
- **`runtimeGated`** (default `false`) marks a connector whose runtime can be
  stopped, such as a container-backed desktop. The platform reads the
  connector's `isRuntimeActive()` and dims its file-tree row while it is down,
  **without** hiding synced files — a visual signal, never an access gate.
  Always-on connectors (local disk, the vector index) omit it.
- **`category`** (optional, declared, never derived) groups the kind in the UI
  — `disk`, `vector`, `machine`, `api`, `db` — and picks its chip icon and
  colour; an unrecognised value renders a generic chip.

Native and trusted packages may contribute source connectors with any
capability; an **untrusted** one is rejected at validation and again at
registration.

## Offering an MCP server [#offering-an-mcp-server]

A `connectors[]` entry with `type: "mcp"` takes one of three forms. A **remote**
server names `transport: "streamable-http"` and a `url`; both are required.
`transport: "stdio"` with a `command` is the managed-sidecar form — the command
runs only in an isolated sidecar container, never in the host, and needs a
trusted or native package. `transport: "in-process"` advertises the package's
own hosted tools (below).

### A remote server is offered, never auto-connected [#a-remote-server-is-offered-never-auto-connected]

```json
{
  "id": "acme",
  "type": "mcp",
  "transport": "streamable-http",
  "url": "https://mcp.acme.example/mcp",
  "name": "Acme",
  "description": "Orders and invoices",
  "icon": "Cloud",
  "auth": { "type": "oauth2", "scopes": ["read"] }
}
```

The platform never connects a package-declared remote server on its own. It
appears as **Offered by &lt;package&gt;** in the agent's Connections → MCP servers
panel — and in the `connect` tool's MCP list — for every caller who can see the
package: holding its base-access feature, with the package switched on for that
agent. **Add** turns the offer into that agent's own MCP server and starts the
server's sign-in: the standard MCP authorization flow (protected-resource and
authorization-server discovery from the `url`, dynamic client registration,
PKCE, token refresh). No MCP request reaches the server before the user
consents (the sign-in itself reads the server's OAuth metadata and registers a
client, as Authorize does), and no Neuralis identity header is ever sent. Only `url`, `name`, `description`,
`icon` and `auth.scopes` are read; `auth.type` is `oauth2`, `oauth2-pkce` or
`none`, and any other type is not offered. An added server belongs to the user:
switching the package off later does not remove it, and the "offered by" label
is provenance, never a permission.

### An in-process connector advertises the package's own tools [#an-in-process-connector-advertises-the-packages-own-tools]

`transport: "in-process"` is **inbound**: the package advertises **its own
hosted tools** as one discoverable connector, served by the platform's MCP host,
so it needs **neither a `url` nor a `command`**.

```json
{
  "id": "git",
  "type": "mcp",
  "transport": "in-process",
  "name": "Git",
  "icon": "GitBranch",
  "category": "mcp",
  "requiredScopes": ["project"]
}
```

It never enters the outbound connector store and is never auto-connected (no
phantom "connected" server). It appears in the agent's `<packages>` overview,
and its tools pass the same hosted-tools boundary as the package's others.
Being in-host execution, it needs a **trusted** or native package, like `stdio`
and sidecar transports; an untrusted one is rejected at validation.

`defaultToolFilter` (`{ include?, exclude? }`) and `requiredScopes` (`local`,
`project`, `user`, `app`, `managed`) are **advisory metadata** and gate nothing:
the real gates are the package's MCP-hosting setting, each tool's
`requires.features` and the source URI policy.

## Declaring sources [#declaring-sources]

Registering a connector adds a source **kind**; it creates no source. Concrete
instances of a kind are declared in `sources[]` — see
[Sources](https://docs.neuralisapp.com/package-system/sources.md).

## Implementing the port [#implementing-the-port]

Pin the supported version as a literal — importing the host's constant would
relabel an old binary as current after an upgrade. v1 execution signatures are
rejected without an adapter; a version check alone cannot prove an external
binary enforces authorization.

Optional `exec` receives `{ command, cwd, timeout?, env?, background? }` and a
separate `{ session: SessionContext, signal? }`. `cwd` is the exact source URI.
The provider resolves its path and enforces its lifecycle and options; identity
never comes from tool input. Return `exitCode`, `stdout`, `stderr`, `truncated`,
`durationMs`, plus optional bounded display `text`.

**A connector never implements the entry check.** Declaring the `exec` capability
requires declaring `execRequires` beside it — a non-empty list of feature ids
that open a shell on this kind:

```json
"capabilities": ["list", "read", "exec"],
"execRequires": ["machine.control"]
```

An empty list is a manifest error (an always-open door). The loader stamps a
frozen copy of the ids on the binding record and wraps `exec` to check each one
before your code runs; the consuming tool then evaluates the source's path
policy on the `cwd`. Your provider gets the call only after both.

The loader snapshots provider id/trust, kind, source, project root, scope and
the entry ids before awaiting the factory, and stamps only a checked instance;
`getConnectorBindingProvenance` exposes that immutable record for execution
callers to compare with current authority. Reusing an instance for another
binding is refused. Exec factories require an absolute `projectRoot`;
filesystem-only ones may omit it. Filesystem methods keep their service-layer
URI-policy checks.

```ts
import {
  type ConnectorPortVersion,
  type ConnectorPort,
  type ConnectorFactoryContext,
} from '@neuralis/package-system/contracts';

class NotionConnector implements ConnectorPort {
  readonly kind = 'notion';
  readonly source: string;
  readonly portVersion = 4 satisfies ConnectorPortVersion;

  constructor(private readonly ctx: ConnectorFactoryContext) {
    this.source = ctx.source; // never assume a fixed scheme
  }
  capabilities() {
    return new Set(['list', 'read', 'write', 'walk', 'scanContent'] as const);
  }
  async list(uri: string) { /* ... */ }
  async read(uri: string) { /* ... */ }
  async write(uri: string, content: string | Uint8Array) { /* ... */ }
}

export function createNotionConnector(ctx: ConnectorFactoryContext): ConnectorPort {
  return new NotionConnector(ctx);
}
```

The factory context carries exactly eight members: `packageId`, `packageRoot`,
the bound `source` slug, the validated `config`, the `projectId`, the optional
`projectRoot`, the persisted ownership `scope`, and `packageState()` — the
declaring package's `init` state, read lazily (it throws before `init`
finishes). There is deliberately **no** credentials map (see above). Source
slugs are URI schemes and may get scoped user/agent variants — read
`ctx.source`, never hard-code a scheme.

## Registries [#registries]

Two registries with deliberately separate lifecycles back the system:

- **`ConnectorRegistry`** holds runtime instances — one per kind plus
  per-source bindings (`resolve(kind)`, `resolveBySource(source)`);
  unregistering a kind clears its bindings.
- **`SourceKindRegistry`** holds the metadata (label, schema, capabilities,
  defaults, factory) for discovery, admin forms and config validation, so an
  orphan source (metadata gone, config on disk) differs from a runtime failure.

The compliance harness in `@neuralis/package-system/testing` exercises every
declared capability and the declared-versus-actual match. See
[Testing](https://docs.neuralisapp.com/package-system/testing.md).