使用说明
@metaid/mcp客户端
MetaID MCP(模型上下文协议)服务器的官方Types/JavaScript客户端
MetaID MCP客户端是一个功能齐全的Types/JavaScript客户端库,用于连接和调用MetaID MCP服务器。支持Node.js和浏览器环境,具有完整的类型定义和基于Promise-based异步API。
默认服务URL: https://api.metaid.io/mcp-service
✨ 特性
- 🚀 零配置 -开箱即用,自动连接到在线服务
- 📘 TypeScript优先 -完整的类型定义和智能提示
- 🔌 多环境支持 -Node.js、浏览器、React、Vue等。
- ⚡ 承诺API -现代异步编程体验
- 🔄 苏格兰和南方能源公司运输 -实时双向通信
- 🎯 命令行工具 -用于测试和调试的内置CLI工具
- 📦 轻量级 -依赖性最小,占地面积小
📦 安装
npm
npm install @metaid/metaid-mcp-client
纱线
yarn add @metaid/metaid-mcp-client
pnpm
pnpm add @metaid/metaid-mcp-client
🚀 快速开始
基本用法
import { MCPClient } from '@metaid/metaid-mcp-client';
// Create client (auto-connects to online service)
const client = new MCPClient();
// Connect and initialize
await client.connect();
await client.initialize({
name: 'my-app',
version: '1.0.0',
});
// Call a tool
const result = await client.callTool('hello_world', {
name: 'MetaID'
});
console.log(result);
完整示例
import { MCPClient } from '@metaid/metaid-mcp-client';
async function main() {
// Create client instance
const client = new MCPClient({
onConnected: () => console.log('✓ Connected'),
onError: (error) => console.error('✗ Error:', error.message),
});
try {
// 1. Connect to server
await client.connect();
// 2. Initialize session
await client.initialize({
name: 'demo-app',
version: '1.0.0',
});
// 3. List available tools
const tools = await client.listTools();
console.log('Available tools:', tools.tools.length);
// 4. Compute MetaID
const metaidResult = await client.callTool('compute_metaid', {
address: '0x1234567890abcdef1234567890abcdef12345678'
});
console.log('MetaID:', metaidResult);
// 5. Get current time
const timeResult = await client.callTool('get_current_time', {});
console.log('Server time:', timeResult);
} catch (error) {
console.error('Error:', error);
} finally {
client.disconnect();
}
}
main();
📖 API文档
MCP客户端
构造函数
new MCPClient(config?: MCPClientConfig)
配置选项:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
baseUrl? |
string |
'https://api.metaid.io/mcp-service' |
MCP服务器地址 |
timeout? |
number |
30000 |
请求超时(毫秒) |
onConnected? |
() => void |
- | 已连接回拨 |
onDisconnected? |
() => void |
- | 已断开连接的回拨 |
onError? |
(error: Error) => void |
- | 错误回调 |
onMessage? |
(message: any) => void |
- | 消息已收到回拨 |
方法
connect()
连接到MCP服务器
await client.connect(): Promise<void>
disconnect()
和服务器断开连接
client.disconnect(): void
initialize()
初始化MCP会话
await client.initialize(clientInfo: {
name: string;
version: string;
}): Promise<InitializeResult>
listTools()
列出所有可用工具
await client.listTools(): Promise<ToolsListResult>
callTool()
调用特定工具
await client.callTool(
name: string,
args?: Record<string, any>
): Promise<CallToolResult>
listResources()
列出所有可用资源
await client.listResources(): Promise<ResourcesListResult>
readResource()
阅读特定资源
await client.readResource(uri: string): Promise<any>
listPrompts()
列出所有可用提示
await client.listPrompts(): Promise<PromptsListResult>
getPrompt()
获取特定提示
await client.getPrompt(
name: string,
args?: Record<string, any>
): Promise<any>
isConnected()
检查连接状态
client.isConnected(): boolean
💡 使用场景
Node.js应用程序
import { MCPClient } from '@metaid/metaid-mcp-client';
const client = new MCPClient();
await client.connect();
// Use client...
React应用程序
import { MCPClient } from '@metaid/metaid-mcp-client';
import { useEffect, useState } from 'react';
function App() {
const [client, setClient] = useState<MCPClient | null>(null);
useEffect(() => {
const mcpClient = new MCPClient({
onConnected: () => console.log('MCP Connected'),
});
mcpClient.connect()
.then(() => mcpClient.initialize({ name: 'react-app', version: '1.0.0' }))
.then(() => setClient(mcpClient));
return () => mcpClient.disconnect();
}, []);
const handleCallTool = async () => {
if (!client) return;
const result = await client.callTool('get_current_time', {});
console.log(result);
};
return <button onClick={handleCallTool}>Get Time</button>;
}
应用程序视图
<script setup lang="ts">
import { MCPClient } from '@metaid/metaid-mcp-client';
import { ref, onMounted, onUnmounted } from 'vue';
const client = ref<MCPClient | null>(null);
onMounted(async () => {
client.value = new MCPClient();
await client.value.connect();
await client.value.initialize({ name: 'vue-app', version: '1.0.0' });
});
onUnmounted(() => {
client.value?.disconnect();
});
const callTool = async () => {
if (!client.value) return;
const result = await client.value.callTool('get_current_time', {});
console.log(result);
};
</script>
<template>
<button @click="callTool">Get Time</button>
</template>
Express.js后端
import express from 'express';
import { MCPClient } from '@metaid/metaid-mcp-client';
const app = express();
const mcpClient = new MCPClient();
await mcpClient.connect();
await mcpClient.initialize({ name: 'express-api', version: '1.0.0' });
app.get('/api/metaid/:address', async (req, res) => {
try {
const result = await mcpClient.callTool('compute_metaid', {
address: req.params.address
});
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);
🌐 浏览器使用情况
通过CDN
<script src="https://unpkg.com/@metaid/metaid-mcp-client/dist/mcp-client.bundle.js"></script>
<script>
const client = new MCPClient.MCPClient();
client.connect()
.then(() => client.initialize({ name: 'browser-app', version: '1.0.0' }))
.then(() => client.callTool('hello_world', {}))
.then(result => console.log(result));
</script>
🔧 命令行工具
安装后提供的CLI工具:
# Connect to server
metaid-mcp-client connect
# List tools
metaid-mcp-client tools
# Call a tool
metaid-mcp-client call -n hello_world -a '{}'
# Specify server address
metaid-mcp-client tools -u http://mcp-server-url
⚙️ 高级配置
自定义服务器地址
const client = new MCPClient({
baseUrl: 'http://mcp-server-url',
timeout: 60000,
});
事件监听器
const client = new MCPClient({
onConnected: () => {
console.log('Connected to MCP server');
},
onDisconnected: () => {
console.log('Connection closed');
},
onError: (error) => {
console.error('Error occurred:', error.message);
},
onMessage: (message) => {
console.log('Message received:', message);
},
});
错误处理
try {
await client.connect();
const result = await client.callTool('some_tool', {});
} catch (error) {
if (error.message.includes('timeout')) {
console.error('Connection timeout');
} else if (error.message.includes('not found')) {
console.error('Tool not found');
} else {
console.error('Unknown error:', error);
}
}
📚 TypeScript支持
完整的TypeScript类型定义:
import {
MCPClient,
MCPClientConfig,
MCPRequest,
MCPResponse,
CallToolResult,
ToolsListResult,
} from '@metaid/metaid-mcp-client';
const config: MCPClientConfig = {
baseUrl: 'https://api.metaid.io/mcp-service',
timeout: 30000,
};
const client: MCPClient = new MCPClient(config);
🧪 测试
# Run tests
npm test
# Test online service
npm run test:online
# Test local service
npm run test:local
📋 版本历史记录
v1.0.0(最新)
发布日期: 2025-01-21
特征:
- ✅ 完全支持MCP协议
- ✅ 基于SSE的实时通信
- ✅ 自动连接到在线服务(https://api.metaid.io/mcp-service)
- ✅ 支持工具、资源和提示
🔨 发展
# Install dependencies
npm install
# Development mode (watch)
npm run watch
# Build
npm run build
# Build all versions
npm run build:all
# Clean
npm run clean
📄 许可证
🔗 链接
❓ 常见问题解答
如何切换到本地服务器?
const client = new MCPClient({
baseUrl: 'http://localhost:7911'
});
支持哪些环境?
- ✅ Node.js>=18.0.0
- ✅ 现代浏览器(Chrome、Firefox、Safari、Edge)
- ✅ React、Vue、Angular等框架
- ✅ TypeScript>=5.0
Made with ❤️ by MetaID
