Skip to content

插件系统

注册插件

typescript
// Server 端
const server = createAgentServer(config)
  .use(plugin1)
  .use(plugin2)

await server.start()

// Client 端
const client = createAgentClient(config)
  .use(plugin1)
  .use(plugin2)

const stream = await client.call('skill', params)

内置插件

插件用途使用场景
Tracing Plugin调用链追踪所有 Agent
Parasite PluginNAT 穿透代理本地 Agent
MCP PluginMCP 工具集成需要外部工具

快速使用

Tracing Plugin

typescript
import { createAgentServer, createTracingPlugin } from '@multi-agent/a2a'

const server = createAgentServer(config)
  .use(createTracingPlugin({
    provider: {
      reportTrace: async (record) => {
        console.log('Trace:', record)
      }
    }
  }))

创建自定义插件

Server 插件

typescript
const myPlugin = {
  hooks: {
    beforeHandler: async (ctx) => {
      console.log('Calling:', ctx.skill)
    },
    afterHandler: async (ctx, result) => {
      console.log('Result:', result)
    },
    onError: async (ctx, error) => {
      console.error('Error:', error)
    }
  }
}

server.use(myPlugin)

Client 插件

typescript
const myPlugin = {
  hooks: {
    beforeCall: async (ctx) => {
      ctx.metadata['x-custom'] = 'value'
    },
    afterCall: async (ctx, stream) => {
      console.log('Connected')
      return stream
    },
    onError: async (ctx, error) => {
      console.error('Error:', error)
    }
  }
}

client.use(myPlugin)

Hook 返回值

typescript
type HookResult = 'handled' | 'pass' | 'exit' | void

// 'handled' - 已处理,跳过默认处理
// 'pass'    - 未处理,继续默认处理(默认)
// 'exit'    - 已处理,退出消息循环

示例:

typescript
const plugin = {
  hooks: {
    onMessage: async (ctx) => {
      if (ctx.message.type === 'custom') {
        handleCustom(ctx.message)
        return 'handled'  // 跳过默认处理
      }
      return 'pass'  // 继续默认处理
    }
  }
}

执行顺序

请求到达

beforeMessage (plugin1 → plugin2 → ...)

onCall / onCancel

beforeHandler

handler 执行

afterHandler

afterMessage

响应发送

MIT Licensed