---
title: Getting started
summary: The folder layout of an extension, a first extension modelled on Tasks, and the development loop with npm run dev.
audience: both
since: protocol 1
---

# Getting started

An extension is one entry in SpaceMIX's left navigation, such as Tasks, Notes, Files or Chat. It has a view the user works in and data the assistant can read and change. Both halves are required. **Anything an extension shows the user, the assistant must be able to reach too.** You get the assistant half by declaring data, not by writing tool code (see [Giving the assistant your data](giving-the-assistant-data.md)).

There are no built-in extensions. Every extension, including the example in this repository, is a *package*: a manifest, one JavaScript bundle and one CSS file (see [Package format](../reference/package-format.md)). The package runs in its own sandboxed frame. Its code reaches the app only through `host` from `@spacemix/sdk`, and the host checks every call against the manifest's permissions (see [The host object](../reference/host/index.md)). Nothing ships with the app: a server gets its extensions from the registry in SpaceMIX Hub. Extension sources live in their own repositories (see [Extensions in their own repository](outside-the-repo.md)) and are built and published like anyone else's (see [Publishing](publishing.md)). This repository keeps only `extensions/example/`, and git ignores any other folder you make in `extensions/`.

If you are an AI agent building an extension, read [For agents](../agents.md) first.

## Folder layout

Use one self-contained folder per extension. `extensions/example/` is the smallest complete example to copy (an `index.ts`, a `manifest.ts` and one view); bigger extensions add the rest of this layout.

```
extensions/<name>/
  index.ts       Entry point: default-exports { manifest, View, actions }
  manifest.ts    Identity, permissions, collections, actions, events, notification kinds
  actions.ts     Handlers for the actions declared in the manifest
  view/          React components; the top-level one is the View
  lib/           Types, hooks and helpers
  README.md      What it does, how it's laid out, which tools it gives the assistant (shown in the store)
```

The entry file is `index.ts` or `index.tsx`. A small extension can keep everything in a single `index.tsx`. Only the shape of the default export matters, which is `ExtensionModule`:

```ts
// index.ts
import type { ExtensionModule } from "@spacemix/sdk";
import { actions } from "./actions";
import { manifest } from "./manifest";
import { BoardView } from "./view/BoardView";

export default { manifest, View: BoardView, actions } satisfies ExtensionModule;
```

| Field | Required | What it is |
|---|---|---|
| `manifest` | yes | The `ExtensionManifest`, usually built with `defineExtension`. See [Manifest](../reference/manifest.md). |
| `View` | yes | A React component with no props. It is the extension's whole screen. |
| `actions` | no | Handlers for the manifest's actions, keyed by action name. See [Actions](../reference/host/actions.md). |
| `mcp` | no | `(host) => Promise<McpServer[]>`: remote MCP servers whose tools the assistant gets. See [MCP](../reference/host/mcp.md). |

There is nothing to register. Every folder in `extensions/` (or listed in `SPACEMIX_EXTENSION_SOURCES`, see [Extensions in their own repository](outside-the-repo.md)) that has an `index.ts` or `index.tsx` is built into a package, and the sidebar, the store and the assistant all read from what is installed.

## A first extension

This is the manifest of Tasks, trimmed to one collection and one action:

```ts
// manifest.ts
import { defineExtension } from "@spacemix/sdk";

export const manifest = defineExtension({
  id: "com.acme.tasks",   // reverse-DNS; the last segment is the tool namespace
  name: "Tasks",
  version: "0.2.6",
  description: "A team board of to-do tasks in columns.",
  icon: "check-square",       // Lucide icon name, kebab-case
  order: 20,                  // position in the navigation, lower is higher up
  permissions: ["storage"],
  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." },
          notes: { type: "string", description: "Details." },
          done: { type: "boolean", description: "Whether it's completed. To complete an existing task, use tasks_complete.", default: false },
        },
        required: ["title"],
      },
    },
  ],
  actions: [
    {
      name: "complete",
      title: "Mark task done",
      description: "Mark a task as completed.",
      inputSchema: {
        type: "object",
        properties: { id: { type: "string", description: "The task's id, from tasks_items_list." } },
        required: ["id"],
      },
    },
  ],
});
```

`defineExtension` returns the manifest unchanged after checking it. It throws when the id is not reverse-DNS (`/^[a-z0-9]+(\.[a-z0-9-]+)+$/`), when a collection, action, event or notification kind name is not snake_case (`/^[a-z][a-z0-9_]*$/`), when a collection schema declares `id`, `createdAt` or `updatedAt`, when an event reuses a collection event's name, and when an event or notification kind is declared twice.

The handler for the action:

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

interface Task {
  title: string;
  notes?: string;
  done: boolean;
}

