Composio中介者模式:简化对象间通信的协调者

Composio中介者模式:简化对象间通信的协调者

【免费下载链接】composio Composio equips agents with well-crafted tools empowering them to tackle complex tasks 【免费下载链接】composio 项目地址: https://gitcode.com/GitHub_Trending/co/composio

在复杂的应用系统中,多个对象之间的直接通信往往会导致代码耦合度高、维护困难的问题。当系统中的对象数量增加时,对象间的交互关系会变得错综复杂,形成一个难以理解和修改的"蜘蛛网"。Composio通过实现中介者模式(Mediator Pattern),为解决这一问题提供了优雅的解决方案。

中介者模式简介

中介者模式是一种行为设计模式,它通过引入一个中介者对象(Mediator)来封装一系列对象之间的交互。原本相互依赖的对象不再直接通信,而是通过中介者进行间接通信,从而降低了对象间的耦合度,提高了系统的可维护性和可扩展性。

项目logo

在Composio中,Model Control Protocol(MCP,模型控制协议)充当了这一中介者角色,它作为AI模型与外部工具之间的桥梁,协调各方之间的通信,使得系统更加灵活和易于管理。

Composio中的MCP中介者实现

Composio的MCP模块是中介者模式的典型实现,它封装了AI模型与各种外部工具之间的复杂交互逻辑。

MCP类的核心功能

MCP类位于ts/packages/core/src/models/MCP.ts文件中,它提供了一系列方法来管理MCP服务器,包括创建、更新、删除服务器,以及获取服务器信息和连接状态等。

export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown>> {
  private client: ComposioClient;
  private toolkits: Toolkits;
  protected provider: TProvider;

  // 创建MCP服务器
  async create(
    name: string,
    serverConfig: Array<{
      authConfigId: string;
      allowedTools: string[];
    }>,
    options: {
      isChatAuth?: boolean;
    }
  ): Promise<McpServerCreateResponse<typeof this.TMcpResponse>> {
    // 实现细节
  }

  // 获取服务器URL
  async getServer(
    serverId: string,
    userId: string,
    options?: {
      limitTools?: string[];
      isChatAuth?: boolean;
    }
  ): Promise<typeof this.TMcpResponse> {
    // 实现细节
  }

  // 其他方法...
}

MCP服务器的创建与管理

MCP服务器作为中介者的具体实例,负责协调特定工具集与AI模型之间的通信。创建MCP服务器的过程如下:

// 创建MCP服务器示例
const server = await composio.mcp.create("personal-mcp-server", [
  {
    authConfigId: "ac_xyz",
    allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
  }
], {
  isChatAuth: true
});

// 获取服务器URL
const urls = await server.getServer({
  userId: "user123"
});

中介者模式解决的核心问题

降低系统耦合度

在传统的直接通信模式中,每个AI模型需要了解各种工具的接口和通信方式,导致系统耦合度高,维护困难。

mermaid

通过引入MCP作为中介者,AI模型只需与MCP进行通信,而不必了解具体工具的实现细节,从而显著降低了系统的耦合度。

mermaid

集中控制交互逻辑

MCP将原本分散在各个对象之间的交互逻辑集中管理,使得系统行为更加清晰可控。如ts/packages/core/src/models/MCP.ts中的getUserConnectionStatus方法所示,MCP统一处理用户与多个工具的连接状态检查:

async getUserConnectionStatus(
  userId: string,
  serverId: string
): Promise<McpUserConnectionStatus> {
  const serverDetails = await this.get(serverId);
  
  // 检查用户与所有工具的连接状态
  const connectedAccounts = await this.client.connectedAccounts.list({
    user_ids: [userId],
    toolkit_slugs: serverDetails.toolkits.map(toolkit => toolkit.toLowerCase()),
    statuses: ['ACTIVE'],
  });
  
  // 处理连接状态并返回结果
  // ...
}

MCP中介者的工作流程

MCP中介者的工作流程可以分为以下几个主要步骤:

  1. 服务器创建:根据应用需求创建MCP服务器,配置所需的工具集和认证信息。
  2. 用户连接:用户通过MCP服务器建立与AI模型的连接。
  3. 工具调用:AI模型通过MCP服务器间接调用各种工具。
  4. 结果返回:MCP服务器将工具执行结果返回给AI模型。

MCP工作流程

MCP服务器URL生成

MCP服务器URL的生成是连接AI模型与工具的关键步骤,相关实现位于ts/packages/core/src/models/MCP.tsgetServer方法:

