# Writing an Appy extension

An Appy extension is a small TypeScript/React package in the Raycast style: it adds commands to Appy's launcher.
A command can be a **view** (a List, Grid, Detail or Form in the launcher), a **no-view** command (runs headless,
shows a toast or HUD) or a **menu-bar** command (renders into the macOS menu bar). You write `.tsx`/`.ts` files,
`create_extension` builds them with esbuild, installs the package and opens it for you.

Always read this document fully before calling `create_extension`. Test what you build with `inspect_extension`.
Before drawing any UI (a popover page, a menu bar title or icon), follow [ui-guide.md](ui-guide.md), which
`get_extension_docs` appends after this guide: light and dark over macOS 26's glass, menu bar space, store icons.

## File layout

```
package.json          written for you from create_extension's arguments — never send it in files
src/<command>.tsx     one entry file per command, named exactly after the command
src/shared.ts         any extra files you like, imported relatively
assets/…              images etc., read with environment.assetsPath or referenced as asset icons
icon.png              optional; if you don't send one, a letter icon is generated
```

## package.json shape (written by create_extension)

```json
{
  "name": "my-extension", "title": "My Extension", "description": "…", "icon": "icon.png",
  "author": "appy", "license": "MIT", "platforms": ["macOS"],
  "commands": [
    { "name": "list", "title": "List Things", "mode": "view",
      "description": "…", "subtitle": "…", "keywords": ["…"],
      "arguments": [{ "name": "query", "type": "text", "placeholder": "…", "required": false }],
      "preferences": [{ "name": "limit", "type": "textfield", "title": "Limit", "default": "10" }] },
    { "name": "watch", "title": "Watch", "mode": "menu-bar", "interval": "5m" }
  ],
  "preferences": [{ "name": "token", "type": "password", "required": true, "title": "API token" }],
  "dependencies": { "dayjs": "1.11.13" }
}
```

Rules: `name` and each command `name` are lowercase slugs; command `mode` is `view` (default), `no-view` or
`menu-bar`; menu-bar `interval` is a shorthand like `30s`, `5m`, `1h` (minimum effective 10 s; without it the
command runs once); dependencies must be exact versions (`1.11.13` — ranges like `^1.0.0` or tags like `latest`
are rejected) published at least 7 days ago. Argument types: `text`, `password`, `dropdown` (with `data`).
Preference types: `textfield`, `password` (stored in the Keychain), `checkbox`, `dropdown` (with `data`
`[{title, value}]`), `appPicker`. Preference defaults apply when the person hasn't set a value; required
preferences are asked in the launcher before first run.

## The supported @raycast/api surface

Every command's default export is a React component (view) or an async function (no-view). Supported:

- Components: `List` (+ `List.Item`, `List.Section`, `List.EmptyView`, `List.Dropdown` + `List.Dropdown.Item`/
  `Section`), `Grid` (+ same children, rendered as a native grid), `Detail` (+ `Detail.Metadata` with
  `Label`/`Link`/`TagList`/`Separator`), `Form` (+ `TextField`, `TextArea`, `PasswordField`, `Dropdown`,
  `Checkbox`, `DatePicker`, `TagPicker`, `FilePicker`, `Separator`, `LinkAccessory`), `MenuBarExtra`
  (+ `Item`, `Section`, `Separator`, `Submenu`), `ActionPanel` (+ `Action`, `ActionPanel.Section`/`Submenu`),
  `Action` variants: `Push`, `CopyToClipboard`, `Paste`, `OpenInBrowser`, `Open`, `SubmitForm`, `Trash`,
  `CreateSnippet`(as copy), `Icon`, `Color`, `Image` types, `Keyboard.Shortcut`.
- Hooks/functions: `useNavigation` (`push`/`pop`/`popToRoot`), `useCachedState`, `useCachedPromise` (basic),
  `useLocalStorage` (via `@raycast/utils`), `getPreferenceValues()`, `environment` (`appearance`, `assetsPath`,
  `supportPath`, `commandName`, `extensionName`, `launchType`, `isDevelopment`), `LocalStorage`
  (`getItem/setItem/removeItem/allItems/clear`, JSON values), `Cache`, `showToast`/`Toast` (+ `Toast.Style`,
  `primaryAction`), `showHUD`, `Clipboard` (`copy`/`paste`/`readText`/`read` with offset), `open`,
  `openExtensionPreferences`, `openCommandPreferences`, `launchCommand` (same extension only),
  `updateCommandMetadata` (`subtitle` persists and shows in root search), `getSelectedText`,
  `getSelectedFinderItems`, `getFrontmostApplication`, `getApplications`, `confirmAlert`/`Alert`,
  `closeMainWindow`, `popToRoot`, `clearSearchBar`, `showInFinder`, `trash`.