export const actions: Record<string, ActionHandler> = {
  complete: async ({ id }, host) => {
    const tasks = host.collection<Task>("items");
    if (!(await tasks.get(String(id)))) throw new Error(`No task with id "${String(id)}". Use tasks_items_list to find valid ids.`);
    return tasks.update(String(id), { done: true });
  },
};
```

And a view that reads the same records:

```tsx
// view/BoardView.tsx
import { useCollection } from "@spacemix/sdk/react";
import { Button, EmptyState, PageHeader } from "@spacemix/ui";
import { CheckSquare } from "lucide-react";

interface Task {
  title: string;
  notes?: string;
  done: boolean;
}

export function BoardView() {
  const { items, loaded, update } = useCollection<Task>("items");
  if (loaded && !items.length) {
    return <EmptyState icon={<CheckSquare className="size-5" />} title="No tasks yet" body="Ask the assistant to add one." />;
  }
  return (
    <div className="h-full overflow-y-auto bg-bg text-fg">
      <PageHeader title="Tasks" />
      <ul className="mx-4 divide-y divide-border rounded-lg border border-border bg-surface md:mx-10">
        {items.map((t) => (
          <li key={t.id} className="flex items-center gap-3 px-4 py-2.5">
            <span className={t.done ? "flex-1 text-muted line-through" : "flex-1"}>{t.title}</span>
            {!t.done && <Button onClick={() => void update(t.id, { done: true })}>Done</Button>}
          </li>
        ))}
      </ul>
    </div>
  );
}
```

That is a complete extension. The assistant now has `tasks_items_list`, `tasks_items_get`, `tasks_items_create`, `tasks_items_update`, `tasks_items_delete` and `tasks_complete`, and anything it changes shows up in the view at once.

## What you may import

Only these modules exist in the frame. The bundle does not carry its own copy; the frame provides them (see `HOST_MODULES` in [Package format](../reference/package-format.md)):

- `react`, `react/jsx-runtime`, `react-dom`
- `@spacemix/sdk` (`host`, types, `defineExtension`): see [The host object](../reference/host/index.md)
- `@spacemix/sdk/react` (hooks): see [React hooks](../reference/react.md)
- `@spacemix/ui` (components): see [UI kit](../reference/ui.md)
- `lucide-react` (icons) and `motion/react` (animation)

Plus your own files. In the Studio, any other bare import fails the build. The command-line build (Vite) would bundle an npm package it finds in `node_modules`, but that breaks the rule in [Self-contained](self-contained.md), and a Studio build of the same sources fails.

## The frame is not an ordinary web page

The view runs in a sandboxed iframe with an opaque origin and a Content-Security-Policy with `connect-src 'none'` (see [Protocol](../reference/protocol.md)). In practice:

- **No `fetch`, `XMLHttpRequest`, `WebSocket` or `EventSource`.** Use `host.net.fetch` with a `net:` permission (see [Network](../reference/host/net.md)).
- **No `localStorage`, cookies or IndexedDB.** Use a collection, `host.storage` or `useStored`.
- **No navigating links.** A click on an `<a href>` to an http(s), `mailto:` or `tel:` URL is routed to `host.shell.openUrl` by the frame runtime. Call `host.shell.openUrl` yourself for buttons (see [Shell](../reference/host/shell.md)), and `host.shell.copy` for the clipboard.
- **No `alert` or `confirm`.** Use `ConfirmDialog` from `@spacemix/ui`.
- **No external scripts, stylesheets or fonts.** Images and media may load from `data:`, `blob:` and http(s) URLs.
- **Layout:** the View fills the extension's box. Make its root `h-full` and scroll inside it (`overflow-y-auto`). Phones are about 380px wide, so don't use fixed widths.

## Pages and routes

**Every extension with more than one page needs routes.** Users expect Back, Forward, reload and copied links to work inside an extension the way they do between views. That only works if the extension reports where the user is.

The app's address names the server, the open view and, after the extension's id, the place inside it: `#/@3fa9c0d14e7b2a85/ai.spacemix.notes/note/42`. `@3fa9c0d14e7b2a85` is the server's shortcode (the first 16 characters of its id; the host writes it, see [Routes](../reference/host/view.md#routes)), so a link opens on the same server for everyone; an address without it still opens on the active server. The last part is your view's **route**, a path you make up (`""` is your start page). Keep the page in the route instead of in `useState`:

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

const [route, navigate] = useRoute();
const [kind, id] = route.split("/"); // "note", "42"