async getServer(
  serverId: string,
  userId: string,
  options?: {
    limitTools?: string[];
    isChatAuth?: boolean;
  }
): Promise<typeof this.TMcpResponse> {
  // 获取服务器详情
  const serverDetails = await this.get(serverId);
  
  // 生成URL
  let data;
  try {
    data = await this.client.mcp.generate.url({
      user_ids: [userId],
      connected_account_ids: [],
      mcp_server_id: serverId,
      managed_auth_by_composio: options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false,
    });
  } catch (error) {
    throw new ValidationError('Failed to generate MCP server URL', {
      cause: error,
    });
  }
  
  // 转换响应格式并返回
  const camelCaseData = transformMcpGenerateUrlResponse(data);
  return this.wrapMcpServerResponse(
    camelCaseData,
    serverDetails.name,
    connectedAccountIds,
    [userId],
    toolkits
  );
}

实际应用场景

多工具协同工作

MCP中介者特别适合需要多个工具协同工作的场景。例如,一个需要同时使用Gmail和Slack的AI助手:

// 创建包含Gmail和Slack工具的MCP服务器
const server = await composio.mcp.create("email-slack-assistant", [
  {
    authConfigId: "ac_gmail",
    allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
  },
  {
    authConfigId: "ac_slack",
    allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
  }
], {
  isChatAuth: true
});

// 检查用户连接状态
const connectionStatus = await composio.mcp.getUserConnectionStatus('user123', server.id);

if (connectionStatus.connected) {
  // 获取服务器URL并与AI模型连接
  const urls = await server.getServer({ userId: "user123" });
  // AI模型使用urls与MCP服务器通信,间接调用Gmail和Slack工具
}

动态工具集管理

MCP中介者支持动态更新工具集,无需修改AI模型代码:

// 更新MCP服务器,添加新的工具
const updatedServer = await composio.mcp.update(
  server.id,
  "email-slack-calendar-assistant",
  [
    {
      toolkit: "GMAIL",
      authConfigId: "ac_gmail",
      allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"],
    },
    {
      toolkit: "SLACK",
      authConfigId: "ac_slack",
      allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"],
    },
    {
      toolkit: "GOOGLE_CALENDAR",
      authConfigId: "ac_calendar",
      allowedTools: ["CALENDAR_CREATE_EVENT", "CALENDAR_LIST_EVENTS"],
    },
  ],
  {
    isChatAuth: true,
  }
);

中介者模式的优缺点

优点

  1. 降低耦合度:通过引入中介者,减少了对象之间的直接依赖。
  2. 集中控制交互:将分散的交互逻辑集中在中介者中,便于维护和扩展。
  3. 简化对象职责:对象无需关心与其他对象的交互细节,只需专注于自身功能。
  4. 提高可重用性:中介者和参与交互的对象都可以独立地被重用。

缺点

  1. 中介者可能变得复杂:随着系统扩展,中介者可能会变得庞大复杂,难以维护。
  2. 单点故障风险:中介者成为系统的关键组件,一旦出现问题,可能影响整个系统。

最佳实践与注意事项

MCP服务器命名规范

为MCP服务器选择清晰、描述性的名称,有助于提高代码可读性和可维护性:

// 推荐的命名方式
'production-email-assistant';
'customer-support-toolkit';
'marketing-automation-server';

// 不推荐的命名方式
'server1';
'myServer';
'mcp';

工具权限控制

在配置MCP服务器时,应明确指定允许使用的工具,遵循最小权限原则:

// 推荐:明确指定允许的工具
{
  toolkit: "github",
  allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
}

// 不推荐:允许所有工具
{
  toolkit: "github"
  // 未指定allowedTools意味着允许使用所有工具
}

连接状态检查

在使用MCP服务器之前,始终检查用户的连接状态:

// 检查用户是否已连接所有必要的工具
const connectionStatus = await composio.mcp.getUserConnectionStatus(userId, serverId);

if (!connectionStatus.connected) {
  // 处理未连接的情况
  Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
    if (!status.connected) {
      console.log(`User needs to connect ${toolkit}`);
      // 引导用户连接缺失的工具
    }
  });
}

总结

Composio的MCP模块通过实现中介者模式,有效地解决了AI模型与外部工具之间通信的复杂性问题。它作为中介者,协调各方之间的交互,降低了系统耦合度,提高了代码的可维护性和可扩展性。

通过使用MCP中介者,开发者可以更专注于业务逻辑的实现,而不必关心复杂的工具集成细节。无论是简单的工具调用还是复杂的多工具协同工作,MCP都能提供一致、高效的解决方案。

随着AI技术的不断发展,中介者模式在AI应用开发中的重要性将日益凸显。Composio的MCP实现为我们展示了如何通过设计模式来解决复杂系统中的实际问题,为构建灵活、可扩展的AI应用提供了有力支持。

更多关于MCP的详细信息,请参考官方文档:ts/docs/api/mcp.md

【免费下载链接】composio Composio equips agents with well-crafted tools empowering them to tackle complex tasks 【免费下载链接】composio 项目地址: https://gitcode.com/GitHub_Trending/co/composio

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值