> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_13_plugin_system/13.1_plugin_interface_definition.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 13.1 Plugin Interface Definition

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

In the preceding chapters, we completed our analysis of OpenCode's core architecture. Starting from this chapter, we enter the **Ecosystem** section -- exploring how OpenCode achieves extensibility through mechanisms such as Plugins, Skills, and MCP.

The Plugin system is OpenCode's most central extension mechanism -- third-party developers can use Plugins to inject custom tools, modify LLM call parameters, intercept messages, listen to events, and even alter the Agent's behavior patterns. oh-my-opencode (covered in detail in Chapter 15) is built on top of the Plugin system.

## 13.1.1 Type Definitions in the @opencode-ai/plugin Package

The Plugin type definitions are located in the `packages/plugin/` package. This is a standalone npm package (`@opencode-ai/plugin`) that contains only TypeScript type definitions -- no runtime code. This design means Plugin developers only need to install this lightweight type package to get full type hinting support.

### The Plugin Type

The core Plugin type definition is remarkably concise:

```typescript
// packages/plugin/src/index.ts
export type Plugin = (input: PluginInput) => Promise<Hooks>
```

A Plugin is simply an async function -- it receives a `PluginInput` context and returns a `Hooks` object. This functional design is more flexible than a class-based approach: a Plugin can be a simple arrow function or a complex factory function.

### PluginInput: The Plugin Context

```typescript
export type PluginInput = {
  client: ReturnType<typeof createOpencodeClient>  // OpenCode SDK client
  project: Project                                   // Current project info
  directory: string                                  // Working directory
  worktree: string                                   // Git worktree root
  serverUrl: URL                                     // Server address
  $: BunShell                                        // Bun Shell (for executing commands)
}
```

| Field       | Type       | Purpose                                                 |
| ----------- | ---------- | ------------------------------------------------------- |
| `client`    | SDK Client | Interact with the OpenCode Server via API               |
| `project`   | `Project`  | Metadata about the current project (ID, VCS type, etc.) |
| `directory` | `string`   | Absolute path to the current working directory          |
| `worktree`  | `string`   | Absolute path to the Git repository root                |
| `serverUrl` | `URL`      | Address of the embedded HTTP Server                     |
| `$`         | `BunShell` | Bun's Shell API for executing system commands           |

`PluginInput` provides all the environment information a Plugin needs to run. The `client` field is especially important -- it allows a Plugin to interact with OpenCode through the standard API without needing to directly reference internal modules.

### The Hooks Interface

`Hooks` is the heart of the Plugin system -- it defines all the lifecycle hooks a Plugin can attach to:

```typescript
export interface Hooks {
  // Event listening
  event?: (input: { event: Event }) => Promise<void>

  // Configuration injection
  config?: (input: Config) => Promise<void>

  // Custom tool registration
  tool?: { [key: string]: ToolDefinition }

  // Authentication extension
  auth?: AuthHook

  // Message hook
  "chat.message"?: (input, output) => Promise<void>

  // LLM parameter hook
  "chat.params"?: (input, output) => Promise<void>

  // Request header hook
  "chat.headers"?: (input, output) => Promise<void>

  // Permission hook
  "permission.ask"?: (input, output) => Promise<void>

  // Pre-command execution hook
  "command.execute.before"?: (input, output) => Promise<void>

  // Pre/post tool execution hooks
  "tool.execute.before"?: (input, output) => Promise<void>
  "tool.execute.after"?: (input, output) => Promise<void>

  // Shell environment variable hook
  "shell.env"?: (input, output) => Promise<void>

  // Experimental: message list transformation
  "experimental.chat.messages.transform"?: (input, output) => Promise<void>

  // Experimental: system prompt transformation
  "experimental.chat.system.transform"?: (input, output) => Promise<void>

  // Experimental: compaction process hook
  "experimental.session.compacting"?: (input, output) => Promise<void>

  // Experimental: text completion hook
  "experimental.text.complete"?: (input, output) => Promise<void>
}
```

All hook functions follow a uniform `(input, output) => Promise<void>` signature pattern:

* **`input`**: Read-only context information (who triggered this hook and under what circumstances).
* **`output`**: A mutable output object (Plugins influence behavior by modifying this object).

This **input/output separation pattern** is the essence of OpenCode's Plugin design -- Plugins do not return results directly; instead, they mutate the `output` object in place. This allows multiple Plugins to process the same event in a chain: each Plugin continues modifying the `output` based on the modifications made by the previous Plugin.

## 13.1.2 ToolDefinition: Plugin Tool Definitions

Plugins can register custom tools through the `tool` hook:

```typescript
// packages/plugin/src/tool.ts
export type ToolDefinition = {
  description?: string
  parameters: Record<string, {
    type: string
    description?: string
    required?: boolean
    enum?: string[]
  }>
  execute: (args: any, context: ToolContext) => Promise<ToolResult>
}

export type ToolContext = {
  sessionID: string
  messageID: string
  abort: AbortSignal
}

export type ToolResult = {
  output: string
  title?: string
  metadata?: any
}
```

Plugin tool definitions are simpler than internal tool definitions -- they do not require Zod Schemas and use plain objects to describe parameters. Internally, OpenCode converts them to the standard `Tool.Info` format through the `fromPlugin()` adapter.

## 13.1.3 AuthHook: Authentication Extension

`AuthHook` is a special hook that allows Plugins to provide authentication methods for specific LLM Providers:

```typescript
export type AuthHook = {
  provider: string           // Associated Provider (e.g., "openai", "anthropic")
  loader?: (auth, provider) => Promise<Record<string, any>>
  methods: (OAuthMethod | ApiKeyMethod)[]
}
```

OpenCode ships with three built-in authentication Plugins:

* `CodexAuthPlugin`: Provides OAuth authentication for OpenAI Codex.
* `CopilotAuthPlugin`: Provides OAuth authentication for GitHub Copilot.
* `GitlabAuthPlugin`: Provides OAuth authentication for GitLab AI.

Two authentication modes are supported:

* **OAuth**: Authorization via browser redirect, returning a `url` and `callback`.
* **API Key**: Direct API key entry.

## 13.1.4 A Minimal Plugin Example

```typescript
import type { Plugin } from "@opencode-ai/plugin"

const myPlugin: Plugin = async (ctx) => {
  console.log(`Plugin loaded for project: ${ctx.project.id}`)

  return {
    // Register a custom tool
    tool: {
      "my-search": {
        description: "Search the web",
        parameters: {
          query: { type: "string", description: "Search query", required: true },
        },
        execute: async (args) => ({
          output: `Results for: ${args.query}`,
        }),
      },
    },

    // Modify LLM parameters
    "chat.params": async (input, output) => {
      output.temperature = 0.7  // Override the temperature setting
    },

    // Listen for events
    event: async ({ event }) => {
      if (event.type === "session.created") {
        console.log("New session:", event.properties.info.id)
      }
    },
  }
}

export default myPlugin
```

This example demonstrates three common Plugin capabilities: registering tools, modifying parameters, and listening for events. The Plugin function receives the project context and returns a Hooks object -- all hooks are optional, so you only need to implement the ones you need.
