@mycodex/plugin
v0.0.1
Published
Plugin SDK for building tools, toolsets, collections, views, hooks, and error registries for the MyCodex AIOS
Readme
@mycodex/plugin
The official MyCodex Plugin SDK — a developer toolkit for building extensions, tools, and integrations on top of the MyCodex AIOS.
Build, extend, and publish autonomous agent capabilities, persistent data schemas, user interface panels, custom error diagnostics, and system hook interceptions with a fluent, type-safe builder API.
Key Features
| Builder | Purpose |
|---------|---------|
| MyCodexTool | Define callable actions with input schemas and async handlers |
| MyCodexToolset | Group related tools under connection configurations |
| MyCodexCollection | Define reactive data persistence schemas with lifecycle hooks |
| MyCodexView | Construct reactive UI trees rendered inside the MyCodex workspace |
| MyCodexHook | Intercept and modify pipeline events (e.g., PreToolUse, SessionStart) |
| MyCodexError | Create diagnostic error registries with actionable CTAs |
Installation
# Using bun (recommended)
bun add @mycodex/plugin
# Using npm
npm install @mycodex/plugin
# Using pnpm
pnpm add @mycodex/pluginPeer Dependencies
This package requires zod@^4.0.0 as a peer dependency:
bun add zodMake sure zod is installed in your project — it is used for schema validation across all builders.
Requirements
- Bun:
>=1.3(recommended) or Node.js:>=22 - TypeScript:
>=5.5(strongly recommended for type safety)
TypeScript Support
All builders are written in TypeScript and export full type definitions out of the box.
import { MyCodexTool, type MyCodexContext } from "@mycodex/plugin";
import { z } from "zod";
// Full type inference on input
const tool = MyCodexTool.create("search")
.withSchema(z.object({ query: z.string() }))
.withHandler(async ({ input, MyCodex }) => {
// `input` is fully typed: { query: string }
// `MyCodex` provides workspace context, env vars, config
const results = await performSearch(input.query);
return { results };
});API Reference
1. Defining a Tool (MyCodexTool)
Tools represent callable actions that AI agents use to interact with the system or external APIs.
import { z } from "zod";
import { MyCodexTool } from "@mycodex/plugin";
const GreetSchema = z.object({
name: z.string().describe("The name of the user to greet")
});
export default MyCodexTool.create("greet")
.withDescription("Greets a user by name professionally")
.withSchema(GreetSchema)
.withHandler(async ({ input, MyCodex }) => {
// Access workspace context
const workspaceName = MyCodex.config.name;
return `Hello, ${input.name}! Welcome to ${workspaceName}.`;
});MyCodexTool Methods
| Method | Description |
|--------|-------------|
| .create(name) | Initialize a new tool with a unique name |
| .withDescription(text) | Set the documentation description for AI agents |
| .withSchema(schema) | Attach a Zod schema for input validation |
| .withHandler(fn) | Define the async execution logic |
| .withRules(rules) | Attach cognitive policy rules (optional) |
2. Grouping Tools in a Toolset (MyCodexToolset)
Toolsets bundle related tools under a shared connection configuration.
import { MyCodexToolset } from "@mycodex/plugin";
import greetTool from "./greet.tool";
import searchTool from "./search.tool";
export default MyCodexToolset.create("utilities")
.withDescription("Essential workspace helper tools")
.withConnection({ type: "custom" })
.addTool(greetTool)
.addTool(searchTool);Connection Types
| Type | Use Case |
|------|----------|
| mcp-server::stdio | Local MCP server subprocess |
| mcp-server::http | Remote MCP server over HTTP/SSE |
| rest-api | Standard REST API integration |
| cli | Command-line tool wrapper |
| custom | In-memory JavaScript/TypeScript handlers |
3. Creating a Collection (MyCodexCollection)
Collections model local files as typed records with reactive lifecycle hooks.
import { z } from "zod";
import { MyCodexCollection } from "@mycodex/plugin";
const UserSchema = z.object({
id: z.string(),
username: z.string(),
role: z.enum(["admin", "developer", "user"]),
createdAt: z.string().optional()
});
export default MyCodexCollection.create("users")
.withSchema(UserSchema)
.withPatterns(["data/users/*.json"])
.onCreated(async ({ data, MyCodex }) => {
console.log(`User ${data.username} created in ${MyCodex.config.name}`);
})
.onUpdated(async ({ data, MyCodex }) => {
await MyCodex.notifications.send({
title: "User Updated",
body: `User ${data.username} was modified.`
});
});Lifecycle Hooks
| Hook | Trigger |
|------|---------|
| onCreated | After a new record is persisted |
| onUpdated | After an existing record is modified |
| onDeleted | After a record is removed |
| onRead | When a record is retrieved |
| onList | When records are queried (supports filtering) |
4. Creating a Workspace View (MyCodexView)
Views render custom visual components inside the MyCodex workspace sidebar or main viewport.
import { MyCodexView } from "@mycodex/plugin";
export default MyCodexView.create("recent-activities")
.withTitle("Recent Activities")
.withDescription("Displays recent actions performed in the active workspace")
.withData(async (ctx) => {
const activities = await ctx.workspace.core.activities.findMany({
take: 20,
orderBy: { createdAt: "desc" }
});
return {
items: activities.map(a => ({
id: a.id,
title: a.title,
status: a.status
})),
stats: { total: activities.length }
};
})
.withTree([
{
component: "Section",
children: [
{
component: "Table",
props: { path: "items" },
children: [
{ component: "Column", props: { path: "title", header: "Activity" } },
{ component: "Column", props: { path: "status", header: "Status" } }
]
}
]
}
]);5. Intercepting Events with Hooks (MyCodexHook)
Hooks intercept operations on the MyCodex pipeline, enabling safety checks, audit logging, or result modification.
import { MyCodexHook } from "@mycodex/plugin";
export default MyCodexHook.create("safety-guard")
.onType("PreToolUse")
.withHandler(async (event) => {
const cmd = event.input.toolInput?.command || "";
// Block dangerous commands
if (cmd.includes("rm -rf") || cmd.includes(":(){ :|:& };:")) {
throw new Error(
"Destructive terminal commands are forbidden in this workspace."
);
}
// Log all tool invocations for audit
await event.MyCodex.audit.log({
tool: event.input.toolName,
args: event.input.toolInput,
timestamp: new Date().toISOString()
});
return event.output;
});Supported Event Types
| Event Type | Description |
|------------|-------------|
| SessionStart | Fired when a new agent session begins |
| SessionEnd | Fired when an agent session completes |
| PreToolUse | Fired before a tool is invoked |
| PostToolUse | Fired after a tool completes |
| PrePrompt | Fired before prompt generation |
| PostPrompt | Fired after prompt generation |
6. Dynamic Custom Errors (MyCodexError)
Define diagnostic error codes with actionable Call-To-Action (CTA) buttons that both developers and agents can execute.
import { z } from "zod";
import { MyCodexError } from "@mycodex/plugin";
const MissingEnvSchema = z.object({
key: z.string().describe("The missing environment variable name")
});
export const WorkspaceErrors = MyCodexError.create()
.addError("ENV_VARIABLE_MISSING", {
status: 400,
schema: MissingEnvSchema,
message: ({ issue }) =>
`Required environment variable "${issue?.key}" is not set.`,
cta: ({ issue }) => ({
description: "Set the missing environment variable in your config.",
commands: [
{
command: `MyCodex config set ${issue?.key}="<value>"`,
description: "Configure the environment key"
}
]
})
})
.build();
// Usage
throw new WorkspaceErrors({
code: "ENV_VARIABLE_MISSING",
issue: { key: "API_TOKEN" }
});Context API
All handlers receive a MyCodex context object with access to:
interface MyCodexContext {
MyCodex: {
config: { name: string; [key: string]: any };
env: { get(name: string): string | undefined };
workspace: MyCodexWorkspaceRuntime;
audit: { log(event: any): Promise<void> };
};
}Troubleshooting
"Cannot find module 'zod'"
Ensure zod is installed as a direct dependency:
bun add zodThe plugin lists zod as a peerDependency, so you must install it separately.
TypeScript errors with builders
This package requires TypeScript >=5.5. Upgrade if you see errors:
bun add -d typescript@latestCollection hooks not firing
Ensure the collection is registered in your workspace configuration:
// MyCodex.config.ts
import greetCollection from "./collections/greet";
export default {
collections: [greetCollection]
};View not appearing in workspace
Views must be explicitly enabled in the workspace settings. Check the MyCodex workspace preferences panel.
Building from Source
# Clone the repository
git clone https://github.com/tryMyCodex/MyCodex.git
cd MyCodex/@packages/plugin
# Install dependencies
bun install
# Build CJS, ESM, and DTS typings
bun run build
# Watch mode for development
bun run devLicense
MIT License — see LICENSE.
Copyright (c) 2026 tryMyCodex
