OpenAI代理MCP客户端
一个基于TypeScript的客户端,用于使用OpenAI的代理SDK与模型上下文协议(MCP)服务器进行交互。此客户端提供CLI和交互模式,用于查询具有持久会话内存的MCP服务器。
概述
本项目演示了如何:
- 连接到MCP服务器(SSE传输)
- 构建使用MCP工具的OpenAI代理
- 在多个回合中维护对话历史记录
- 支持单查询和交互模式
先决条件
- Node.js 18+(用于顶级等待支持)
- npm或纱线
- OpenAI API密钥(在这里买一个)
- 访问MCP服务器(SSE传输)或凭据(如果需要身份验证)
安装
git clone
cd mcpclient_ts
npm install构建
npm run build配置
创建一个 .env 项目根目录中的文件:
# Required
OPENAI_API_KEY=sk-...
# MCP Server Configuration
MCP_SERVER_URL=https://your-mcp-server.com/sse
MCP_SERVER_NAME=Your Server Name
# Optional: Authentication headers
USER_EMAIL=user@example.com
AUTHORIZATION_TOKEN=your_auth_token_here环境变量
| 变量 | 描述 | 必填 | 示例 |
|---|---|---|---|
OPENAI_API_KEY | OpenAI API密钥 | ✅ | sk-... |
MCP_SERVER_URL | MCP服务器SSE端点 | ✅ | https://mcp.example.com/sse |
MCP_SERVER_NAME | 服务器的显示名称 | ❌ | My Server |
USER_EMAIL | 请求的电子邮件标题(如果需要) | ❌ | user@example.com |
AUTHORIZATION_TOKEN | 用于身份验证的承载令牌 | ❌ | your_token |
用法
单查询模式
运行一个查询并退出:
npm start "What tools are available?"
npm start "Generate a summary of recent items"交互模式
使用持久内存启动交互式聊天会话:
npm start然后键入您的查询:
You: What tools do you have?
Assistant: [response with conversation context]
You: Can you use the previous tools to help me?
Assistant: [response remembering previous conversation]
You: exit项目结构
mcpclient_ts/
├── src/
│ └── main.ts # Main agent implementation
├── dist/ # Compiled JavaScript (generated)
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── .env # Environment variables (create this)
└── README.md # This file建筑
关键组件
内存会话
- 存储会话历史进程内存
- 自动管理多个回合的上下文
- 对开发和测试有用
MCPServerSSE
- 使用服务器发送事件传输连接到MCP服务器
- 注意:SSE已被弃用,取而代之的是Streamable HTTP;使用
MCPServerStreamableHttp对于新的实现 - 缓存性能工具列表
代理
- AI模型的名称和说明
- 连接到MCP服务器以访问工具
- 使用OpenAI
run推理功能
数据流
User Input
↓
Agent (with MCP tools)
↓
MCP Server (via SSE)
↓
Tool Results
↓
OpenAI Model
↓
Response
↓
MemorySession (stores conversation)定制
更改代理说明
在 src/main.ts,修改 instructions 字段:
const agent = new Agent({
name: 'My Custom Agent',
instructions: 'You are a helpful assistant that...', // Customize here
mcpServers: [mcpServer],
});使用OpenAI对话API进行持久存储
替换 MemorySession 随着 OpenAIConversationsSession:
import { OpenAIConversationsSession } from '@openai/agents';
const session = new OpenAIConversationsSession({
conversationId: 'conv_123', // Optional: reuse existing conversation
});连接多个MCP服务器
import { connectMcpServers } from '@openai/agents';
const servers = [
new MCPServerSSE({ url: 'https://server1.com/sse', name: 'Server 1' }),
new MCPServerSSE({ url: 'https://server2.com/sse', name: 'Server 2' }),
];
const mcpServers = await connectMcpServers(servers, { connectInParallel: true });
const agent = new Agent({
name: 'Multi-Server Agent',
instructions: 'Use tools from multiple servers to answer questions.',
mcpServers: mcpServers.active,
});使用流式HTTP而不是SSE
为了获得更好的性能和更新的MCP实现:
import { MCPServerStreamableHttp } from '@openai/agents';
const mcpServer = new MCPServerStreamableHttp({
url: process.env.MCP_SERVER_URL || '',
name: 'Backend',
requestInit: {
headers: {
'X-User-Email': process.env.USER_EMAIL || '',
'Authorization': `Bearer ${process.env.AUTHORIZATION_TOKEN || ''}`,
},
},
});筛选可用工具
import { createMCPToolStaticFilter } from '@openai/agents';
const mcpServer = new MCPServerSSE({
url: process.env.MCP_SERVER_URL || '',
name: 'Backend',
toolFilter: createMCPToolStaticFilter({
allowed: ['safe_tool', 'read_only_tool'],
blocked: ['delete_tool', 'admin_tool'],
}),
requestInit: { /* ... */ },
});脚本
# Build TypeScript to JavaScript
npm run build
# Run in production
npm start [query]
# Build and run
npm run build && npm startAPI 参考
内存会话
将对话历史记录存储在进程内存中:
const session = new MemorySession({
sessionId: 'session-123', // Optional: stable identifier
initialItems: [], // Optional: seed with existing history
});
// Get all items
const history = await session.getItems();
// Add items
await session.addItems(items);
// Remove last item
await session.popItem();
// Clear all
await session.clearSession();run()选项
const result = await run(agent, userInput, {
session: mySession, // Add conversation memory
stream: true, // Stream responses (requires OpenAI Responses API)
});故障排除
“找不到模块‘dist/main.js’”
首先构建TypeScript:
npm run build“只允许使用顶级'wait'表达式…”
更新 tsconfig.json:
{
"compilerOptions": {
"module": "esnext",
"target": "es2022"
}
}MCP服务器连接失败
- 验证
MCP_SERVER_URL在.env - 检查身份验证标头(
USER_EMAIL,AUTHORIZATION_TOKEN) - 测试服务器可用性:
curl https://your-mcp-server.com/sse
代理不记得上下文
确保你通过 { session } 到 run() 功能在 chat() 功能。
参考文献
许可证
麻省理工学院
贡献
欢迎投稿!请随时提交问题和拉取请求。
