Plugin Development in Five Forms: From Minimal Extensions to Service Collaboration in Practice
This article breaks down plugin development into five practical forms: the minimal plugin, tool registration for model calls, event listening with automatic cleanup, configurable plugins, and reusable service providers. It explains how a host framework discovers plugins, creates context, injects capabilities, and manages lifecycle state, while each plugin handles its own business logic. You will learn the shared directory and config layout, how to define and validate tools, why event listeners need disposal through ctx.effect, how to keep config types and schemas in sync, and how services differ from tools. A pre-launch checklist helps you verify loading, input validation, timeouts, cleanup, and error handling before moving an experimental plugin into production.
1. The Overall Approach to Plugin Development
A plugin is essentially an extension module that is loaded by convention, runs according to a lifecycle, and collaborates through interfaces. The host framework is responsible for discovering plugins, creating context, injecting capabilities, and managing runtime state, while the plugin implements the specific business logic.
Compared with directly modifying the main program, a plugin mechanism usually offers the following advantages:
- Better isolation: Plugin code is separated from the core program, making it easier to debug and upgrade independently.
- Lower extension cost: Adding a capability does not require changing the main flow; you only register a new plugin entry.
- Clearer lifecycle: Stages such as initialization, running, and disposal can be handled separately.
- Stronger composability: Multiple plugins can collaborate through events, utilities, or services.
- On-demand enabling: A config file or override layer can control whether a plugin loads.
This article uses an abstracted plugin interface for explanation. In the examples, apply, inject, defineTool, ctx.effect, and the config pattern all represent common designs found in plugin frameworks. The actual import paths, startup commands, and config file formats differ between frameworks, so when applying these ideas you should follow the interface definitions of the specific framework.
2. A Unified Directory and Run Setup
To make it easy to switch between examples, you can place all code in a separate temporary plugin directory:
project-root/└── scratch-plugin/├── src/│ └── my-plugin.ts└── plugin-config.yml
Where:
src/my-plugin.ts: the plugin entry file;plugin-config.yml: declares how the plugin loads, its config options, or override rules;scratch-plugin: a standalone experiment directory that avoids modifying the host project source directly.
A generic override-layer config can be abstracted as:
plugins:- entry: ./scratch-plugin/src/my-plugin.tsenabled: true
At startup, load this directory using the host framework’s “development mode” or “override mode.” Since command-line arguments are not standardized across frameworks, it is recommended to wrap the startup command in a project script, for example:
{"scripts": {"dev:plugin": "your-runtime --config ./scratch-plugin/plugin-config.yml"}}
In practice, you should focus on confirming three things:
- Whether the plugin file is discovered by the host framework;
- Whether the object exported by the plugin matches the framework’s convention;
- Whether the injected capabilities the plugin depends on are already enabled in the host environment.
3. Example 1: The Minimal Plugin
The goal of a minimal plugin is not to implement complex business logic, but to verify that the entire loading chain works. It is useful for troubleshooting directory configuration, module exports, runtime versions, and plugin registration.
export default {name: 'hello-plugin',apply(ctx: any) {ctx.logger?.info('[hello-plugin] plugin loaded')}}
This example typically contains two core fields:
name: the plugin name, used for log identification, config references, and troubleshooting;apply: the plugin initialization function, called by the host framework after the plugin is loaded.
If you see a log similar to the following after running, the most basic loading flow is working:
[hello-plugin] plugin loaded
1. When to Use a Minimal Plugin
A minimal plugin is more than an introductory example; it also has value in real projects:
- Checking whether a plugin is loaded correctly;
- Verifying that the current runtime provides the expected context;
- Reserving a unified entry point for later extensions;
- Serving as a plugin template to quickly copy out new feature modules.
2. Development Recommendations
The initialization stage should avoid running time-consuming tasks. A safer approach is to:
- Perform only necessary parameter checks;
- Avoid accessing resources at the module top level that may not yet be initialized;
- Move asynchronous operations into explicit lifecycle stages;
- Record the plugin name and key states through structured logging.
4. Example 2: Exposing Tool Capabilities to the Model
When a plugin needs to let the model invoke a capability, it can do so through the tool registration mechanism. For example, a plugin can provide text statistics, data queries, file parsing, or business rule calculations.
export default {name: 'text-tools-plugin',inject: ['tools'],apply(ctx: any) {const tools = ctx.toolstools.defineTool({name: 'count-words',description: 'Count the number of words in the input text',inputSchema: {type: 'object',properties: {text: {type: 'string',description: 'The text to analyze'}},required: ['text']},async execute(input: { text: string }) {if (!input || typeof input.text !== 'string') {throw new Error('text must be a string')}const words = input.text.trim().split(/\s+/).filter(Boolean)return {count: words.length}}})}}
1. Key Parts of a Tool Definition
A tool that can be called by the model usually needs to specify the following:
- Name: should be short, stable, and express an action;
- Description: helps the caller understand the tool’s purpose;
- Input structure: describes parameters using a schema or type definition;
- Required fields: avoids missing necessary information at call time;
- Execute function: performs the actual business processing;
- Return structure: use a stable, serializable data format whenever possible.
2. Input Validation Cannot Be Skipped
Model-generated arguments do not always match expectations, so the tool must still perform a second round of validation internally. At minimum, check:
- Whether the argument object exists;
- Whether field types are correct;
- Whether string length exceeds the limit;
- Whether numeric values fall within the allowed range;
- Whether enum values belong to a valid set.
For tools that involve files, networks, databases, or system commands, you should also add permission control, timeout limits, and error redaction to prevent the tool from becoming an entry point for privilege escalation.
3. Designing Tool Return Results
Return values should be structured as much as possible, for example:
{success: true,data: {count: 12}}
On a business failure, you can also use a unified format:
{success: false,error: {code: 'INVALID_INPUT',message: 'Input content cannot be empty'}}
This makes it easier for the caller to distinguish between “the tool executed successfully but the result is empty” and “the tool itself failed to execute.”
5. Example 3: Event Listening and Automatic Cleanup
An event plugin is suited to inserting logic when the framework reaches a specific stage, such as the start of a request, the end of a task, the completion of a model response, or a change in session state.
export default {name: 'lifecycle-observer',apply(ctx: any) {const dispose = ctx.on?.('task:completed', (event: any) => {ctx.logger?.info('[lifecycle-observer] task completed', {taskId: event?.taskId})})if (typeof dispose === 'function') {ctx.effect(dispose)}}}
1. Why Automatic Cleanup Is Needed
Event listeners usually persist. If a plugin is reloaded, hot-updated, or dynamically unloaded while old listeners are not removed, you may end up with:
- The same event handled repeatedly;
- Log output duplicated;
- Memory growing continuously;
- Stale objects still being referenced;
- Old logic still running after the plugin is unloaded.
Therefore, when registering an event, you should also keep the method that cancels the listener and hand it to the lifecycle manager.
2. Typical Uses of ctx.effect
ctx.effect can be understood as “register a disposal action.” Besides canceling event listeners, it can also be used for:
ctx.effect(() => timer && clearInterval(timer))ctx.effect(() => socket?.close())ctx.effect(() => removeTemporaryFile())
Example:
export default {name: 'periodic-checker',apply(ctx: any) {const timer = setInterval(() => {ctx.logger?.debug('[periodic-checker] checking')}, 5000)ctx.effect(() => {clearInterval(timer)ctx.logger?.info('[periodic-checker] timer disposed')})}}
Any timers, connections, listeners, and temporary resources created by a plugin should have clearly defined cleanup logic.
6. Example 4: A Plugin with Configuration
When a plugin’s behavior needs to be adjusted by the user, the configuration should be separated from the code. Typical configuration includes switches, thresholds, timeouts, output levels, and business policies.
type PluginConfig = {enabled: booleanprefix: stringmaxLength: number}const configSchema = {type: 'object',properties: {enabled: { type: 'boolean', default: true },prefix: { type: 'string', default: '[plugin]' },maxLength: { type: 'number', minimum: 1, default: 200 }},required: ['enabled', 'prefix', 'maxLength']}export default {name: 'configurable-plugin',configSchema,apply(ctx: any, config: PluginConfig) {if (!config.enabled) {ctx.logger?.info('configurable-plugin is disabled')return}ctx.on?.('message:received', (message: any) => {const text = String(message?.text ?? '')if (text.length > config.maxLength) {ctx.logger?.warn(`${config.prefix} message exceeds configured length`)}})}}
The config file can be written as:
plugins:- entry: ./scratch-plugin/src/my-plugin.tsconfig:enabled: trueprefix: "[checker]"maxLength: 500
1. Keep Types and Schemas Consistent
The config type is used for static checks during development, while the schema is used for validation at runtime, and the two should be maintained in sync. If the type allows a string but the schema only allows a number, the development code and the actual runtime result will diverge.
2. Set Reasonable Defaults
Defaults should satisfy the “works out of the box” principle while not introducing obvious risk. For example:
- Enable read-only capabilities by default;
- Disable high-risk operations by default;
- Limit input length by default;
- Set a reasonable timeout by default;
- Use the lowest privilege by default.
3. Behavior After Configuration Changes
If the framework supports dynamic config updates, the plugin also needs to consider hot config updates. For configuration that cannot be safely modified at runtime, the documentation should explicitly require restarting the plugin or reloading the runtime environment.
7. Example 5: Providing a Reusable Service
Tools usually target the model or external callers, whereas services are better suited for direct calls from other plugins. A service can encapsulate common capabilities such as caching, format conversion, rule calculation, and state management.
class TextService {constructor(private ctx: any) {}normalize(value: string) {return value.trim().replace(/\s+/g, ' ')}summarize(value: string, limit = 100) {const text = this.normalize(value)return text.length <= limit? text: `${text.slice(0, limit)}...`}}export default {name: 'text-service-provider',apply(ctx: any) {ctx.provide?.('textService', new TextService(ctx))}}
Other plugins can use it through injection:
export default {name: 'text-service-consumer',inject: ['textService'],apply(ctx: any) {const result = ctx.textService.summarize('This is a piece of text content that needs unified processing.',10)ctx.logger?.info(result)}}
1. Service Design Principles
A service should keep a single responsibility as much as possible:
- One service solves one relatively stable class of problem;
- Do not implicitly modify global state inside the service;
- Expose clear methods and parameters;
- Use stable exceptions or result structures for errors;
- Provide a version compatibility strategy when necessary.
2. The Difference Between Services and Tools
You can distinguish them by caller and purpose:
| Type | Primary Caller | Typical Use |
|---|---|---|
| Tool | Model, task executor, or external request | Perform a specific action |
| Service | Other plugins or internal modules | Provide reusable programmatic capability |
| Event listener | The plugin itself | Run logic at a specific lifecycle point |
In real projects, a single plugin can provide both services and tools, but you should avoid piling all functionality into one entry point.
8. How to Choose Among the Five Plugin Forms
You can choose the plugin form with the following approach:
- You only want to confirm loading succeeded: use a minimal plugin;
- You need the model to perform an action: register a tool;
- You need to respond to a framework runtime point: listen for events;
- You want the user to adjust behavior: add a config type and config schema;
- You need other plugins to reuse a capability: provide a service;
- Multiple needs exist at once: split responsibilities, then compose them through services or events.
9. Pre-Launch Checklist
Before using an experimental plugin in a production environment, it is recommended to complete the following checks:
- Is the plugin name unique and stable;
- Is all external input validated;
- Do asynchronous tasks have timeouts;
- Can events, timers, and connections be disposed;
- Does the configuration have defaults and validity checks;
- Do error logs avoid leaking sensitive information;
- Do service interfaces have a clear return structure;
- Do tools limit permissions and resource scope;
- Does reloading the plugin produce side effects;
- Can a clear error be given when the host environment is unavailable.
These five basic forms cover most plugin development scenarios. It is recommended to first use a minimal plugin to verify the loading chain, then gradually add tools, events, configuration, and service capabilities. This reduces troubleshooting costs while keeping the plugin structure clear, maintainable, and extensible.