navigate(`note/${id}`);                                     // a new history step
navigate("", { replace: true });                            // the note was deleted: nothing to come back to
navigate(`search/${encodeURIComponent("q")}`, { replace: true }); // a search box, as the user types
```

- **What goes in it:** places worth coming back to: the open record, folder, tab or sub-screen. Not dialogs, filters, selections, scroll position or hover.
- **Segments:** separate them with `/`. Values that may contain `/` (file paths, names) go through `encodeURIComponent` when you build the route and `decodeURIComponent` when you read it. The host encodes the address on top.
- **Read it, don't copy it:** render from `route` on every render, so Back and Forward, which change it from outside, just work.
- **Missing targets:** on start the route may name something before your data has loaded. Wait for `loaded` before treating it as missing. Then show the nearest sensible page and fix the address with `navigate(…, { replace: true })`.
- **`replace`** rewrites the current step instead of adding one: redirects, a default tab filled in, text typed into a search box.

Outside React, use `host.view.route()`, `host.view.navigate(route, { replace })` and `host.view.onRoute(fn)`. Full reference: [Routes](../reference/host/view.md#routes).

A page that needs the whole window's width (an editor for one record, a canvas) can ask the app to hide its navigation while it shows: call `host.view.setFullscreen(route.startsWith("edit/"))` whenever the route changes, guarded with `typeof host.view.setFullscreen === "function"` for older hosts. The user can always end it from the app, and then your requests are ignored until they leave the view. Full reference: [Full screen](../reference/host/view.md#full-screen).

## Styling

Use Tailwind utility classes. The build compiles only the utilities your own files use, and they resolve through SpaceMIX's design tokens, so the extension matches the app in light and dark without shipping a theme. Use the token colors (`bg-bg`, `bg-surface`, `text-fg`, `text-muted`, `border-border`, `bg-accent`, `text-danger` and the rest listed in [UI kit](../reference/ui.md#design-tokens)) and never hard-code colors.

## The development loop

From the repository root:

```sh
npm install
cp apps/desktop/.env.example apps/desktop/.env
# In apps/desktop/.env set SPACEMIX_DATA_DIR and SPACEMIX_DB_KEY (openssl rand -hex 32).
npm run dev:server -- apps/desktop/.env   # a debug spacemix-server on port 1421
npm run dev                               # in a second terminal
```

`npm run dev:server` builds and runs a debug `spacemix-server` and prints the claim code you create the owner's account with. `npm run dev` runs `scripts/dev.mjs`: the frame runtime build, the Vite dev server for the app on `http://localhost:1420`, and `scripts/build-extensions.mjs --watch`, which rebuilds an extension folder whenever a file in it changes.

**While developing, builds install themselves.** A debug build of the SpaceMIX server watches `dist/extensions/` and, once a second, installs every package there whose file changed, new or not, with or without a version bump, approving the permissions it asks for (`apps/desktop/src-tauri/src/dev_extensions.rs`). Every window then reloads that extension's frame, because its hash changed. So saving a file reloads the extension within a second or two.

- These installs are local installs with source `dev`. The store shows them as "Built on this machine", and the registry never replaces them on its own: a listing under the id waits for the server's owner (see [When a listing takes a build's id](../reference/permissions.md#when-a-listing-takes-a-builds-id)).
- Uninstalling one stops it until you install it again from the Marketplace or a file.
- **Delete extension** on its page in **Extensions** uninstalls it and, if the server's owner ticks **Erase its data on this server**, erases its data there, so the next install starts empty. Its folder stays, and it doesn't come back on the next rebuild; install it again from the store or a file. See [Deleting your own build](../reference/permissions.md#deleting-your-own-build).
- `SPACEMIX_DEV_EXTENSIONS` sets the folder to watch, which also works for a release build or `spacemix-server`. Set it to an empty string or `off` to stop watching. When it is unset, a debug build watches the repository's `dist/extensions/` and a release build watches nothing.

To build without the app, run `npm run build:extensions` in `apps/desktop` (or `node scripts/build-extensions.mjs` from the root). `--only <folder>` builds one folder and `--watch` keeps rebuilding. To type-check the extensions, run `npm run typecheck` (it includes `tsc -p extensions`).

Extensions don't have to live in this repository. To keep one in its own repository, with its own version control, list its folder in `SPACEMIX_EXTENSION_SOURCES`; it's then built, watched and installed like the ones here. See [Extensions in their own repository](outside-the-repo.md).

You can also build an extension inside the app, with the assistant writing the code: see [The Studio](studio.md).

## Next

- [Extensions in their own repository](outside-the-repo.md): developing outside `extensions/`, with your own version control.
- [Self-contained](self-contained.md): the rules that keep an extension installable anywhere.
- [Giving the assistant your data](giving-the-assistant-data.md): collections, actions and MCP servers.
- [Writing for the model](writing-for-the-model.md): names, descriptions and errors the assistant can use.
- [Notifications and events](notifications-and-events.md): telling people and other extensions what happened.
- [Publishing](publishing.md) and the [Checklist](checklist.md).