- Detail markdown: real markdown — headings, lists, tables, code blocks, links, images (https or paths in assets).

Not supported (don't use them): AI/`AI.*`, OAuth utilities, `useSQL`, `usePromise` refreshers beyond basics,
`List.Item.Detail` custom React children (metadata only), window management APIs, `MenuBarExtra` `isLoading`
spinner details. Grids render image/color/emoji content; complex custom cell children are not drawn.

### @appy/api extras

```ts
import { runInTerminal, chooseFolder } from "@appy/api";
await runInTerminal("npm test", { cwd: "/path/to/cwd", title: "Tests" });   // opens Terminal.app, cwd optional, title sets the tab
const folder = await chooseFolder();               // string path, or null when cancelled
```

### Calendar

Your extension can read and add to the person's calendars (macOS Calendar, through EventKit). The first call asks
them for access once; if they refuse, calls throw with a message saying where to allow it.

```ts
import { calendar } from "@appy/api";
const cals = await calendar.list();                          // [{ id, title, color, writable, source }]
const events = await calendar.events(from, to);              // Dates or ISO strings, at most 400 days apart
// → [{ id, title, start: Date, end: Date, allDay, calendar, calendarId, color, location?, notes?, url? }]
await calendar.create({ title: "Lunch", start, end, allDay: false, calendar: cals[0].id, location: "Café" });
await calendar.open(date);                                   // Calendar.app on that day
```

Only add events the person asked for (a form they submitted), never on your own.

### Menu bar extras: clock, date icon and popovers

`MenuBarExtra` takes three Appy props on top of Raycast's:

- `titleFormat="EEE d MMM  HH:mm"`: Appy keeps the title current from this Unicode date pattern, every second, without
  running your command again. Use it instead of an `interval` for any clock or date.
- `dateIcon`: today's day number in a rounded box, the way a calendar app shows it; redrawn at midnight.
- `popover`: what a click opens instead of a menu.
  - `popover={{ page: "popover.html", width: 260 }}`: your own page from `assets/`, in a native popover under the
    icon. It fits its height to the content and hears `appy:show` / `appy:hide` as it opens and closes (stop timers on
    hide). The page gets `window.appy`: `appy.calendar.*` (as above), `appy.system.*` (below),
    `appy.open(url)` (http, https or mailto), `appy.close()`, `appy.pin(true|false)` (stay open on outside
    clicks), `appy.openCalendar()`, and `appy.environment` (`appearance`, `firstWeekday` 0 = Sunday, `locale`,
    `uses24Hour`). It hears a `appy:show` event each time it opens, to refresh. Use `prefers-color-scheme` for dark mode.
  - `popover="month"`: one of your view commands, opened in the launcher under the icon.

```tsx
export default function Command() {
  return <MenuBarExtra dateIcon titleFormat="EEE h:mm a" popover={{ page: "popover.html", width: 236 }} />;
}
```

`examples/extensions/mini-calendar` is a complete Itsycal-style calendar built this way.

### System readings

```ts
import { system } from "@appy/api";
const s = await system.stats();       // { cpu: { usage, user, system, cores, perCore, load }, memory: { total, used, app, wired, compressed,
                                       //   usedPercent, swapUsed, pressure }, network: { down, up, received, sent }, disk: { name, total, free,
                                       //   usedPercent }, battery?: { percent, charging, onPower, minutesLeft?, minutesToFull? }, history: [...] }
const top = await system.processes(); // { cpu: [{ pid, name, cpu, memory }], memory: [...] } (the 5 busiest)
```

Appy samples every 2 seconds while anything asks (and stops 15 seconds after the last ask), keeping a minute of
history for graphs. A menu-bar command can keep running and update its title from these: see
`examples/extensions/system-monitor` (iStat Menus-style). Popover pages get the same as `appy.system.*`.

### Web links (browser pickers)

Declare `"appy": { "linkHandler": "route" }` in package.json, where `route` is a no-view command. While Appy is the
default browser, every http(s) link opened on the Mac runs it with `props.launchContext.url`; open it with
`open(url, browserPath)`. With no handler installed, links go to the browser that was the default before.

```ts
import { links } from "@appy/api";
await links.browsers();               // [{ name, path, bundleId }], Appy left out
await links.isDefaultBrowser();       // true once the person accepted
await links.becomeDefaultBrowser();   // macOS asks them to confirm
```

`MenuBarExtra.Item` also takes `icon={{ fileIcon: "/Applications/Safari.app" }}` (an app's own icon) and `checked`
(a check mark). See `examples/extensions/browser-picker` (Velja-style).

### Camera in a popover page

A popover page may call `navigator.mediaDevices.getUserMedia({ video: true })`; macOS asks the person once. The
microphone is refused. Stop the tracks on `appy:hide` so the camera turns off when the popover closes:
`examples/extensions/camera-preview`.

### Grid text cells

`<Grid.Item content={{ text: "17", tint: "#FFFFFF", background: "#FF3B30" }} />` draws text (a day number, a short
label) instead of an image; `background: "transparent"` leaves the tile out.

### MCP servers

An extension can call the tools of any MCP server: a program on this Mac, or a remote one over Streamable HTTP.

```ts
import { mcp } from "@appy/api";
const servers = await mcp.listServers();                  // [{ name, title, kind: "local" | "remote", configured, allowed, installed }]
const tools = await mcp.listTools("linear");
const result = await mcp.callTool("linear", "list_issues", { query: "bug" }, { timeout: 30000 });
result.text; result.structuredContent; result.content;    // a tool error throws, with the tool's message
```

Declare the servers it uses, so the person needn't set them up: `mcp_servers` in `create_extension`, or in package.json
`"appy": { "mcpServers": { "chime": { "title": "Chime", "command": "/path/to/server", "args": [] }, "linear": { "title": "Linear", "url": "https://mcp.linear.app/mcp" } } }`.
Never put tokens there. The person's own server of the same name wins. The first use of a server asks them; a no makes the
call throw, so have something else to do. `installed` is false when a local server's program isn't there. A remote server may
need a sign-in (Settings › MCP Servers); until then calls throw and say so. Timeouts default to 60 s, 10 minutes at most.

### @raycast/utils

`@raycast/utils` is available to import (`useLocalStorage`, `useFetch`, `usePromise`, …) without declaring it.
Anything else must be an exact-version dependency; it is installed with npm `--omit=dev --ignore-scripts` and
bundled into your command by esbuild. `react`, `@raycast/api` and `@raycast/utils` are provided by the host —
never put them in dependencies.

## Keyboard and interaction defaults

Return runs the first action, ⌘Return the second, ⌘K opens the action panel (sections, shortcuts and all),
Esc pops one level (leaving the first level ends the command). `searchBarPlaceholder` sets the search field's
placeholder, `isShowingDetail` on a List shows the markdown detail pane, `searchBarAccessory` takes a
`List.Dropdown`, `pagination`/`onLoadMore` paged loading works, `isLoading` shows a progress line.
In Forms, ⌘Return or the primary button submits; give every field an `id`; `error` shows red text under the
field; `storeValue` remembers the last submitted value per command.

## Storage

`LocalStorage` and `useLocalStorage` persist JSON per extension (survives updates and reinstalls of the same id,
removed on uninstall). `Cache` is for data that may vanish. `environment.supportPath` is a writable per-extension
directory. Password preferences live in the Keychain, never in the preferences file.

## Complete example (builds and runs as-is)

`src/list.tsx`:

```tsx
import { Action, ActionPanel, Color, Icon, List, showToast, Toast } from "@raycast/api";
import { useState } from "react";

const ITEMS = [
  { id: "one", title: "First thing", tag: "alpha" },
  { id: "two", title: "Second thing", tag: "beta" },
];

export default function Command() {
  const [tag, setTag] = useState("all");
  const shown = ITEMS.filter((i) => tag === "all" || i.tag === tag);
  return (
    <List
      isShowingDetail
      searchBarPlaceholder="Search things…"
      searchBarAccessory={
        <List.Dropdown tooltip="Tag" onChange={setTag}>
          <List.Dropdown.Item title="All" value="all" />
          <List.Dropdown.Section title="Tags">
            <List.Dropdown.Item title="Alpha" value="alpha" />
            <List.Dropdown.Item title="Beta" value="beta" />
          </List.Dropdown.Section>
        </List.Dropdown>
      }
    >
      <List.Section title="Things">
        {shown.map((item) => (
          <List.Item
            key={item.id}
            title={item.title}
            icon={{ source: Icon.Circle, tintColor: Color.Blue }}
            accessories={[{ tag: { value: item.tag, color: Color.Green } }, { date: new Date() }]}
            detail={
              <List.Item.Detail
                markdown={`# ${item.title}\n\nSome **markdown** with \`code\` and a list:\n\n- one\n- two`}
                metadata={
                  <Detail.Metadata>
                    <Detail.Metadata.Label title="Tag" text={item.tag} />
                    <Detail.Metadata.Separator />
                  </Detail.Metadata>
                }
              />
            }
            actions={
              <ActionPanel>
                <ActionPanel.Section title="Do">
                  <Action title="Say Hello" icon={Icon.Message} onAction={() => showToast({ style: Toast.Style.Success, title: "Hello!" })} />
                  <Action.Push title="Open Form" shortcut={{ modifiers: ["cmd"], key: "return" }} target={<ThingForm />} />
                </ActionPanel.Section>
                <Action.CopyToClipboard title="Copy Title" content={item.title} shortcut={{ modifiers: ["cmd", "shift"], key: "c" }} />
              </ActionPanel>
            }
          />
        ))}
      </List.Section>
    </List>
  );
}
```

(If the form is in the same file, import `Form`/`useNavigation` too; a Form example:)

```tsx
function ThingForm() {
  const { pop } = useNavigation();
  return (
    <Form
      actions={
        <ActionPanel>
          <Action.SubmitForm title="Save" onSubmit={async (values) => {
            await showToast({ style: Toast.Style.Success, title: "Saved " + values.name });
            pop();
          }} />
        </ActionPanel>
      }
    >
      <Form.TextField id="name" title="Name" placeholder="…" storeValue />
      <Form.TagPicker id="tags" title="Tags">
        <Form.TagPicker.Item value="a" title="A" />
        <Form.TagPicker.Item value="b" title="B" />
      </Form.TagPicker>
      <Form.DatePicker id="when" title="When" />
    </Form>
  );
}
```

`import { Detail, Form, useNavigation } from "@raycast/api";` at the top as needed.
`create_extension` call for it: `commands: [{name: "list", title: "List Things", mode: "view"}]`,
`files: [{path: "src/list.tsx", content: "…"}]`.

A no-view command exports an async function instead:

```ts
import { showHUD } from "@raycast/api";
export default async function Command(props: { arguments: { query?: string } }) {
  await showHUD("Done " + (props.arguments.query ?? ""));
}
```

## Testing with inspect_extension

After `create_extension` (which already opens the first view command and returns a screenshot), drive it:

```
inspect_extension { extension: "appy.my-extension", steps: [
  { "type": "search text" },          // replaces the launcher search text
  { "wait": 400 },
  { "select": "First thing" },        // row title (or id)
  { "key": "cmd+k" },                 // open the action panel
  { "action": "Open Form" },          // click an action by its title
  { "fill": { "name": "Test" } },     // form fields by id
  { "submit": true },
  { "wait": 600 },
  { "key": "esc" }
] }
```

Keys: `return`, `esc`, `tab`, `up`/`down`/`left`/`right`, `cmd+k`, `cmd+return`, or any `cmd+shift+x` style
combo. `wait` is milliseconds (max 5000). The result is the level stack, the top level's normalized view JSON,
toasts/HUDs since your last inspect, the last 50 log lines, any error and a PNG screenshot. A step that can't
run stops there and tells you why. Use `run_extension` for no-view and menu-bar commands, `list_extensions`
to see everything installed, `uninstall_extension` to remove one.

`select` and `action` fail when there is no such row or action; `type`, `select`, `action` and `dropdown` fail while a form or
detail page is showing, and `fill`/`submit` while a list is.

Store extensions (installed from the Raycast Store, possibly signed in as the person) can't be run or inspected
through MCP — build your own instead.
