import Anthropic from '@anthropic-ai/sdk';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
const anthropic = new Anthropic();
// 初始化 MCP Client
async function createMcpClient() {
const transport = new SSEClientTransport(
new URL('https://mcp.chainstream.io/sse'),
{
requestInit: {
headers: {
'Authorization': `Bearer ${process.env.CHAINSTREAM_ACCESS_TOKEN}`
}
}
}
);
const client = new Client({
name: 'custom-agent',
version: '1.0.0'
});
await client.connect(transport);
return client;
}
async function chat(userMessage) {
const mcp = await createMcpClient();
// 获取可用工具
const { tools } = await mcp.listTools();
// 转换为 Anthropic 格式
const anthropicTools = tools.map(tool => ({
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema
}));
// 调用 Claude
let response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
tools: anthropicTools,
messages: [{ role: 'user', content: userMessage }]
});
// 处理工具调用
while (response.stop_reason === 'tool_use') {
const toolUse = response.content.find(c => c.type === 'tool_use');
// 调用 MCP 工具
const toolResult = await mcp.callTool({
name: toolUse.name,
arguments: toolUse.input
});
// 带工具结果继续对话
response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
tools: anthropicTools,
messages: [
{ role: 'user', content: userMessage },
{ role: 'assistant', content: response.content },
{
role: 'user',
content: [{
type: 'tool_result',
tool_use_id: toolUse.id,
content: JSON.stringify(toolResult.content)
}]
}
]
});
}
await mcp.close();
return response.content.find(c => c.type === 'text')?.text;
}
// 使用示例
const result = await chat('查看 Ethereum 上的 ETH 价格');
console.log(result);