内容
# 简单的 MCP 客户端与 LangGraph 代理
一个轻量级的多服务器 MCP(模型上下文协议)客户端实现,使用 LangGraph 代理和 Express.js 以及 TypeScript。
## 特性
- 使用 TypeScript 的 Express.js 服务器
- 用于处理对话的 LangGraph 代理
- 用于工具集成的 MCP 客户端
- 流式响应
## 设置
1. 克隆仓库
2. 安装依赖:
`npm install`
3. 创建一个 `.env` 文件,包含以下变量:
```
PORT=3000
NODE_ENV=development
CORS_ORIGIN=*
ANTHROPIC_API_KEY=your_anthropic_api_key
```
4. 构建并启动服务器:
`npm run buildnpm start`
## API 端点
### 初始化聊天
```
GET /api/chat/init
```
### 生成聊天
```
POST /api/chat
```
请求体:
```json
{
"input": "Hello, how can you help me?",
"characterId": "character_123",
"llmConfig": {
"model": "claude-3-opus-20240229",
"verbose": true
},
"chatHistory": [],
"mcpServers": [
{
"name": "weather-service",
"version": "1.0",
"url": "https://example-mcp-server.com",
"key": "optional_api_key"
}
]
}
```
### 关闭聊天
```
GET /api/chat/close
```
## MCP 集成
服务器连接到请求中指定的 MCP 服务器,并检索可以被 LangGraph 代理使用的可用工具。
## 开发
运行带有自动重载的开发服务器:
```
npm run dev
```
## 示例用法
```typescript
// 发送消息并流式获取响应
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
input: "What's the weather in New York?",
characterId: "agent1",
chatHistory: [],
mcpServers: [
{
name: "weather-service",
version: "1.0",
url: "https://my-mcp-server.com",
},
],
}),
});
// 读取流式响应
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = new TextDecoder().decode(value);
const events = text.split("\n\n").filter(Boolean);
for (const event of events) {
const data = JSON.parse(event);
console.log(data);
}
}
```