LangChain MCP适配器
用于将模型上下文协议(MCP)服务器与LangChain应用程序集成的Node.js适配器。
概述
该项目提供了一种简单有效的方法将MCP服务器连接到LangChain,使您能够在LangChain工作流中无缝使用MCP工具。
安装
npm install依赖项
此项目使用最新版本的:
@modelcontextprotocol/sdk(^1.22.0)-用于客户端连接的MCP SDK@langchain/langgraph(^1.0.2)-用于工作流编排的LangGraph@langchain/mcp-adapters(^1.0.0)-官方LangChain MCP适配器@langchain/openai(^1.1.2)-LangChain的OpenAI集成
用法
基础示例
const { LangChainMCPAdapter } = require("./index.js");
async function main() {
const adapter = new LangChainMCPAdapter();
// Connect to an MCP server
await adapter.connect("npx", ["-y", "@modelcontextprotocol/server-memory"]);
// Get LangChain-compatible tools
const tools = await adapter.getLangChainTools();
// Get a model with tools bound
const model = await adapter.getModelWithTools({
model: "gpt-4o-mini",
temperature: 0,
});
// Use the model
const response = await model.invoke("Your query here");
console.log(response.content);
// Clean up
await adapter.close();
}
main().catch(console.error);运行示例
设置您的OpenAI API密钥:
export OPENAI_API_KEY="your-api-key-here"运行示例:
node example.jsAPI 参考
LangChainMCPAdapter
用于连接MCP服务器和将工具转换为LangChain格式的主类。
方法
connect(command, args)
连接到MCP服务器。
- 参数:
- command (string):运行MCP服务器的命令 - args (string\[\]):命令的参数
- 退货: 承诺
listTools()
列出MCP服务器上的所有可用工具。
- 退货: 承诺 -MCP工具定义数组
getLangChainTools()
将MCP工具转换为与LangChain兼容的工具。
- 退货: 承诺 -LangChain工具数组
getModelWithTools(config)
获取绑定了MCP工具的ChatOpenAI实例。
- 参数:
- config (对象):OpenAI配置 - model (string):型号名称(默认:“gpt-4o-mini”) - temperature (数字):温度设置(默认值:0)
- 退货: 承诺 -带工具的ChatOpenAI实例
close()
关闭与MCP服务器的连接。
- 退货: 承诺
环境变量
OPENAI_API_KEY:您的OpenAI API密钥(使用ChatOpenAI时需要)
MCP服务器示例
您可以连接到各种MCP服务器:
- 内存服务器:
npx -y @modelcontextprotocol/server-memory - 文件系统服务器:
npx -y @modelcontextprotocol/server-filesystem /path/to/directory - SQLite服务器:
npx -y @modelcontextprotocol/server-sqlite /path/to/database.db
贡献
欢迎投稿!请随时提交拉取请求。
许可证
ISC
