langchain-mcp-adapters:让langchain开发者轻松使用MCP工具

昨天,笔者介绍了一个MCP Client的库,有开发者询问有无简单js版本的MCP Client。

6行代码让你的应用也能调用Mcp工具!

实际上,LangChain 在三月份就已经开发了适配MCP的库mcp-adapters,支持python(langchain-mcp-adapters)和javascript(@langchain/mcp-adapters)。

其中,js版本的 @langchain/mcp-adapters 库可以无缝将MCP工具集成到 LangChain.js 和 LangGraph.js 应用中。

该库特性包括:

  1. MCP 工具兼容性转换: 自动将 MCP 工具接口转换为 LangChain.js 和 LangGraph.js 可直接使用的格式,无需手动适配。
  2. 多服务器连接与管理: 支持同时连接和管理来自多个不同 MCP 服务器的工具集,可通过编程方式或 JSON 文件进行便捷配置。
  3. 灵活的传输协议支持: 提供对标准输入/输出(stdio)用于本地工具和服务器发送事件(SSE)用于远程工具的连接支持,并包含可配置的自动重连策略及对 SSE 自定义头(如认证)的支持。
  4. 富内容响应处理: 能够处理并传递 MCP 工具返回的多样化内容格式,包括纯文本、Base64 编码的图像及其他嵌入式资源。

使用上也比较简单,

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { loadMcpTools } from "@langchain/mcp-adapters";

// Initialize the ChatOpenAI model
const model = new ChatOpenAI({ modelName: "gpt-4" });

// Automatically starts and connects to a MCP reference server
const transport = new StdioClientTransport({
command"npx",
  args: ["-y""@modelcontextprotocol/server-math"],
});

// Initialize the client
const client = new Client({
  name: "math-client",
  version: "1.0.0",
});

try {
  // Connect to the transport
  await client.connect(transport);

  // Get tools with custom configuration
  const tools = await loadMcpTools("math", client, {
    // Whether to throw errors if a tool fails to load (optional, default: true)
    throwOnLoadError: true,
    // Whether to prefix tool names with the server name (optional, default: false)
    prefixToolNameWithServerName: false,
    // Optional additional prefix for tool names (optional, default: "")
    additionalToolNamePrefix: "",
  });

  // Create and run the agent
  const agent = createReactAgent({ llm: model, tools });
  const agentResponse = await agent.invoke({
    messages: [{ role: "user", content: "what's (3 + 5) x 12?" }],
  });
  console.log(agentResponse);
} catch (e) {
  console.error(e);
} finally {
  // Clean up connection
  await client.close();
}

感兴趣的朋友快去试试吧。

地址:https://github.com/langchain-ai/langchainjs-mcp-adapters

实际上这类方案很多,更新迭代也非常快,开发者只需要选择自己顺手的即可。

具体也可以在此查看,涵盖官方推荐的mcp server以及相关框架及学习资源:

https://github.com/modelcontextprotocol/servers

公众号回复“进群”入群讨论。

(文:AI工程化)

发表评论

×

下载每时AI手机APP

 

和大家一起交流AI最新资讯!

立即前往