React Hook MCP🏗️
用于在客户端和服务器上与模型上下文协议(MCP)交互的SDK。
🚀 现在使用 fixtergeek mcp服务器 作为MCP服务器的基础
🎯 主要使用案例
🏥 卫生部门-医疗数据分析
// Análisis de resultados de laboratorio
const analisis = await client.processQuery(
"Analiza los valores de hemoglobina y glucosa del paciente ID-12345"
);
// Interpretación de radiografías
const diagnostico = await client.processQuery(
"Revisa la radiografía de tórax del paciente y busca signos de neumonía"
);🏦 金融部门-风险管理
// Evaluación de riesgo crediticio
const riesgo = await client.processQuery(
"Evalúa el riesgo crediticio del cliente corporativo XYZ basado en su historial financiero"
);
// Análisis de mercado en tiempo real
const mercado = await client.processQuery(
"Analiza las tendencias del mercado de valores y genera recomendaciones de inversión"
);🏭 工业部门-预测性维护
// Monitoreo de equipos industriales
const estado = await client.processQuery(
"Analiza los datos de vibración de la turbina T-001 y predice el próximo mantenimiento"
);
// Optimización de procesos
const optimizacion = await client.processQuery(
"Optimiza los parámetros de temperatura y presión en el reactor químico R-205"
);🛡️ 网络安全-威胁检测
// Análisis de logs de seguridad
const amenazas = await client.processQuery(
"Analiza los logs del firewall y detecta patrones de actividad sospechosa"
);
// Evaluación de vulnerabilidades
const vulnerabilidades = await client.processQuery(
"Evalúa el reporte de escaneo de vulnerabilidades del sistema de pagos"
);📊 商业分析-商业洞察
// Análisis de ventas y tendencias
const ventas = await client.processQuery(
"Analiza las ventas del Q4 por región y genera insights para la estrategia del próximo trimestre"
);
// Predicción de demanda
const demanda = await client.processQuery(
"Predice la demanda de productos para el próximo mes basado en datos históricos"
);🚀 软件开发-Devops和CI/CD
// Análisis de rendimiento de aplicaciones
const rendimiento = await client.processQuery(
"Analiza las métricas de rendimiento de la aplicación web y identifica cuellos de botella"
);
// Gestión de incidentes
const incidente = await client.processQuery(
"Analiza el incidente de producción y genera un plan de acción para la resolución"
);安装
npm install react-hook-mcp🤖 Phi-4 的服务器代理
该MCP代理是购买您自己的LLM PHI-4服务器时包含的集成的一部分: https://phi4.fly.dev/
🏗️ Arquitectura
该项目使用包 fixtergeek-mcp-server 作为MCP服务器的基础,提供:
- ✅ HTTP服务器 连接端点REST
- ✅ LLMs整合 (OpenAI、Ollama、Claude)
- ✅ 资源和工具管理
- ✅ WebSocket代理 用于实时通信
- ✅ 互动式网页客户端
Usuario → Web Client → WebSocket Proxy → fixtergeek-mcp-server → LLM → Recursos/Herramientas🚀 快速入门
执行整个堆栈:
# Modo desarrollo (con watch mode)
npm run dev
# Modo producción
npm run start这将开始:
- 🟢 MCP服务器:
http://localhost:3001(fixtergeek mcp服务器) - 🟢 web客户端:
http://localhost:3000(Web界面)
访问Web客户端:
- 打开您的浏览器:
http://localhost:3000 - 单击“连接到服务器”
- 准备好了!您现在可以使用所有功能
使用指南
1.对于客户(react/node.js)
使用MCP
Hook React连接到MCP服务器:
import { useMCP } from "react-hook-mcp";
function MyComponent() {
const {
isConnected,
loading,
readResource,
callTool,
processQuery,
getStatus,
disconnect,
} = useMCP();
// Ejemplo de uso completo
const handleQuery = async () => {
try {
// Consultar al LLM
const response = await processQuery("¿Qué hora es?");
console.log("Respuesta LLM:", response.content);
// Leer un recurso
const resource = await readResource("/path/to/resource");
console.log("Contenido recurso:", resource.content);
// Llamar a una herramienta
const toolResult = await callTool("tool-name");
console.log("Resultado herramienta:", toolResult.content);
} catch (error) {
console.error("Error:", error);
}
};
return (
Estado: {isConnected ? "Conectado" : "Desconectado"}
Cargando: {loading ? "Sí" : "No"}
Probar todas las funciones
Desconectar
);
}MCPHttpClient
Node.js的HTTP客户端,允许与MCP服务器通信:
import { MCPHttpClient } from "react-hook-mcp";
// Crear cliente
const client = new MCPHttpClient("http://localhost:3001");
// Ejemplos de uso
async function main() {
try {
// Leer recurso
const resource = await client.readResource("/path/to/resource");
console.log("Recurso:", resource.content);
// Llamar herramienta
const toolResult = await client.callTool("tool-name");
console.log("Resultado herramienta:", toolResult.content);
// Consultar LLM
const queryResult = await client.processQuery("¿Qué hora es?");
console.log("Respuesta LLM:", queryResult.content);
} catch (error) {
console.error("Error:", error);
}
}
main();2.对于服务器
Servidor MCP控制器MCP服务器
服务器使用 fixtergeek-mcp-server 它提供:
import { createMCPServer } from "fixtergeek-mcp-server";
// Configuración del servidor MCP
const server = createMCPServer({
port: 3001,
logLevel: "info",
llm: {
provider: "ollama",
baseUrl: "http://localhost:11434",
model: "llama3.2:3b",
temperature: 0.7,
},
});
// Registrar recursos personalizados
server.registerResource(
"hello-resource",
"file:///hello.txt",
{
title: "Hello Resource",
description: "A simple hello world resource",
},
async () => ({
success: true,
data: {
content: "Hello, World! This is a custom resource!",
mimeType: "text/plain",
},
timestamp: Date.now(),
})
);
// Registrar herramientas personalizadas
server.registerTool(
"tool-pelusear",
{
title: "Pelusear Tool",
description: "A simple tool that pelusea (pets) you",
},
async (params) => ({
success: true,
data: {
result: {
message: "¡Has sido peluseado! 🐶",
params,
timestamp: new Date().toISOString(),
},
},
timestamp: Date.now(),
})
);
// Iniciar el servidor
await server.start();MCPWeb服务器
通过HTTP/WS公开MCP并处理与LLMS连接的Web服务器:
import { MCPWebServer } from "react-hook-mcp";
// Opción 1: Servidor simple
const server = MCPWebServer.start();
// Servidor iniciará en http://localhost:3000
// Opción 2: Servidor con configuración personalizada
const server = new MCPWebServer();
server.start();
// Ejemplo de manejo de eventos
server.wss.on("connection", (ws) => {
console.log("Cliente conectado");
ws.on("message", async (message) => {
try {
const data = JSON.parse(message.toString());
// Procesar mensaje
} catch (error) {
console.error("Error procesando mensaje:", error);
}
});
});LLM客户
LLMS的基本客户,可以直接使用或作为其他客户的基础:
import { LLMClient } from "react-hook-mcp";
// Crear cliente personalizado
const client = new LLMClient({
apiUrl: "http://localhost:11434/api/chat",
model: "llama3.2:3b",
headers: {
Authorization: "Bearer tu-token",
},
});
// Usar el cliente
async function main() {
try {
const response = await client.chat([
{ role: "user", content: "¿Qué hora es?" },
]);
console.log("Respuesta:", response);
} catch (error) {
console.error("Error:", error);
}
}
main();客户端预配置
createOllamaClient
Ollama 的预配置客户端 :
import { createOllamaClient } from "react-hook-mcp";
// Crear cliente de Ollama
const client = createOllamaClient("llama3.2:3b");
async function main() {
try {
const response = await client.chat([
{ role: "user", content: "¿Qué hora es?" },
]);
console.log("Respuesta Ollama:", response);
} catch (error) {
console.error("Error:", error);
}
}
main();创建OpenAIClient
OpenAI客户端预配置:
import { createOpenAIClient } from "react-hook-mcp";
// Crear cliente de OpenAI
const client = createOpenAIClient("tu-api-key", "gpt-3.5-turbo");
async function main() {
try {
const response = await client.chat([
{ role: "user", content: "¿Qué hora es?" },
]);
console.log("Respuesta OpenAI:", response);
} catch (error) {
console.error("Error:", error);
}
}
main();主要特征
客户
- 挂钩反应(
useMCP)易于集成到React应用程序中 - HTTP 客户端
MCPHttpClient)用于node.js - 自动处理连接状态
- 资源阅读支持
- MCP工具调用
- 向LLM咨询
- 综合错误处理
服务器
- HTTP服务器 基于
fixtergeek-mcp-server - LLMs整合 (奥利马、OpenAI、克劳德)
- WebSocket代理 用于实时通信
- 多连接处理
- 资源和工具支持
- 可配置个性化
- 事件和消息处理
提示和配置
- 完整类型脚本
- 配置灵活
- 处理状态
- URL和模型的个性化
- 支持不同的LLMS供应商
🎯 主要特征
- 🤖 LLMs整合
- OpenAI - 克劳德 - 没有 - API个性化
- 📊 实时分析
- 🛠️ 执行工具
- 📦 与REACT的整合
- 钩子可重复使用 - 自动连接 - 处理状态
- ✅ TypeScript完成
- ✅ 鲁棒错误处理
- ✅ 详细文件
- ✅ 集成测试 completos
- 🚀 基于FixterGeek-MCP-Server
🚀 这次回购包括什么?
1.维修MCP服务器
# Para desarrollo (con watch mode)
npm run dev
# Para producción
npm run start
# Solo servidor MCP
npm run start:mcpMCP服务器在端口3001上运行,并提供:
- 得到/ -测试终点
- 获取/资源?uri= -阅读资源
- POST/工具 -运行工具
- POST/查询 -处理LLM查询
2. 互动式网页客户端
要使用交互式Web客户端:
# Ejecutar solo el cliente web
npm run web
# O ejecutar ambos servidores juntos
npm run dev # Modo desarrollo
npm run start # Modo producción然后在以下位置打开您的浏览器:http://localhost:3000
Web客户端允许您:
- 连接/断开MCP服务器
- 阅读资源(例如
file:///hello.txt) - 运行工具(例如
tool-pelusear) - 处理LLM查询 (新功能)
🧩 MCP服务器结构
服务器包括:
- 资源:
file:///hello.txt-Devuelve“你好,世界!这是来自fixtergeek mcp服务器的自定义资源!” - 工具:
tool-pelusear-return“你被毛了!🐶(二)
添加新资源:
server.registerResource(
"mi-recurso",
"file:///mi-archivo.txt",
{
title: "Mi Recurso",
description: "Descripción de mi recurso",
},
async () => ({
success: true,
data: {
content: "Contenido del archivo",
mimeType: "text/plain",
},
timestamp: Date.now(),
})
);添加新工具:
server.registerTool(
"mi-herramienta",
{
title: "Mi Herramienta",
description: "Descripción de mi herramienta",
},
async (params) => ({
success: true,
data: {
result: {
message: "Resultado de mi herramienta",
params,
timestamp: new Date().toISOString(),
},
},
timestamp: Date.now(),
})
);🧪 测试
该项目包括一套完整的测试,涵盖主要功能:
运行所有测试:
npm test执行特定测试:
# Tests unitarios
npm test -- test/unit.test.ts
# Tests de integración
npm test -- test/integration.test.ts
# Tests simples (verificación básica)
npm test -- test/simple.test.ts测试类型
1. 测试单元 (test/unit.test.ts)
他们验证单个组件:
- ✅ MCP服务器配置
- ✅ 注册资源和工具
- ✅ HTTP客户端和实用程序
- ✅ 网络套接字通信
- ✅ 错误处理
- ✅ 数据有效期
- ✅ LLM设置
2. 集成测试 (test/integration.test.ts)
他们验证系统的完整功能:
- ✅ 服务器的启动和停止
- ✅ MCP服务器的HTTP端点(端口3001)
- ✅ Web服务器(端口3000)
- ✅ 网络套接字通信
- ✅ 完整流程:连接→阅读资源→调用工具→查询LLM
- ✅ 错误处理和边缘案例
3. 简单测试 (test/simple.test.ts)
基本环境验证:
- ✅ 基本操作
- ✅ 项目结构
- ✅ 所需文件
试验方法
测试包括:
Servidor MCP(修复程序MCP服务器)
- ✅ 启动和配置
- ✅ 端点HTTP(
/,/resource,/tool,/query) - ✅ 注册资源和工具
- ✅ 法学硕士课程
- ✅ 错误处理
Web 服务器
- ✅ 为客户提供HTML
- ✅ 网络套接字通信
- ✅ MCP 代理服务器
- ✅ 多连接处理
脚本和配置
- ✅ Package.json
- ✅ 脚本npm
- ✅ Vitest配置
- ✅ 项目建设
测试配置
美国项目 速度 como框架去测试:
// vitest.config.ts
export default defineConfig({
test: {
globals: true,
environment: "node",
setupFiles: ["./test/setup.ts"],
testTimeout: 60000,
hookTimeout: 60000,
},
});在监视模式下运行测试
# Ejecutar tests en modo watch
npm test -- --watch
# Ejecutar tests específicos en modo watch
npm test -- test/unit.test.ts --watch完整性测试
集成测试验证整个流程:
- 服务器启动
- MCP服务器端口3001 - 网络服务器en puerto 3000
- 端点测试
- MCP服务器健康检查 - 阅读资源 - 执行工具 - 向LLM咨询
- 网络套接字通信
- 连接建立 - 发送消息 - 收到答复
- 端到端流
- 连接到服务器 - 阅读资源 file:///hello.txt - 绘制工具 tool-pelusear - 处理LLM查询
测试结果
测试验证:
- ✅ MCP服务器已正确启动
- ✅ 可以读取资源(
file:///hello.txt) - ✅ 工具可以运行(
tool-pelusear) - ✅ WebSocket通信稳定
- ✅ 该项目的建设是成功的
- ✅ 与LLM的集成工程
- ✅ 错误处理是健壮的
调试与测试
调试设备测试特别说明:
# Ejecutar un test específico con más información
npm test -- test/integration.test.ts --reporter=verbose
# Ejecutar tests con logs detallados
DEBUG=* npm test
# Ejecutar tests en modo debug
npm test -- --inspect-brk🚀 普雷西奥斯·帕索斯
- \[\]添加更多资源(API、数据库等)
- \[\]部署更复杂的工具
- \[\]添加身份验证和安全性
- \[\]改进Web界面
- \[\]添加更多测试
- \[\]与更多的LLM供应商集成
- \[ \] 创建监控仪表板
- \[\]数据的持久性
- \[\]⚡ 实施响应流媒体
🤝 贡献
- 叉项目
- 为您的功能创建分支(
git checkout -b feature/AmazingFeature) - 提交您的更改(
git commit -m 'Add some AmazingFeature') - 推拉拉马(
git push origin feature/AmazingFeature) - 取消拉取请求
📄 许可证
这个项目在麻省理工学院的许可下-查看文件 许可证 为了细节。
🙏 感谢
- 模型上下文协议 按标准
- fixtergeek mcp服务器 基于MCP服务器
- Anthropic 克劳德
- OpenAI 通过 GPT
- 没有 通过局部模型
📦 脚本消耗品
npm run build # Build del proyecto
npm run dev # Ambos servidores en modo desarrollo (MCP + Web)
npm run start # Ambos servidores (MCP + Web)
npm run start:mcp # Solo servidor MCP
npm run web # Solo cliente web interactivo
npm run example # Ejecuta todos los ejemplos del cliente LLM
npm test # Corre los tests de integración📦 在NPM中安装包!
你喜欢这个项目吗?直接从NPM安装!
npm install react-hook-mcp有用的链接
- 📦 ****
- 🐙 ****
- 📚 完整文件
- 🚀 fixtergeek mcp服务器
⭐ 给他一颗星星!
如果这个项目对你有用,在Github上给他一颗星!
______________________________________________________________________
_发展与🤖 通过 赫克托布利斯_
