npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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/plugin

Peer Dependencies

This package requires zod@^4.0.0 as a peer dependency:

bun add zod

Make 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 zod

The 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@latest

Collection 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 dev

License

MIT License — see LICENSE.

Copyright (c) 2026 tryMyCodex


Links