发现优秀的 MCP 服务器

通过 MCP 服务器扩展您的代理能力,拥有 18,170 个能力。

全部18,170
Echo MCP Server

Echo MCP Server

一个简单的服务器,实现了模型上下文协议(MCP),会将消息回显,专为测试 MCP 客户端而设计。

ERPNext MCP Server

ERPNext MCP Server

A production-ready server that enables AI assistants like Claude Desktop to seamlessly integrate with ERPNext for document operations, reporting, and custom workflows through natural language interaction.

Bankless Onchain MCP Server

Bankless Onchain MCP Server

将 Bankless Onchain API 引入 MCP

Weather MCP Server

Weather MCP Server

Provides current weather data and hourly forecasts for any location worldwide using the Open-Meteo API, accessible through HTTP transport without requiring an API key.

Database Schema MCP Server

Database Schema MCP Server

GitLab MCP Server

GitLab MCP Server

Pabal MCP

Pabal MCP

Manages App Store Connect and Google Play Console metadata, releases, and ASO workflows locally through MCP tools, enabling store management directly from AI clients without manual console navigation.

🚀 Go-Tapd-SDK

🚀 Go-Tapd-SDK

Go Tapd SDK 是一个用于访问 Tapd API 的 Go 客户端库,并且它也支持最新的 MCP 服务器。

Tambo Docs MCP Server

Tambo Docs MCP Server

Enables AI assistants to discover, fetch, and search through Tambo documentation from docs.tambo.co. Provides intelligent content parsing with caching for improved performance when accessing technical documentation.

DAV MCP Server

DAV MCP Server

A Model Context Protocol server that allows users to interact with their CalDAV, CardDAV, and WebDAV services (calendars, contacts, and files) from Fastmail and Apple iCloud accounts.

rest-to-mcp

rest-to-mcp

