JS 实现入门
本教程将指导您如何使用JavaScript开发MCP客户端,实现与MCP服务器的无缝交互。
环境准备
依赖安装
# 使用npm
npm install axios eventsource
# 使用yarn
yarn add axios eventsource
项目结构
mcp-js-client/
├── src/
│ ├── mcpClient.js # MCP客户端核心代码
│ └── index.js # 入口文件
├── examples/ # 示例代码
│ ├── weatherQuery.js
│ └── documentAnalysis.js
├── package.json # 项目配置
└── README.md # 项目说明
基础客户端实现
创建基本客户端类
// mcpClient.js
const axios = require('axios');
/**
* MCP协议客户端实现
*/
class MCPClient {
/**
* 初始化MCP客户端
* @param {string} serverUrl - MCP服务器URL
* @param {string} [apiKey] - 可选的API密钥
*/
constructor(serverUrl, apiKey = null) {
this.serverUrl = serverUrl;
this.headers = {
'Content-Type': 'application/json'
};
if (apiKey) {
this.headers['Authorization'] = `Bearer ${apiKey}`;
}
// 创建axios实例
this.client = axios.create({
baseURL: serverUrl,
headers: this.headers,
timeout: 10000 // 默认超时时间10秒
});
}
/**
* 获取服务器信息
* @returns {Promise<Object>} 服务器信息
*/
async getServerInfo() {
try {
const response = await this.client.get('/');
return response.data;
} catch (error) {
this._handleError(error);
}
}
/**
* 获取资源列表
* @returns {Promise<Array>} 资源列表
*/
async listResources() {
try {
const response = await this.client.get('/resources');
return response.data;
} catch (error) {
this._handleError(error);
}
}
/**
* 获取特定资源详情
* @param {string} resourceName - 资源名称
* @returns {Promise<Object>} 资源详情
*/
async getResource(resourceName) {
try {
const response = await this.client.get(`/resources/${resourceName}`);
return response.data;
} catch (error) {
this._handleError(error);
}
}
/**
* 调用工具
* @param {string} toolName - 工具名称
* @param {Object} params - 工具参数
* @returns {Promise<Object>} 工具调用结果
*/
async callTool(toolName, params) {
try {
const response = await this.client.post(`/tools/${toolName}`, params);
return response.data;
} catch (error) {
this._handleError(error);
}
}
/**
* 发送提示词
* @param {string} resourceName - 资源名称
* @param {string} prompt - 提示词内容
* @param {Array} [history] - 对话历史
* @returns {Promise<Object>} 模型响应
*/
async sendPrompt(resourceName, prompt, history = null) {
const payload = {
prompt: prompt
};
if (history) {
payload.history = history;
}
try {
const response = await this.client.post(
`/resources/${resourceName}/prompt`,
payload
);
return response.data;
} catch (error) {
this._handleError(error);
}
}
/**
* 处理错误
* @private
* @param {Error} error - 错误对象
*/
_handleError(error) {
if (error.response) {
// 服务器返回了错误状态码
const { status, data } = error.response;
console.error(`服务器错误 (${status}):`, data);
throw new Error(`MCP服务器错误: ${status} - ${data.message || JSON.stringify(data)}`);
} else if (error.request) {
// 请求已发送但没有收到响应
console.error('无法连接到MCP服务器:', error.request);
throw new Error('无法连接到MCP服务器,请检查URL和网络连接');
} else {
// 请求设置过程中发生错误
console.error('请求错误:', error.message);
throw error;
}
}
}
module.exports = MCPClient;
高级功能实现
添加流式响应支持
// 添加EventSource依赖
const EventSource = require('eventsource');
/**
* 支持流式响应的MCP客户端
*/
class StreamingMCPClient extends MCPClient {
/**
* 流式发送提示词
* @param {string} resourceName - 资源名称
* @param {string} prompt - 提示词内容
* @param {Object} [options] - 选项
* @param {Array} [options.history] - 对话历史
* @param {function} [options.onMessage] - 消息回调
* @param {function} [options.onError] - 错误回调
* @param {function} [options.onComplete] - 完成回调
*/
streamPrompt(resourceName, prompt, options = {}) {
const { history = null, onMessage, onError, onComplete } = options;
// 构建查询参数
const params = new URLSearchParams({
prompt: prompt,
stream: true
});
if (history) {
params.append('history', JSON.stringify(history));
}
// 构建URL
const url = `${this.serverUrl}/resources/${resourceName}/prompt?${params}`;
// 创建EventSource
const eventSource = new EventSource(url, {
headers: this.headers
});
let fullText = '';
// 处理消息事件
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
fullText += data.text || '';
if (onMessage && typeof onMessage === 'function') {
onMessage(data.text, fullText);
}
} catch (error) {
console.error('处理消息时出错:', error);
}
};
// 处理错误事件
eventSource.onerror = (error) => {
eventSource.close();
if (onError && typeof onError === 'function') {
onError(error);
}
};
// 处理完成事件
eventSource.addEventListener('done', () => {
eventSource.close();
if (onComplete && typeof onComplete === 'function') {
onComplete(fullText);
}
});
// 返回关闭函数
return {
close: () => eventSource.close()
};
}
}
module.exports = {
MCPClient,
StreamingMCPClient
};