Plugin Development Guide
Step-by-step guide to scaffolding, building host-rendered UI, declaring permissions, packaging .ncpkg, and debugging Netcatty plugins
This guide walks through creating a production-ready Netcatty plugin from scratch using @netcatty/plugin-contract, @netcatty/plugin-sdk, and @netcatty/plugin-cli.
Prerequisites
- Node.js
>= 22(Node 24 recommended for modern plugins such as Netcatty Database) - TypeScript 5.x and a bundler (such as
esbuildorvite) when using React or external browser dependencies - Access to the Netcatty workspace packages (
@netcatty/plugin-contract,@netcatty/plugin-sdk,@netcatty/plugin-cli, currently API version0.1.0-internal.1)
If you are working inside a checkout of binaricat/Netcatty, build the plugin packages once from the repository root:
npm ci
npm run build:plugin-packagesStep 1: Scaffold a New Plugin
Use the netcatty-plugin CLI to generate a validated starter project with a reverse-domain plugin ID:
netcatty-plugin init ./my-netcatty-plugin \
--id com.example.my-plugin \
--name "My Plugin"This creates a clean package layout:
my-netcatty-plugin/
├── netcatty.plugin.json # Canonical manifest (required at package root)
├── package.json # Build scripts & @netcatty/plugin-sdk dependency
├── tsconfig.json # Strict ES2022 + Bundler resolution
└── src/
└── index.ts # Plugin entrypoint using definePlugin()Step 2: Configure netcatty.plugin.json
netcatty.plugin.json is validated against the closed JSON Schema 2020-12 contract (additionalProperties: false) plus strict semantic and path portability checks (UTF-8, NFC-normalized POSIX relative paths, no .., no backslashes, no symlinks escaping the package).
{
"manifestVersion": 1,
"id": "com.example.my-plugin",
"name": "my-plugin",
"displayName": {
"en": "My Plugin",
"zh-CN": "我的插件"
},
"description": {
"en": "Adds a host-rendered panel and command palette workflow to Netcatty.",
"zh-CN": "为 Netcatty 添加宿主渲染面板与命令面板工作流。"
},
"version": "0.1.0",
"publisher": "example",
"license": "MIT",
"engines": {
"netcatty": ">=0.0.0",
"api": ">=0.1.0-internal.1 <0.2.0"
},
"features": {
"required": [
"views.host-drawn",
"views.vault-pages",
"metadata.brand-icon"
]
},
"main": {
"browser": "dist/index.js"
},
"activationEvents": [
"onView:com.example.my-plugin.page",
"onCommand:com.example.my-plugin.open"
],
"permissions": {
"required": ["views", "commands", "settings.read"],
"optional": [
{
"permission": "storage",
"resources": ["*"],
"reason": "Persist local workspace preferences inside this plugin."
}
]
},
"contributes": {
"views": [
{
"id": "com.example.my-plugin.page",
"title": { "en": "My Tool", "zh-CN": "我的工具" },
"location": "vault-page",
"icon": { "kind": "theme", "name": "sparkles" }
}
],
"commands": [
{
"id": "com.example.my-plugin.open",
"title": { "en": "My Plugin: Run Action", "zh-CN": "我的插件:执行操作" }
}
],
"menus": [
{
"command": "com.example.my-plugin.open",
"location": "commandPalette",
"group": "tools"
}
],
"settings": [
{
"id": "com.example.my-plugin.defaultLabel",
"label": { "en": "Default label", "zh-CN": "默认标签" },
"group": { "en": "General", "zh-CN": "常规" },
"control": "text",
"scope": "application",
"default": "Hello"
}
]
},
"icon": {
"kind": "package",
"light": "assets/icon-light.png",
"dark": "assets/icon-dark.png"
}
}Manifest Rules to Remember
- Contribution ID prefixing: Every
view,command,setting,provider, andthemeID must begin with<manifest.id>.and be unique across all contribution kinds within the plugin. - Lazy activation: Prefer specific activation events (
onView:<id>,onCommand:<id>,onProvider:<id>) overonStartupFinishedso Netcatty keeps startup instant and only boots your sandbox when needed. - Brand icons (
metadata.brand-icon): Package brand icons must be static.pngor.webpfiles (recommended128×128or256×256),<= 256 KiB, dimensions1..512px. SVG and animated images are rejected for top-level brand icons. - Host-owned settings: Settings are always rendered as native Netcatty forms (
text,textarea,switch,select,number,secret). There is no customsettingsview location.
Step 3: Implement Lifecycle & Host Capabilities
Export a default object wrapped in definePlugin from @netcatty/plugin-sdk. Always register disposables on context.subscriptions so disable, reload, and shutdown clean up cleanly.
import { definePlugin } from "@netcatty/plugin-sdk";
export default definePlugin({
activate(context) {
context.subscriptions.add(
context.commands.registerCommand("com.example.my-plugin.open", async () => {
const label =
(await context.settings.get<string>("com.example.my-plugin.defaultLabel")) ??
"Hello";
context.logger.info("Command executed", { label });
return { label };
}),
);
},
deactivate() {
// Optional async teardown hook
},
});Core PluginContext Services
| Property | Purpose | Required Feature(s) | Permission(s) |
|---|---|---|---|
context.views | Register host-rendered views, persist per-scope view state (getState/setState), post messages, update sidebar notification badges (setBadge) | views.host-drawn, views.vault-pages, views.terminal-sidebar, views.badges | views |
context.commands | Register and execute namespaced commands | commands.interactive (for interactive commands) | commands |
context.settings | Read/update declared settings and subscribe to live onDidChange updates | — | settings.read / settings.write |
context.storage | Per-plugin local key-value store (device-local, never synced) | — | storage |
context.secrets | OS-encrypted (safeStorage) secret storage scoped strictly to your plugin | — | secrets |
context.network | Bounded HTTP(S) request(), direct TCP/TLS ByteStream, and Vault SSH tunnel connectViaHost() | network.byte-streams, network.host-byte-streams | network, network.stream, network.hostStream |
context.vault | Host picker (selectHosts with optional durable: true hb_* tokens), resolveHostBindings, execHostCommand, probeHost, listGroups, updateHostNotes, updateHostTags, requestConnect (terminal/sftp/remoteDesktop), revokeHostBinding | vault.host-actions, vault.host-exec, vault.host-probe | vault.metadata, vault.write, vault.hostExec |
context.vault.sftp | Pooled main-process SFTP (listDir, stat, readFile, writeFile, mkdir, delete) over durably bound SSH hosts (bounded <= 2 MiB file reads/writes) | vault.host-sftp | sftp.read, sftp.write |
context.portForward | Inspect and manage saved port-forwarding tunnels (list, create via hostBindingToken, start, stop, delete) | vault.port-forwarding | portForward.read, portForward.manage |
context.snippets | Read and manage reusable ops scripts in the Snippets library (list, get, save, delete) | vault.snippets | snippets.read, snippets.write |
context.terminals | Share selections, propose input drafts, plus listSessions, readScreen (<= 300 rows), sendInput (<= 8192B, audited), and openLocal | terminal.session-control, terminal.selection-sharing, terminal.input-drafts | terminal.metadata, terminal.output, terminal.input, ui.interact |
context.ui | Native dialogs (quickPick, input, confirm, openExternalUrl strictly https:// with confirmation) and file dialogs (openFile, saveFile, readFileHandle, writeFileHandle) | host.interactions | ui.interact |
context.workspace | Inspect open tabs (listTabs) and focus an existing tab (focusTab) | workspace.tabs | workspace.read, workspace.navigate |
context.ai / context.agent | Invoke host-configured AI models or agent sessions without touching API keys | ai.model-invocation, ai.agent-sessions | ai.invoke, ai.agent.use |
context.providers | Register terminal completion, decoration, theme, connection, auth, or importer providers | — | provider.terminal, etc. |
Tunneling Through a User's Vault SSH Host
Browser plugins can connect to private remote services (such as databases behind a bastion) without ever requesting SSH credentials or opening a local listening port:
const selection = await context.vault.selectHosts({
title: "Select an SSH bastion host",
});
if (selection.cancelled || selection.hosts.length !== 1) return;
const target = selection.hosts[0].target;
const conn = await context.network.connectViaHost({
target,
expectedRevision: target.revision,
endpoint: "tcp://127.0.0.1:5432",
});
try {
await conn.writable.write(handshakeBytes);
const response = await conn.readable.read();
} finally {
await conn.close();
}Netcatty presents a trusted confirmation dialog showing the plugin, selected SSH server, and destination endpoint, then reuses the user's existing SSH keys, jump hosts, proxies, and MFA.
Durable Host Bindings, Bounded SSH Exec & Quick-Jump
Plugins such as server monitors can bind saved Vault hosts durably and run bounded SSH inspection commands strictly inside the main process without ever accessing SSH keys:
- Declare required features
vault.host-actionsandvault.host-exec(PLUGIN_HOST_VAULT_EXEC_FEATURE), plus optional permissionsvault.metadataandvault.hostExec. - Durable tokens (
hb_*) are scoped to the plugin's opaquesourceOwner, survive restarts, and can be refreshed viavault.resolveHostBindingsor revoked anytime viavault.revokeHostBinding. vault.execHostCommandenforces strict host bounds (<= 8192Bcommand,1–30stimeout,1 KiB–1 MiBoutput cap,<= 16concurrent execs per runtime) over pooled SSH transports and aborts immediately on App Lock, disable, revocation, or policy switch.
// 1. Pick hosts and persist revocable durable bindings
const picked = await context.vault.selectHosts({
title: "Select hosts to monitor",
durable: true,
});
if (picked.cancelled) return;
const token = picked.hosts[0]?.hostBindingToken;
if (!token) return;
// 2. Refresh metadata (label, tags, group, os, notes) without re-prompting
const resolved = await context.vault.resolveHostBindings({
hostBindingTokens: [token],
});
// 3. Execute a bounded telemetry command on the host-pooled SSH transport
const res = await context.vault.execHostCommand({
hostBindingToken: token,
command: "uname -sr && uptime",
timeoutMs: 10_000,
maxOutputBytes: 262_144,
});
// 4. One-click jump to Terminal, SFTP, or Remote Desktop
await context.vault.requestConnect({
hostBindingToken: token,
mode: "sftp", // "terminal" | "sftp" | "remoteDesktop"
});
// 5. Zero-credential RDP / VNC / SSH reachability probe (feature: vault.host-probe)
const probe = await context.vault.probeHost({
hostBindingToken: token,
protocol: "ssh", // "rdp" | "vnc" | "ssh"
timeoutMs: 5_000,
});Safe SFTP, Port Forwarding, Snippets, Terminals & Workspace
All host-mediated infrastructure services reuse the same sourceOwner-scoped security model, fail closed on App Lock or revocation, and audit mutating operations:
// Pooled SFTP over a durably bound SSH host (feature: vault.host-sftp, perms: sftp.read / sftp.write)
const { entries } = await context.vault.sftp.listDir({
hostBindingToken: token,
path: "/etc/nginx",
});
const { data } = await context.vault.sftp.readFile({
hostBindingToken: token,
path: "/etc/nginx/nginx.conf",
encoding: "utf8",
});
// Port forwarding (feature: vault.port-forwarding, perms: portForward.read / portForward.manage)
const { rules } = await context.portForward.list();
// Snippets library (feature: vault.snippets, perms: snippets.read / snippets.write)
const { snippets } = await context.snippets.list();
// Terminal inspection & control (feature: terminal.session-control)
const { sessions } = await context.terminals.listSessions();
if (sessions[0]) {
const snap = await context.terminals.readScreen({
sessionId: sessions[0].sessionId,
maxRows: 80,
});
}
// Host confirmation & safe external HTTPS links (feature: host.interactions, perm: ui.interact)
const ok = await context.ui.confirm({
title: "Restart service?",
message: "This will reload nginx on prod-web-01.",
destructive: true,
});
if (ok) {
await context.ui.openExternalUrl({ url: "https://netcatty.app/en/docs/" });
}
// Workspace tabs (feature: workspace.tabs, perms: workspace.read / workspace.navigate)
const { tabs } = await context.workspace.listTabs();Step 4: Build Host-Rendered UI
Declare one or more view locations in contributes.views:
vault-page— Full workspace page in Vault's Extensions sidebar (requires featureviews.vault-pages)terminal-sidebar— Docked tool inside the terminal split side-panel (requires featureviews.terminal-sidebar)tab— Standalone main tabaside— Right-side drawer panelpanel— Bottom panelmodal— Focused modal dialog
Option A: React (@netcatty/plugin-sdk/host-react)
Bundle @netcatty/plugin-sdk/host-react, react, and react-dom into your browser entrypoint (dist/index.js):
import { useState } from "react";
import { definePlugin } from "@netcatty/plugin-sdk";
import {
registerHostReactView,
PluginPopover,
PluginCodeEditor,
PluginDataGrid,
PluginSplitPane,
usePluginShortcuts,
} from "@netcatty/plugin-sdk/host-react";
const css = `
.app {
display: flex;
flex-direction: column;
height: 100%;
background: hsl(var(--background));
color: hsl(var(--foreground));
font-family: system-ui, sans-serif;
}
.toolbar {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
border-bottom: 1px solid hsl(var(--border));
}
.run-btn {
background: hsl(var(--primary));
color: hsl(var(--primary-foreground));
border: 0;
border-radius: 6px;
padding: 6px 12px;
cursor: pointer;
}
`;
function Workbench() {
const [sql, setSql] = useState("SELECT 1 AS ok;");
const [menuOpen, setMenuOpen] = useState(false);
usePluginShortcuts((shortcut) => {
if (shortcut === "escape") setMenuOpen(false);
});
return (
<div className="app">
<div className="toolbar">
<button id="actions-btn" className="run-btn" onClick={() => setMenuOpen(true)}>
Actions
</button>
<PluginPopover anchor="actions-btn" open={menuOpen} onClose={() => setMenuOpen(false)}>
<div style={{ padding: 8 }}>Host-positioned popover content</div>
</PluginPopover>
</div>
<PluginSplitPane direction="vertical" initialSize={220}>
<PluginCodeEditor
value={sql}
language="pgsql"
onChange={({ value }) => setSql(value)}
/>
<PluginDataGrid
columns={[{ name: "ok", type: "int" }]}
rows={[{ ok: 1 }]}
/>
</PluginSplitPane>
</div>
);
}
export default definePlugin({
activate(context) {
context.subscriptions.add(
registerHostReactView(
context.views,
"com.example.my-plugin.page",
() => <Workbench />,
css,
),
);
},
});Option B: Plain DOM (@netcatty/plugin-sdk/host-dom)
For lightweight plugins without React, use registerHostDomView(context.views, viewId, (root, stateScope) => cleanup, css).
Theme Tokens, Assets & Rendering Limits
- Host theme tokens: Seven semantic HSL variables track light/dark mode and user palettes automatically:
--background,--foreground,--muted,--muted-foreground,--border,--primary, and--primary-foreground. Author-defined variables must use the--plugin-prefix. - Package images: Reference package-local images with
<img src="asset:images/logo.svg" alt="Logo" />. Netcatty validates path containment and rasterizes them offline to safe PNGs (max512 KiBsource,2048pxoutput edge). External HTTP(S) image URLs,data:URLs, inline<svg>,<canvas>, andposition: fixedare disallowed. - Native IDE widgets:
@netcatty/plugin-sdk/host-reactexportsPluginPopover,PluginCodeEditor,PluginDataGrid,PluginMetricChart,PluginBiChart,PluginSplitPane,PluginErCanvas, andusePluginShortcuts(mod+k,mod+s,mod+t,mod+w,mod+z,mod+shift+z,escape).PluginMetricChart(metric-chart) renders pure host-owned SVG time-series charts (variant: "area" | "line" | "sparkline" | "bar") with multi-series data, sparse gap breaking, configurablethresholds(warning/critical), and 60fps local crosshair hover tooltips with zero IPC roundtrips (while keeping arbitrary plugin<svg>blocked).PluginBiChart(bi-chart) renders pure host-owned interactive BI analytics charts across 10 chart types (bar,horizontal-bar,stacked-bar,line,area,pie,donut,scatter,funnel,combo) with strict schema bounds (12 series, 500 categories, 1,500 scatter points), 60fps local hover tooltips & legend toggling, built-in standalone SVG and 2× PNG export (onExportSvg/onExportPng), and semanticonDatumClickcross-filtering events.
import { PluginMetricChart, PluginBiChart } from "@netcatty/plugin-sdk/host-react";
// Real-time telemetry trend chart (metric-chart)
<PluginMetricChart
variant="area"
height={180}
min={0}
max={100}
thresholds={[
{ value: 80, tone: "warning", label: "Warn 80%" },
{ value: 95, tone: "critical", label: "Crit 95%" },
]}
series={[
{
id: "cpu",
label: "CPU",
color: "primary",
unit: "%",
points: [
{ at: Date.now() - 60_000, value: 34.2 },
{ at: Date.now(), value: 41.8 },
],
},
]}
/>
// Interactive BI analytics chart (bi-chart: 10 chart types, <= 12 series / 500 categories / 1,500 scatter points)
<PluginBiChart
type="bar" // "bar" | "horizontal-bar" | "stacked-bar" | "line" | "area" | "pie" | "donut" | "scatter" | "funnel" | "combo"
title="Revenue by Region"
categories={["North America", "Europe", "APAC"]}
series={[
{ id: "revenue", label: "Revenue", values: [24800, 15200, 8600] },
{ id: "profit", label: "Gross Profit", values: [9400, 6100, 3400] },
]}
valueFormat="currency"
currency="USD"
height={260}
exportable
onDatumClick={({ category, seriesId, value }) => {
// Cross-filter tables or pinned dashboard cards
}}
onExportSvg={({ svg, filename }) => { /* save SVG */ }}
onExportPng={({ dataUrl, filename }) => { /* save 2x PNG */ }}
/>- Validation budgets: Each view enforces bounded limits (up to
4,096remote nodes, depth32,1 MiBtext/batch payload,128 KiBstylesheet,256uniqueasset:image paths per view instance,120updates/sec). Invalid elements or unsafe CSS close the view safely.
Sidebar Notification Badges (context.views.setBadge)
Plugins declaring a vault-page or terminal-sidebar view can display live numeric counters, short status labels, or compact dot indicators directly on their sidebar icon (both expanded and collapsed rails) and terminal sidebar launcher using context.views.setBadge:
- Feature & permission: Advertised as
PLUGIN_VIEW_BADGES_FEATURE = "views.badges"incontext.enabledFeaturesand reuses the existingviewspermission (checkcontext.enabledFeatures.has("views.badges")or list it infeatures.optional/features.required). - Overloads:
context.views.setBadge(badge: ViewBadgeParams): Promise<void>context.views.setBadge(viewId: string, badge: Omit<ViewBadgeParams, "viewId"> | null): Promise<void>
- Precedence & strict host bounds:
- Only the calling plugin's own declared
vault-pageorterminal-sidebarviewIdis accepted (foreign, unknown, or other-location views are rejected). - Display priority:
count(non-negative integer clamped0..999;0/nullclears; renders99+above99) >text(trimmed<= 4printable ASCII chars, no control chars) >dot(boolean). tone:"default" | "info" | "warning" | "danger"(defaults to"default").tooltip: optional string<= 160chars (no control chars).- Automatic cleanup: Clearing via
setBadge(viewId, null)or{ viewId, count: null, text: null, dot: false }removes the badge immediately; the host also clears all plugin badges automatically on runtime stop/crash, disable/uninstall, and App Lock.
- Only the calling plugin's own declared
if (context.enabledFeatures.has("views.badges")) {
// Show active alert counter on the plugin's own Vault sidebar page
await context.views.setBadge({
viewId: "com.example.my-plugin.page",
count: activeAlerts.length,
tone: hasCritical ? "danger" : "warning",
tooltip: `${activeAlerts.length} active host alerts`,
});
// Clear the badge once alerts are acknowledged
await context.views.setBadge("com.example.my-plugin.page", null);
}Building Data-Only Theme Packs
If you only want to ship custom light or dark host colors, you do not need any JavaScript or permissions:
{
"manifestVersion": 1,
"id": "com.example.ocean-themes",
"name": "ocean-themes",
"displayName": { "en": "Ocean Themes", "zh-CN": "海洋主题" },
"version": "0.1.0",
"publisher": "example",
"license": "MIT",
"engines": { "netcatty": ">=0.0.0", "api": ">=0.1.0-internal.1 <0.2.0" },
"features": { "required": ["appearance.theme-packs"] },
"main": { "data": "theme" },
"contributes": {
"themes": [
{
"id": "com.example.ocean-themes.dark",
"label": { "en": "Ocean Dark", "zh-CN": "海洋深色" },
"variant": "dark",
"entry": "dark.json"
}
]
}
}Each palette file (dark.json) specifies formatVersion: 1, base: "light" | "dark", and opaque #RRGGBB semantic colors verified automatically by Netcatty for WCAG contrast (>= 4.5:1 for text pairs, >= 3:1 for borders/controls).
Step 5: Validate, Check Compatibility & Pack .ncpkg
Run the official CLI commands before testing or releasing:
# 1. Build your plugin (runs npm run build --if-present, then validates directory)
netcatty-plugin build ./my-netcatty-plugin
# 2. Validate manifest schema, semantic rules, paths, and icons
netcatty-plugin validate ./my-netcatty-plugin
# 3. Verify engine & feature compatibility
netcatty-plugin compatibility ./my-netcatty-plugin \
--netcatty 1.0.0 \
--api 0.1.0-internal.1 \
--features views.host-drawn,views.vault-pages,metadata.brand-icon
# 4. Pack into a deterministic .ncpkg archive (prints file count + SHA-256)
netcatty-plugin pack ./my-netcatty-plugin --out ./dist/my-plugin-0.1.0.ncpkg
# 5. Validate the packed .ncpkg archive itself
netcatty-plugin validate ./dist/my-plugin-0.1.0.ncpkgIf you are using the CLI directly from a Netcatty repository checkout, invoke node packages/plugin-cli/dist/cli.js <command> ....
Step 6: Local Testing & Debugging in Netcatty
- Import into Netcatty: Open Settings → Plugins → Browse → Import
.ncpkgand select your.ncpkgfile. - Review & Enable: Newly imported packages install disabled. Inspect the declared permissions and toggle the plugin Enabled.
- Test Permission Modes: Switch optional capabilities between Allow, Ask, and Deny in the plugin's Settings detail view to verify your plugin handles rejections gracefully (remember: changing policy cancels in-flight RPCs).
- Inspect Logs & Audit Events: Use
context.logger(debug/info/warn/error) for structured, redacted diagnostics and inspect recent security events in the plugin's detail panel. - Re-pack and Re-import: Bump your version or re-import during iteration. Because unsigned security principals hash the package bytes, re-importing an updated
.ncpkgkeeps the new package isolated until re-enabled.
Ready to share your plugin with Netcatty users? Head over to the Marketplace Submission & Publishing Guide.