好的,这是一个将 REST API 转换为 MCP 服务器的教程项目: **项目目标:** * 创建一个 MCP 服务器,该服务器可以接收来自客户端的请求。 * 将接收到的请求转换为对现有 REST API 的调用。 * 将 REST API 的响应转换回 MCP 响应并发送回客户端。 **技术栈:** * **MCP (Minecraft Protocol):** 理解 Minecraft 协议是关键。你需要了解数据包的结构和如何发送/接收它们。 * **Java (或你熟悉的语言):** Java 是 Minecraft 服务器开发的常用语言,但你也可以使用其他语言,只要它们支持网络编程和 JSON 处理。 * **Netty (或类似的网络库):** Netty 是一个高性能的网络应用程序框架,可以简化网络编程。 * **JSON 处理库 (Gson, Jackson, etc.):** 用于序列化和反序列化 JSON 数据。 * **HTTP 客户端库 (HttpClient, OkHttp, etc.):** 用于调用 REST API。 **项目步骤:** 1. **环境搭建:** * 安装 Java Development Kit (JDK)。 * 安装一个 IDE (例如 IntelliJ IDEA 或 Eclipse)。 * 创建一个新的 Java 项目。 * 添加 Netty、JSON 处理库和 HTTP 客户端库作为项目依赖。 (使用 Maven 或 Gradle 管理依赖) 2. **理解 Minecraft 协议:** * **研究 Minecraft 协议:** 了解客户端和服务器之间如何通信。 你可以参考以下资源: * [Wiki.vg](https://wiki.vg/Protocol) (非常详细的协议文档) * [MCProtocolLib](https://github.com/Steveice112/MCProtocolLib) (一个 Java 库,可以帮助你处理 Minecraft 协议) * **确定要支持的协议版本:** 不同的 Minecraft 版本使用不同的协议。选择一个你想要支持的版本。 * **分析需要拦截的数据包:** 确定哪些客户端数据包需要被拦截并转换为 REST API 调用。 例如,聊天消息、命令、物品使用等。 * **分析需要发送的数据包:** 确定哪些服务器数据包需要被发送回客户端,以及如何将 REST API 的响应转换为这些数据包。 3. **创建 MCP 服务器:** * **使用 Netty 创建一个 TCP 服务器:** 监听指定的端口 (例如 25565,Minecraft 的默认端口)。 * **实现一个 ChannelHandler:** 这个 handler 将处理客户端连接、接收数据包、发送数据包和处理错误。 * **处理握手 (Handshake) 数据包:** 客户端首先发送一个握手数据包,其中包含协议版本、服务器地址和端口。 你需要解析这个数据包并验证协议版本。 * **处理登录 (Login) 数据包:** 客户端发送登录数据包,其中包含玩家的用户名。 你需要验证用户名并发送登录成功数据包。 4. **拦截和转换数据包:** * **拦截客户端数据包:** 在 ChannelHandler 中,拦截你想要处理的客户端数据包。 * **解析数据包内容:** 根据协议文档,解析数据包中的数据。 * **将数据转换为 REST API 请求:** 将解析后的数据转换为一个 HTTP 请求,并发送到你的 REST API。 例如,如果客户端发送了一个聊天消息,你可以将消息内容发送到 REST API 的一个端点。 * **处理 REST API 响应:** 接收 REST API 的响应。 * **将 REST API 响应转换为 MCP 数据包:** 将 REST API 的响应转换为一个或多个 MCP 数据包,并发送回客户端。 例如,如果 REST API 返回一个自定义的聊天消息,你可以将其转换为一个聊天消息数据包并发送回客户端。 5. **调用 REST API:** * **使用 HTTP 客户端库发送 HTTP 请求:** 使用你选择的 HTTP 客户端库 (例如 HttpClient 或 OkHttp) 发送 HTTP 请求到你的 REST API。 * **处理 HTTP 响应:** 接收 HTTP 响应并解析响应内容。 6. **错误处理:** * **处理网络错误:** 处理连接错误、超时错误等。 * **处理协议错误:** 处理无效的数据包、错误的协议版本等。 * **处理 REST API 错误:** 处理 REST API 返回的错误。 * **向客户端发送错误消息:** 如果发生错误,向客户端发送一个错误消息。 7. **测试:** * **使用 Minecraft 客户端连接到你的 MCP 服务器:** 确保你的 Minecraft 客户端使用与你的服务器相同的协议版本。 * **测试所有功能:** 测试所有你想要支持的功能,例如聊天消息、命令、物品使用等。 * **调试错误:** 如果出现错误,使用调试器来查找问题并修复它们。 **代码示例 (简化版,仅供参考):** ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.buffer.ByteBuf; import java.util.List; public class McpServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new PacketDecoder(), new PacketEncoder(), new McpServerHandler() ); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(25565).sync(); System.out.println("MCP Server started on port 25565"); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } // 示例:数据包解码器 static class PacketDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // 读取数据包长度 (VarInt) int packetLength = readVarInt(in); // 确保有足够的数据 if (in.readableBytes() < packetLength) { in.resetReaderIndex(); // 重置读取索引,等待更多数据 return; } // 读取数据包 ID (VarInt) int packetId = readVarInt(in); // 读取数据包内容 ByteBuf packetData = in.readBytes(packetLength - varIntLength(packetId)); // 创建一个数据包对象 (你需要定义你的数据包类) Packet packet = new Packet(packetId, packetData); out.add(packet); } // 读取 VarInt (Minecraft 使用的变长整数) private int readVarInt(ByteBuf in) { int numRead = 0; int result = 0; byte read; do { read = in.readByte(); int value = (read & 0x7f); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) { throw new RuntimeException("VarInt is too big"); } } while ((read & 0x80) != 0); return result; } // 计算 VarInt 的长度 private int varIntLength(int value) { int length = 0; do { value >>>= 7; length++; } while (value != 0); return length; } } // 示例:数据包编码器 static class PacketEncoder extends MessageToByteEncoder<Packet> { @Override protected void encode(ChannelHandlerContext ctx, Packet msg, ByteBuf out) throws Exception { ByteBuf packetData = msg.getData(); int packetId = msg.getId(); // 计算数据包长度 int packetLength = varIntLength(packetId) + packetData.readableBytes(); // 写入数据包长度 (VarInt) writeVarInt(out, packetLength); // 写入数据包 ID (VarInt) writeVarInt(out, packetId); // 写入数据包内容 out.writeBytes(packetData); } // 写入 VarInt private void writeVarInt(ByteBuf out, int value) { while (true) { if ((value & ~0x7F) == 0) { out.writeByte(value); return; } out.writeByte((value & 0x7F) | 0x80); value >>>= 7; } } // 计算 VarInt 的长度 private int varIntLength(int value) { int length = 0; do { value >>>= 7; length++; } while (value != 0); return length; } } // 示例:服务器处理器 static class McpServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { Packet packet = (Packet) msg; int packetId = packet.getId(); ByteBuf packetData = packet.getData(); System.out.println("Received packet with ID: " + packetId); // 根据数据包 ID 处理数据包 switch (packetId) { case 0x00: // Handshake handleHandshake(ctx, packetData); break; case 0x00: // Login Start handleLoginStart(ctx, packetData); break; // 其他数据包处理 default: System.out.println("Unknown packet ID: " + packetId); break; } } private void handleHandshake(ChannelHandlerContext ctx, ByteBuf packetData) { // 解析握手数据包 int protocolVersion = readVarInt(packetData); String serverAddress = readString(packetData); int serverPort = packetData.readUnsignedShort(); int nextState = readVarInt(packetData); System.out.println("Handshake received: protocolVersion=" + protocolVersion + ", serverAddress=" + serverAddress + ", serverPort=" + serverPort + ", nextState=" + nextState); // 根据 nextState 进行处理 (例如,切换到状态 1 - Status 或 2 - Login) if (nextState == 1) { // 发送 Status Response sendStatusResponse(ctx); } else if (nextState == 2) { // 准备处理 Login } } private void handleLoginStart(ChannelHandlerContext ctx, ByteBuf packetData) { // 解析登录开始数据包 String username = readString(packetData); System.out.println("Login Start received: username=" + username); // TODO: 调用 REST API 进行身份验证 // 发送 Login Success 数据包 sendLoginSuccess(ctx, username); } private void sendStatusResponse(ChannelHandlerContext ctx) { // 创建 Status Response 数据包 String jsonResponse = "{\"version\": {\"name\": \"My MCP Server\", \"protocol\": 754}, \"players\": {\"max\": 100, \"online\": 0}, \"description\": {\"text\": \"A custom MCP server\"}}"; ByteBuf responseData = ctx.alloc().buffer(); writeString(responseData, jsonResponse); // 创建数据包 Packet statusResponsePacket = new Packet(0x00, responseData); // 发送数据包 ctx.writeAndFlush(statusResponsePacket); } private void sendLoginSuccess(ChannelHandlerContext ctx, String username) { // 创建 Login Success 数据包 ByteBuf responseData = ctx.alloc().buffer(); writeString(responseData, "00000000-0000-0000-0000-000000000000"); // UUID (可以生成一个) writeString(responseData, username); // 创建数据包 Packet loginSuccessPacket = new Packet(0x02, responseData); // 发送数据包 ctx.writeAndFlush(loginSuccessPacket); } // 读取 VarInt private int readVarInt(ByteBuf in) { int numRead = 0; int result = 0; byte read; do { read = in.readByte(); int value = (read & 0x7f); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) { throw new RuntimeException("VarInt is too big"); } } while ((read & 0x80) != 0); return result; } // 写入 VarInt private void writeVarInt(ByteBuf out, int value) { while (true) { if ((value & ~0x7F) == 0) { out.writeByte(value); return; } out.writeByte((value & 0x7F) | 0x80); value >>>= 7; } } // 读取字符串 private String readString(ByteBuf in) { int length = readVarInt(in); ByteBuf stringData = in.readBytes(length); return stringData.toString(java.nio.charset.StandardCharsets.UTF_8); } // 写入字符串 private void writeString(ByteBuf out, String value) { byte[] stringBytes = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); writeVarInt(out, stringBytes.length); out.writeBytes(stringBytes); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } // 数据包类 static class Packet { private final int id; private final ByteBuf data; public Packet(int id, ByteBuf data) { this.id = id; this.data = data; } public int getId() { return id; } public ByteBuf getData() { return data; } } } ``` **重要提示:** * **安全性:** 确保你的 REST API 是安全的,并且只允许授权的客户端访问。 使用身份验证和授权机制。 * **性能:** 优化你的代码以获得最佳性能。 使用缓存、连接池等技术。 * **可扩展性:** 设计你的服务器以支持大量的并发连接。 使用异步编程和非阻塞 I/O。 * **错误处理:** 实现完善的错误处理机制,以便在出现问题时能够快速诊断和修复。 * **协议版本:** 密切关注 Minecraft 协议的更新,并及时更新你的服务器以支持最新的协议版本。 * **代码组织:** 将你的代码组织成模块化的组件,以便于维护和扩展。 **下一步:** 1. **创建你的 REST API:** 如果你还没有 REST API,你需要创建一个。 你可以使用任何你喜欢的编程语言和框架。 2. **实现数据包处理逻辑:** 根据你的 REST API 的需求,实现数据包处理逻辑。 3. **测试你的服务器:** 使用 Minecraft 客户端连接到你的服务器并测试所有功能。 这是一个复杂的项目,需要对 Minecraft 协议和网络编程有深入的了解。 祝你成功! **中文翻译:** 好的,这是一个将 REST API 转换为 MCP 服务器的教程项目: **项目目标:** * 创建一个 MCP 服务器,该服务器可以接收来自客户端的请求。 * 将接收到的请求转换为对现有 REST API 的调用。 * 将 REST API 的响应转换回 MCP 响应并发送回客户端。 **技术栈:** * **MCP (Minecraft 协议):** 理解 Minecraft 协议是关键。你需要了解数据包的结构和如何发送/接收它们。 * **Java (或你熟悉的语言):** Java 是 Minecraft 服务器开发的常用语言,但你也可以使用其他语言,只要它们支持网络编程和 JSON 处理。 * **Netty (或类似的網絡庫):** Netty 是一个高性能的网络应用程序框架,可以简化网络编程。 * **JSON 处理库 (Gson, Jackson, etc.):** 用于序列化和反序列化 JSON 数据。 * **HTTP 客户端库 (HttpClient, OkHttp, etc.):** 用于调用 REST API。 **项目步骤:** 1. **环境搭建:** * 安装 Java Development Kit (JDK)。 * 安装一个 IDE (例如 IntelliJ IDEA 或 Eclipse)。 * 创建一个新的 Java 项目。 * 添加 Netty、JSON 处理库和 HTTP 客户端库作为项目依赖。 (使用 Maven 或 Gradle 管理依赖) 2. **理解 Minecraft 协议:** * **研究 Minecraft 协议:** 了解客户端和服务器之间如何通信。 你可以参考以下资源: * [Wiki.vg](https://wiki.vg/Protocol) (非常详细的协议文档) * [MCProtocolLib](https://github.com/Steveice112/MCProtocolLib) (一个 Java 库,可以帮助你处理 Minecraft 协议) * **确定要支持的协议版本:** 不同的 Minecraft 版本使用不同的协议。选择一个你想要支持的版本。 * **分析需要拦截的数据包:** 确定哪些客户端数据包需要被拦截并转换为 REST API 调用。 例如,聊天消息、命令、物品使用等。 * **分析需要发送的数据包:** 确定哪些服务器数据包需要被发送回客户端,以及如何将 REST API 的响应转换为这些数据包。 3. **创建 MCP 服务器:** * **使用 Netty 创建一个 TCP 服务器:** 监听指定的端口 (例如 25565,Minecraft 的默认端口)。 * **实现一个 ChannelHandler:** 这个 handler 将处理客户端连接、接收数据包、发送数据包和处理错误。 * **处理握手 (Handshake) 数据包:** 客户端首先发送一个握手数据包,其中包含协议版本、服务器地址和端口。 你需要解析这个数据包并验证协议版本。 * **处理登录 (Login) 数据包:** 客户端发送登录数据包,其中包含玩家的用户名。 你需要验证用户名并发送登录成功数据包。 4. **拦截和转换数据包:** * **拦截客户端数据包:** 在 ChannelHandler 中,拦截你想要处理的客户端数据包。 * **解析数据包内容:** 根据协议文档,解析数据包中的数据。 * **将数据转换为 REST API 请求:** 将解析后的数据转换为一个 HTTP 请求,并发送到你的 REST API。 例如,如果客户端发送了一个聊天消息,你可以将消息内容发送到 REST API 的一个端点。 * **处理 REST API 响应:** 接收 REST API 的响应。 * **将 REST API 响应转换为 MCP 数据包:** 将 REST API 的响应转换为一个或多个 MCP 数据包,并发送回客户端。 例如,如果 REST API 返回一个自定义的聊天消息,你可以将其转换为一个聊天消息数据包并发送回客户端。 5. **调用 REST API:** * **使用 HTTP 客户端库发送 HTTP 请求:** 使用你选择的 HTTP 客户端库 (例如 HttpClient 或 OkHttp) 发送 HTTP 请求到你的 REST API。 * **处理 HTTP 响应:** 接收 HTTP 响应并解析响应内容。 6. **错误处理:** * **处理网络错误:** 处理连接错误、超时错误等。 * **处理协议错误:** 处理无效的数据包、错误的协议版本等。 * **处理 REST API 错误:** 处理 REST API 返回的错误。 * **向客户端发送错误消息:** 如果发生错误,向客户端发送一个错误消息。 7. **测试:** * **使用 Minecraft 客户端连接到你的 MCP 服务器:** 确保你的 Minecraft 客户端使用与你的服务器相同的协议版本。 * **测试所有功能:** 测试所有你想要支持的功能,例如聊天消息、命令、物品使用等。 * **调试错误:** 如果出现错误,使用调试器来查找问题并修复它们。 **代码示例 (简化版,仅供参考):** ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.buffer.ByteBuf; import java.util.List; public class McpServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new PacketDecoder(), new PacketEncoder(), new McpServerHandler() ); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(25565).sync(); System.out.println("MCP Server started on port 25565"); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } // 示例:数据包解码器 static class PacketDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // 读取数据包长度 (VarInt) int packetLength = readVarInt(in); // 确保有足够的数据 if (in.readableBytes() < packetLength) { in.resetReaderIndex(); // 重置读取索引,等待更多数据 return; } // 读取数据包 ID (VarInt) int packetId = readVarInt(in); // 读取数据包内容 ByteBuf packetData = in.readBytes(packetLength - varIntLength(packetId)); // 创建一个数据包对象 (你需要定义你的数据包类) Packet packet = new Packet(packetId, packetData); out.add(packet); } // 读取 VarInt (Minecraft 使用的变长整数) private int readVarInt(ByteBuf in) { int numRead = 0; int result = 0; byte read; do { read = in.readByte(); int value = (read & 0x7f); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) { throw new RuntimeException("VarInt is too big"); } } while ((read & 0x80) != 0); return result; } // 计算 VarInt 的长度 private int varIntLength(int value) { int length = 0; do { value >>>= 7; length++; } while (value != 0); return length; } } // 示例:数据包编码器 static class PacketEncoder extends MessageToByteEncoder<Packet> { @Override protected void encode(ChannelHandlerContext ctx, Packet msg, ByteBuf out) throws Exception { ByteBuf packetData = msg.getData(); int packetId = msg.getId(); // 计算数据包长度 int packetLength = varIntLength(packetId) + packetData.readableBytes(); // 写入数据包长度 (VarInt) writeVarInt(out, packetLength); // 写入数据包 ID (VarInt) writeVarInt(out, packetId); // 写入数据包内容 out.writeBytes(packetData); } // 写入 VarInt private void writeVarInt(ByteBuf out, int value) { while (true) { if ((value & ~0x7F) == 0) { out.writeByte(value); return; } out.writeByte((value & 0x7F) | 0x80); value >>>= 7; } } // 计算 VarInt 的长度 private int varIntLength(int value) { int length = 0; do { value >>>= 7; length++; } while (value != 0); return length; } } // 示例:服务器处理器 static class McpServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { Packet packet = (Packet) msg; int packetId = packet.getId(); ByteBuf packetData = packet.getData(); System.out.println("Received packet with ID: " + packetId); // 根据数据包 ID 处理数据包 switch (packetId) { case 0x00: // Handshake handleHandshake(ctx, packetData); break; case 0x00: // Login Start handleLoginStart(ctx, packetData); break; // 其他数据包处理 default: System.out.println("Unknown packet ID: " + packetId); break; } } private void handleHandshake(ChannelHandlerContext ctx, ByteBuf packetData) { // 解析握手数据包 int protocolVersion = readVarInt(packetData); String serverAddress = readString(packetData); int serverPort = packetData.readUnsignedShort(); int nextState = readVarInt(packetData); System.out.println("Handshake received: protocolVersion=" + protocolVersion + ", serverAddress=" + serverAddress + ", serverPort=" + serverPort + ", nextState=" + nextState); // 根据 nextState 进行处理 (例如,切换到状态 1 - Status 或 2 - Login) if (nextState == 1) { // 发送 Status Response sendStatusResponse(ctx); } else if (nextState == 2) { // 准备处理 Login } } private void handleLoginStart(ChannelHandlerContext ctx, ByteBuf packetData) { // 解析登录开始数据包 String username = readString(packetData); System.out.println("Login Start received: username=" + username); // TODO: 调用 REST API 进行身份验证 // 发送 Login Success 数据包 sendLoginSuccess(ctx, username); } private void sendStatusResponse(ChannelHandlerContext ctx) { // 创建 Status Response 数据包 String jsonResponse = "{\"version\": {\"name\": \"My MCP Server\", \"protocol\": 754}, \"players\": {\"max\": 100, \"online\": 0}, \"description\": {\"text\": \"A custom MCP server\"}}"; ByteBuf responseData = ctx.alloc().buffer(); writeString(responseData, jsonResponse); // 创建数据包 Packet statusResponsePacket = new Packet(0x00, responseData); // 发送数据包 ctx.writeAndFlush(statusResponsePacket); } private void sendLoginSuccess(ChannelHandlerContext ctx, String username) { // 创建 Login Success 数据包 ByteBuf responseData = ctx.alloc().buffer(); writeString(responseData, "00000000-0000-0000-0000-000000000000"); // UUID (可以生成一个) writeString(responseData, username); // 创建数据包 Packet loginSuccessPacket = new Packet(0x02, responseData); // 发送数据包 ctx.writeAndFlush(loginSuccessPacket); } // 读取 VarInt private int readVarInt(ByteBuf in) { int numRead = 0; int result = 0; byte read; do { read = in.readByte(); int value = (read & 0x7f); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) { throw new RuntimeException("VarInt is too big"); } } while ((read & 0x80) != 0); return result; } // 写入 VarInt private void writeVarInt(ByteBuf out, int value) { while (true) { if ((value & ~0x7F) == 0) { out.writeByte(value); return; } out.writeByte((value & 0x7F) | 0x80); value >>>= 7; } } // 读取字符串 private String readString(ByteBuf in) { int length = readVarInt(in); ByteBuf stringData = in.readBytes(length); return stringData.toString(java.nio.charset.StandardCharsets.UTF_8); } // 写入字符串 private void writeString(ByteBuf out, String value) { byte[] stringBytes = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); writeVarInt(out, stringBytes.length); out.writeBytes(stringBytes); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } // 数据包类 static class Packet { private final int id; private final ByteBuf data; public Packet(int id, ByteBuf data) { this.id = id; this.data = data; } public int getId() { return id; } public ByteBuf getData() { return data; } } } ``` **重要提示:** * **安全性:** 确保你的 REST API 是安全的,并且只允许授权的客户端访问。 使用身份验证和授权机制。 * **性能:** 优化你的代码以获得最佳性能。 使用缓存、连接池等技术。 * **可扩展性:** 设计你的服务器以支持大量的并发连接。 使用异步编程和非阻塞 I/O。 * **错误处理:** 实现完善的错误处理机制,以便在出现问题时能够快速诊断和修复。 * **协议版本:** 密切关注 Minecraft 协议的更新,并及时更新你的服务器以支持最新的协议版本。 * **代码组织:** 将你的代码组织成模块化的组件,以便于维护和扩展。 **下一步:** 1. **创建你的 REST API:** 如果你还没有 REST API,你需要创建一个。 你可以使用任何你喜欢的编程语言和框架。 2. **实现数据包处理逻辑:** 根据你的 REST API 的需求,实现数据包处理逻辑。 3. **测试你的服务器:** 使用 Minecraft 客户端连接到你的服务器并测试所有功能。 这是一个复杂的项目,需要对 Minecraft 协议和网络编程有深入的了解。 祝你成功!

Fetch MCP Server

Fetch MCP Server

Okay, here's a breakdown of how you can fetch URLs from a webpage using Playwright, integrate it with an SSE (Server-Sent Events) MCP (Management Control Plane) server, and use Node.js with Express.js to orchestrate everything. I'll provide code snippets and explanations to guide you. **Conceptual Overview** 1. **Playwright (Web Scraping):** Playwright will be used to launch a browser, navigate to the target webpage, and extract the URLs you need. 2. **Node.js/Express.js (Server):** Express.js will create a web server that handles requests to start the scraping process and stream the results back to the client. 3. **SSE (Server-Sent Events):** SSE will be used to push the extracted URLs from the server to the client in real-time as they are found. This is more efficient than repeatedly polling the server. 4. **MCP (Management Control Plane):** The MCP part is a bit more abstract. It implies you have a system for managing and controlling the scraping process. This could involve: * Configuration: Specifying the target URL, selectors for extracting URLs, etc. * Monitoring: Tracking the progress of the scraping job. * Error Handling: Managing errors that occur during scraping. * Scaling: Distributing the scraping workload across multiple instances. **Code Example (Illustrative)** **1. Project Setup** ```bash mkdir playwright-sse-mcp cd playwright-sse-mcp npm init -y npm install playwright express eventsource ``` **2. `server.js` (Node.js/Express.js Server)** ```javascript const express = require('express'); const { chromium } = require('playwright'); const app = express(); const port = 3000; app.use(express.json()); // For parsing JSON request bodies // In-memory storage for SSE connections (replace with a more robust solution for production) const sseClients = []; app.get('/sse', (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); res.flushHeaders(); const clientId = Date.now(); // Unique ID for the client const newClient = { id: clientId, res, }; sseClients.push(newClient); console.log(`${clientId} Connection open`); req.on('close', () => { console.log(`${clientId} Connection closed`); sseClients = sseClients.filter((client) => client.id !== clientId); }); }); function sendSSE(data) { sseClients.forEach((client) => { client.res.write(`data: ${JSON.stringify(data)}\n\n`); }); } app.post('/scrape', async (req, res) => { const { url, selector } = req.body; // Get URL and selector from request body if (!url || !selector) { return res.status(400).send('URL and selector are required.'); } console.log(`Starting scrape for ${url} with selector ${selector}`); try { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto(url); const links = await page.locator(selector).evaluateAll(links => links.map(link => link.href)); for (const link of links) { sendSSE({ url: link }); // Send each URL via SSE } await browser.close(); console.log(`Scrape complete for ${url}`); res.status(200).send('Scrape started and URLs are being streamed.'); } catch (error) { console.error('Scrape error:', error); sendSSE({ error: error.message }); // Send error via SSE res.status(500).send('Scrape failed.'); } }); app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); }); ``` **3. `client.html` (Simple Client to Receive SSE)** ```html <!DOCTYPE html> <html> <head> <title>SSE Client</title> </head> <body> <h1>SSE Stream</h1> <ul id="urlList"></ul> <script> const urlList = document.getElementById('urlList'); const eventSource = new EventSource('http://localhost:3000/sse'); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); if (data.url) { const listItem = document.createElement('li'); listItem.textContent = data.url; urlList.appendChild(listItem); } else if (data.error) { const listItem = document.createElement('li'); listItem.textContent = `Error: ${data.error}`; urlList.appendChild(listItem); } }; eventSource.onerror = (error) => { console.error('SSE error:', error); }; </script> </body> </html> ``` **4. Running the Example** 1. **Start the Server:** `node server.js` 2. **Open `client.html`** in your browser. 3. **Send a POST request to `/scrape`:** You can use `curl`, `Postman`, or a similar tool. For example: ```bash curl -X POST -H "Content-Type: application/json" -d '{"url": "https://www.example.com", "selector": "a"}' http://localhost:3000/scrape ``` Replace `"https://www.example.com"` with the URL you want to scrape and `"a"` with the CSS selector for the links you want to extract. **Explanation** * **`server.js`:** * Sets up an Express.js server. * `/sse` endpoint: Handles SSE connections. It sets the correct headers for SSE and keeps track of connected clients. * `sendSSE(data)`: Sends data to all connected SSE clients. * `/scrape` endpoint: * Receives the target URL and CSS selector from the request body. * Launches a Playwright browser. * Navigates to the URL. * Uses `page.locator(selector).evaluateAll()` to extract the `href` attributes of all elements matching the selector. * Sends each URL back to the client via SSE. * Handles errors and sends error messages via SSE. * **`client.html`:** * Creates an `EventSource` object to connect to the `/sse` endpoint. * Listens for `message` events from the server. * Parses the JSON data and displays the URLs in a list. * Handles errors. **Important Considerations for Production (MCP)** * **Configuration Management:** Instead of hardcoding the URL and selector in the `curl` command, you'd typically store them in a database or configuration file. Your MCP would provide an interface for managing these configurations. * **Job Queuing:** Use a message queue (e.g., RabbitMQ, Kafka) to queue scraping jobs. This allows you to handle a large number of requests without overloading the server. * **Scaling:** Run multiple instances of the scraping server behind a load balancer. The message queue will distribute the jobs across the instances. * **Monitoring:** Use a monitoring system (e.g., Prometheus, Grafana) to track the performance of the scraping servers, the number of jobs in the queue, and any errors that occur. * **Error Handling:** Implement robust error handling and retry mechanisms. For example, if a scraping job fails, you might retry it a few times before giving up. * **Rate Limiting:** Be respectful of the websites you are scraping. Implement rate limiting to avoid overloading their servers. * **Data Storage:** Instead of just displaying the URLs in the browser, you'll likely want to store them in a database or other data store. * **Authentication/Authorization:** Secure your MCP endpoints with authentication and authorization to prevent unauthorized access. * **Headless Mode:** Run the Playwright browser in headless mode (which is the default) for better performance. **Example of MCP Integration (Conceptual)** Let's say you have an MCP API endpoint `/api/scrape-jobs` that allows you to create new scraping jobs. The request body might look like this: ```json { "url": "https://www.example.com", "selector": "a", "callbackUrl": "https://your-data-store.com/api/store-data" // Where to send the scraped data } ``` Your server would then: 1. Receive the request to `/api/scrape-jobs`. 2. Validate the request. 3. Create a job in the message queue (e.g., RabbitMQ). 4. A worker process (one of your scraping server instances) would pick up the job from the queue. 5. The worker would scrape the URL, extract the data, and send it to the `callbackUrl`. 6. The worker would update the job status in the MCP (e.g., "in progress", "completed", "failed"). This is a simplified example, but it illustrates the basic principles of integrating Playwright with an SSE server and an MCP. The specific implementation will depend on your requirements and the architecture of your MCP. **Chinese Translation of Key Concepts** * **Web Scraping:** 网络爬虫 (wǎngluò páchóng) * **Server-Sent Events (SSE):** 服务器发送事件 (fúwùqì fāsòng shìjiàn) * **Management Control Plane (MCP):** 管理控制平面 (guǎnlǐ kòngzhì píngmiàn) * **Playwright:** Playwright (no direct translation, use the English name) * **Node.js:** Node.js (no direct translation, use the English name) * **Express.js:** Express.js (no direct translation, use the English name) * **URL:** 网址 (wǎngzhǐ) * **CSS Selector:** CSS 选择器 (CSS xuǎnzéqì) * **Endpoint:** 端点 (duāndiǎn) * **Message Queue:** 消息队列 (xiāoxi duìliè) * **Load Balancer:** 负载均衡器 (fùzài jūnhéngqì) * **Monitoring:** 监控 (jiānkòng) * **Error Handling:** 错误处理 (cuòwù chǔlǐ) * **Rate Limiting:** 速率限制 (sùlǜ xiànzhì) This comprehensive explanation and code example should give you a solid foundation for building your Playwright-based web scraping solution with SSE and MCP integration. Remember to adapt the code and architecture to your specific needs and environment. Good luck!

XML Documents MCP Server by CData

XML Documents MCP Server by CData

XML Documents MCP Server by CData

Paylo MCP Server

Paylo MCP Server

Enables AI agents to interact with the Paylo commerce ecosystem, allowing them to discover merchants, search products, manage shopping carts, and facilitate transactions through Paystack payment integration.

Enrichment MCP Server

Enrichment MCP Server

A Model Context Protocol server that enables users to perform third-party enrichment lookups for security observables (IP addresses, domains, URLs, emails) through services like VirusTotal, Shodan, and others.

stackzero-labs/mcp

stackzero-labs/mcp

A model context protocol server that enables applications to use stackzero-labs/ui components through the MCP protocol, supporting both standalone operation and integration with Claude Desktop and Cursor.

Rongcloud Native

Rongcloud Native

Native MCP Overview RongCloud Native MCP is a lightweight RongCloud IM service wrapper based on the MCP (Model Control Protocol) protocol. By directly wrapping the high-performance Rust IM SDK, it provides a simple and efficient instant messaging solution for client-side or local applications

MCP REST API Server

MCP REST API Server

A server implementation of the Model Context Protocol (MCP) that provides REST API endpoints for managing and interacting with MCP resources.

CTF-MCP-Server

CTF-MCP-Server

Mcp Starwars

Mcp Starwars

用于 SWAPI 星球大战 API 的 MCP 服务器。该项目的主要目标是展示如何使用 MCP 服务器与 API 进行交互。

MCP Web Extractor

MCP Web Extractor

使用 Readability.js 提取网页内容的 MCP 服务器。

Redmine MCP Server

Redmine MCP Server

镜子 (jìng zi)

Stock MCP 服务器

Stock MCP 服务器

Cursor Talk to Figma MCP

Cursor Talk to Figma MCP

Enables Cursor AI to communicate with Figma for reading designs and modifying them programmatically, allowing users to automate design tasks through natural language.

Firefly III MCP Server

Firefly III MCP Server

Enables AI tools to interact with Firefly III personal finance management instances through a cloud-deployed MCP server. Supports financial operations like account management, transactions, budgeting, and reporting with configurable tool presets.

MCP Meeting Summary System

MCP Meeting Summary System

An AI-powered meeting assistant that combines FastAPI backend with React frontend to generate high-quality meeting summaries and provide Q&A functionality using OpenAI and Selenium.

YouTube Knowledge MCP

YouTube Knowledge MCP

Transforms YouTube into a queryable knowledge source with search, video details, transcript analysis, and AI-powered tools for summaries, learning paths, and knowledge graphs. Features quota-aware API access with caching and optional OpenAI/Anthropic integration for advanced content analysis.

Azure DevOps MCP Proxy

Azure DevOps MCP Proxy

Enables interaction with Azure DevOps through Personal Access Token authentication. Supports work item management, wiki operations, project/repository listing, and build pipeline access through natural language.

MCP-Kit Developer Task Assignment System

MCP-Kit Developer Task Assignment System

Enables intelligent task assignment to developers using hybrid AI algorithms that match tasks based on past experience, skill sets, workload balance, and project alignment. Features enterprise-grade security with AES-256 encryption and 75% performance optimization through smart caching.

WAHA MCP Server

WAHA MCP Server

Enables AI assistants to interact with WhatsApp through the WAHA (WhatsApp HTTP API) platform. Supports chat management, message operations including sending/receiving messages, and marking chats as read.