---
title: Giving the assistant your data
summary: Collections, actions and MCP servers - the three ways an extension's data becomes assistant tools, with examples and the exact tool shapes.
audience: both
since: protocol 1
---

# Giving the assistant your data

There are three ways, and every extension uses at least one. You declare data, and the host (`apps/desktop/src/lib/tools.ts`) turns it into tools. **An extension never writes tool definitions itself.**

| Use | When | Tools |
|---|---|---|
| [Collections](#collections) | The data is a list of things the extension owns: tasks, notes, contacts | Five per collection, derived by the host |
| [Actions](#actions) | An operation that isn't a plain field edit, or data that isn't in a collection | One per action, implemented by you |
| [MCP servers](#mcp-servers) | A remote service already offers tools over MCP | One per server tool |

## Where data goes

Records go in collections: each collection is a table of its own on the server, the assistant gets tools for it, and the view sees every change live. Settings and small state (connection details, a cursor, the selected item, a draft) go in `host.storage`, which holds values up to 64 KB and which the assistant can't see. Never keep a list of records in a `host.storage` key.

```ts
const { items } = useCollection<Task>("items"); // records: one row each, tools for the assistant
const [selected, setSelected] = useStored<string | null>("selected", null); // small state, up to 64 KB
```

`<ns>` below is the extension's namespace: the last segment of its id, with hyphens turned into underscores (`namespaceOf`). `ai.spacemix.tasks` gives `tasks`; `com.acme.my-crm` gives `my_crm`.

## Collections

If your data is a list of things (tasks, notes, messages, contacts, events), make it a collection. Describe one record with a JSON schema:

```ts
collections: [
  {
    name: "items",
    itemName: "task",
    description: "Cards on the team's task board, each in one column.",
    searchFields: ["title", "notes"],
    schema: {
      type: "object",
      properties: {
        title: { type: "string", description: "What needs doing." },
        done: { type: "boolean", description: "Whether the task is completed.", default: false },
        column: { type: "string", description: "Id of the column it's in, from tasks_columns_list." },
      },
      required: ["title"],
    },
  },
],
```

That declaration gives the assistant up to five tools, named `<ns>_<collection>_<operation>`:

| Tool | Arguments | Returns |
|---|---|---|
| `<ns>_<collection>_list` | `query` (case-insensitive substring over `searchFields`, default every string field), `where` (exact match on the scalar fields: string, number, integer, boolean; array and object fields never match), `limit` (default 20) | `{ total, items }`, newest first by `updatedAt`. `total` counts the matches before `limit`. |
| `<ns>_<collection>_get` | `id` | The record, or `{ error: "No task with id \"…\"." }` |
| `<ns>_<collection>_create` | The schema's fields; `default`s are filled in | The new record |
| `<ns>_<collection>_update` | `id` plus only the fields to change | The updated record |
| `<ns>_<collection>_delete` | `id` | `{ deleted: id }` |

- `operations` limits which tools exist (default: all five). `operations: ["list", "get"]` makes a read-only collection.
- `requireApproval` lists the operations the user confirms before they run (default `["delete"]`).
- `itemName` (and `itemNamePlural`, default `${itemName}s`) words the tool titles and descriptions: "Find tasks", "Create task".
- `list` and `get` count as read-only, so widgets and other read-only consumers may call them.
- The model sees each field's `description` on `create` and `update`, and the collection's `description` on `list` (on `create` when the collection has no `list`); `list`'s `where` shows only the scalar fields' types. A collection without `create` and `update` has its field descriptions listed in the `list` tool's description (in `get`'s without `list`), so keep them short there and point to the action that writes the records for long ones.

Every record also gets `id`, `createdAt` and `updatedAt` (milliseconds since the epoch) from the host. Don't declare them in the schema; `defineExtension` throws if you do.

The full field reference is in [Manifest](../reference/manifest.md#collectiondefinition), and the API in [Collections](../reference/host/collections.md).

### How arguments are checked

Every create and update, from the assistant or from your own code, goes through the host's `validate` (`apps/desktop/src/lib/data.ts`):

- Fields not in the schema are **rejected** with an error that lists the allowed fields. They are not silently dropped.
- Required fields must be present on create. On update every field is optional.
- `null` counts as absent.
- Common model slips are fixed: `"true"`/`"false"` for a boolean, `"3"` for a number or integer, and `"a,b"` for an array.
- `enum` values are enforced. Nested objects are only checked to be objects.

Each write is applied atomically on the server, one record at a time, so the user and the assistant can't overwrite each other's change.

### The view reads the same records

```tsx
import { useCollection } from "@spacemix/sdk/react";

const { items, loaded, create, update, delete: remove } = useCollection<Task>("items");
```

`items` updates live, so a task the assistant creates shows up on the board right away, and the assistant sees whatever the user just dragged. **Don't keep the data somewhere else** (component state, `useStored` under your own key, a separate store). If you do, the assistant can't see it and the two drift apart. See [React hooks](../reference/react.md#usecollection).

In code, `host.collection(name).list()` returns every matching record unless you pass `limit`; the default of 20 belongs to the assistant's tool only.

## Actions

Use an action for an operation that isn't a plain field edit: something that touches several records, talks to the outside world, or reads data that isn't stored in a collection (like files on disk).

Declare it in the manifest:

```ts
actions: [
  {
    name: "move",                       // tool name: tasks_move
    title: "Move task",                 // shown to the user, imperative
    description: "Move a task to the top or bottom of a column.",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "The task's id, from tasks_items_list." },
        column: { type: "string", description: "Id of the destination column, from tasks_columns_list." },
        to: { type: "string", enum: ["top", "bottom"], description: "Where in the column. Defaults to bottom." },
      },
      required: ["id", "column"],
    },
  },
],
```

Then implement it. Whatever the handler returns is the tool result the model sees (a long one as a shortened view; see [Results](writing-for-the-model.md#results)):

```ts
import type { ActionHandler } from "@spacemix/sdk";

interface Column { title: string; position?: number }
interface Task { title: string; column?: string; position?: number }

export const actions: Record<string, ActionHandler> = {
  move: async ({ id, column, to }, host) => {
    const columns = host.collection<Column>("columns");
    if (!(await columns.get(String(column)))) throw new Error(`No column with id "${String(column)}". Use tasks_columns_list to find valid ids.`);
    const tasks = host.collection<Task>("items");
    const others = await tasks.list({ where: { column } });
    const ends = others.map((t) => t.position ?? 0);
    const position = to === "top" ? Math.min(0, ...ends) - 1024 : Math.max(0, ...ends) + 1024;
    return tasks.update(String(id), { column: String(column), position });
  },
};
```

- The handler is `(args, host, ctx) => Promise<unknown>` (`ActionHandler`). `args` arrive already validated against `inputSchema`. `host` is the same object as `import { host } from "@spacemix/sdk"`. `ctx` is an `ActionContext`; see [Writing for the model](writing-for-the-model.md#attribute-to-the-caller).
- Actions run in the extension's frame. The app starts the frame for the call if the view isn't open, so use `host`, not React state. A call that doesn't finish within 60 seconds fails.
- A thrown error goes back to the model as `{ error: message }`.
- A declared action with no handler fails with "… declares "move" but doesn't implement it."
- `requiresApproval: true` makes the user confirm the call before it runs. Set it on anything outward-facing or destructive: sending mail, writing or deleting files, spending money.
- `readOnly: true` says the action changes nothing, here or anywhere else. Read-only actions can feed widgets, which call them on their own without asking. Leave it off when in doubt.
- Return lists as arrays of objects (`{ items: [{ id, name, … }] }`), not text or arrays of arrays. A chat keeps every table of 2 or more objects in a result as a [material](../agents.md#materials), named after your extension and the action's `title`, that the model can query and the person can open, copy and download. A material from a `readOnly` action that doesn't ask can be fetched again with `material_refresh`; any other must be called again.

Data that isn't in a collection still has to reach the assistant, through actions that read it. Files is the example: its data is on disk, so it offers `files_roots`, `files_list`, `files_find` and `files_read`.

Full reference: [Actions](../reference/host/actions.md).

## MCP servers

If the service behind your extension runs an [MCP](https://modelcontextprotocol.io) server over Streamable HTTP, the assistant can use its tools directly. Add `mcp` to the default export, returning the servers to connect to:

```ts
import type { ExtensionModule } from "@spacemix/sdk";

interface Settings { serverUrl: string; apiKey: string }

export default {
  manifest,
  View,
  actions,
  mcp: async (host) => {
    const s = await host.storage.get<Settings>("settings");
    if (!s?.apiKey) return []; // not connected yet: no tools, no error
    return [{ name: "crm", url: `${s.serverUrl}/mcp`, headers: { Authorization: `Bearer ${s.apiKey}` } }];
  },
} satisfies ExtensionModule;
```

- **Needs network permission.** The host only asks extensions that declare a `net:` permission for MCP servers, and each server's host must be allowed by it, the same as for `host.net.fetch`. With `net:*` the user is asked the first time each new host is reached. See [Network](../reference/host/net.md).
- **When:** `mcp` runs when a chat turn starts, so credentials always come from current settings. Return `[]` while the extension isn't connected.
- **Filtering:** `include` keeps only the named tools of a server; `exclude` leaves the named ones out, after `include`.
- **Names:** `<ns>_<tool>`, with anything outside `A-Z a-z 0-9 _ -` replaced by `_`, cut to 64 characters. A collection or action tool with the same name wins: the MCP tool is left out and the user sees a notice. Twenty's `twenty_list` is an action, so a server tool named `list` wouldn't reach the model. A [member's build](../reference/permissions.md#tool-names) comes after every other extension and loses any name clash, MCP tools or not.
- **Approval** (`mcpToolNeedsApproval`): a tool annotated `readOnlyHint: true` runs without asking. `destructiveHint: true`, or `readOnlyHint`/`destructiveHint` set to anything else, asks. With neither hint, a tool runs without asking only if its name, or the part after the last `.`, `/` or `:`, starts with a reading verb (`get`, `list`, `find`, `search`, `read`, `describe`, `query`, `count`, `fetch`) followed by something other than a lowercase letter (`list_people`, `getCompany`). Otherwise it asks.
- **Read-only** for widgets and `host.tools` means `readOnlyHint: true` only; the name guess doesn't count.
- **Arguments** go to the server as the model sent them. The host only checks they are an object, not against the tool's schema. Descriptions are cut to 1,000 characters; a tool with no description gets its name in words.
- **Requests** come from the app's webview (`apps/desktop/src/lib/mcp.ts`), so the server must allow CORS from any origin, including the `Authorization`, `Content-Type`, `Accept` and `MCP-Protocol-Version` headers. Each request is one POST; sessions aren't used. Tool lists are cached for five minutes.
- A server that can't be listed shows the user a notice in the chat; every other tool still works.

Views can call a server's tools themselves with `host.mcp.listTools` and `host.mcp.callTool`; see [MCP](../reference/host/mcp.md).

An MCP server doesn't need an extension to reach the assistant. Someone with `server:settings` can connect it to the whole SpaceMIX server in **Settings → MCP connections**: the server makes every request, keeps the credentials, and offers the tools as `<connection id>_<tool>` to the people with `mcp:<id>`. Build an extension around an MCP server when you also want a view, collections, events or your own settings; see [MCP connections](../reference/mcp-connections.md) for the difference. A connection's tools never take a name under an installed extension's namespace, so an extension's own MCP tools keep theirs.

## What the host does for you

- Builds the tools from each **installed** extension (`toolsFor` in `apps/desktop/src/lib/tools.ts`). An extension the team uninstalls loses its view and its tools but keeps its data.
- Runs each extension in its own sandboxed frame and checks every call it makes against the manifest's permissions.
- Validates arguments before your code runs, and returns every failure to the model as `{ error }` so it can correct itself instead of the turn failing.
- Stores collections encrypted on disk, one record per row, applies each write atomically, and pushes changes live to signed-in browsers.
- Reports every collection change as an event (`<collection>_created`, `_updated`, `_deleted`); see [Events](../reference/host/events.md).
- Asks the user for approval on gated tools before running them, in the SpaceMIX app's chats. `host.tools.call`, widgets and the [SpaceMIX API](../reference/api.md) never ask; an API key with `tools:write` runs gated tools as its scope allows.
- Offers the same tools to scripts and services over HTTP through the [SpaceMIX API](../reference/api.md#tools), by the same names and with the same validation.
