Discover Awesome MCP Servers

Extend your agent with 16,080 capabilities via MCP servers.

All16,080
TypeScript MCP Server

TypeScript MCP Server

Mcp Servers Collection

Mcp Servers Collection

已验证的 MCP 服务器和集成集合

worker17

worker17

一个 MCP 服务器,用于监控员工生产力并在必要时解雇他们。

mcp-server-yahoo-finance MCP server

mcp-server-yahoo-finance MCP server

镜子 (jìng zi)

MCP Test Client

MCP Test Client

MCP 测试客户端是一个用于模型上下文协议 (MCP) 服务器的 TypeScript 测试实用程序。

ActionKit MCP Starter

ActionKit MCP Starter

Okay, here's a translation of "Starter code for a MCP server powered by ActionKit" into Chinese, along with a few options depending on the nuance you want to convey: **Option 1 (Most Literal):** * **基于 ActionKit 的 MCP 服务器的起始代码** * (Jīyú ActionKit de MCP fúwùqì de qǐshǐ dàimǎ) This is a direct translation. It's clear and understandable. **Option 2 (Slightly More Natural):** * **使用 ActionKit 构建的 MCP 服务器的初始代码** * (Shǐyòng ActionKit gòujiàn de MCP fúwùqì de chūshǐ dàimǎ) This emphasizes that ActionKit is used to *build* the server. "构建 (gòujiàn)" means "to build" or "to construct." **Option 3 (Focus on Getting Started):** * **用于 ActionKit 驱动的 MCP 服务器的入门代码** * (Yòng yú ActionKit qūdòng de MCP fúwùqì de rùmén dàimǎ) This emphasizes that the code is for *getting started* with an ActionKit-powered server. "入门 (rùmén)" means "entry-level" or "getting started." "驱动 (qūdòng)" means "driven by" or "powered by." **Option 4 (Concise and Common):** * **ActionKit MCP 服务器的初始代码** * (ActionKit MCP fúwùqì de chūshǐ dàimǎ) This is a more concise version, assuming the context makes it clear that the code is *for* the server. It's common to omit "基于" or "使用" in Chinese when it's implied. **Which option is best depends on the specific context:** * If you want to be very precise and literal, use Option 1. * If you want to emphasize the building aspect, use Option 2. * If you want to emphasize that it's for beginners, use Option 3. * If you want a concise and common phrasing, use Option 4. **Key Vocabulary:** * **起始代码 (qǐshǐ dàimǎ) / 初始代码 (chūshǐ dàimǎ):** Starter code, initial code * **MCP 服务器 (MCP fúwùqì):** MCP server * **基于 (jīyú):** Based on * **使用 (shǐyòng):** To use * **构建 (gòujiàn):** To build, to construct * **驱动 (qūdòng):** Driven by, powered by * **入门 (rùmén):** Entry-level, getting started I hope this helps! Let me know if you have any other questions.

Database Analyzer MCP Server

Database Analyzer MCP Server

Wisdom MCP Gateway

Wisdom MCP Gateway

Enterpret Wisdom MCP SSE 服务器的 stdio 网关

Local iMessage RAG MCP Server

Local iMessage RAG MCP Server

来自 Anthropic MCP 黑客马拉松 (纽约) 的 iMessage RAG MCP 服务器

Mcp Namecheap Registrar

Mcp Namecheap Registrar

连接到 Namecheap API,用于检查域名可用性和价格,并注册域名。

MCP Bundler Service

MCP Bundler Service

一个微服务,用于从 GitHub 仓库打包 MCP 服务器,并准备好进行部署。

@enemyrr/mcp-mysql-server

@enemyrr/mcp-mysql-server

镜子 (jìng zi)

MCP Actions Adapter

MCP Actions Adapter

一个简单的适配器,用于将 MCP 服务器转换为与 GPT actions 兼容的 API。

xtrace-mcp

xtrace-mcp

Alpaca MCP Server

Alpaca MCP Server

镜子 (jìng zi)

MCP (Model Context Protocol)

MCP (Model Context Protocol)

一个用于人工智能的简单模型上下文服务器

Servidor MCP do Supabase

Servidor MCP do Supabase

Supabase 具有查询和插入数据功能的 MCP 服务器。

Eka MCP Server

Eka MCP Server

Eka MCP 服务器 (Eka MCP fúwùqì)

Atlassian Jira MCP Server

Atlassian Jira MCP Server

用于 Atlassian Jira 的 Node.js/TypeScript MCP 服务器。为 AI 系统(LLM)配备工具,以列出/获取项目、搜索/获取问题(使用 JQL/ID)以及查看开发信息(提交、PR)。将 AI 功能直接连接到 Jira 项目管理和问题跟踪工作流程中。

Chrome MCP Server

Chrome MCP Server

用于 Chrome 扩展程序和 Claude AI 之间集成的 MCP 服务器

MSSQL MCP Server

MSSQL MCP Server

镜子 (jìng zi)

T2_C2

T2_C2

Please be more specific. "Server code for MCP" is too vague. MCP could refer to many things. To give you relevant information, I need to know which MCP you're referring to. For example, are you looking for: * **Minecraft Protocol (MCP):** If you're referring to the protocol used for Minecraft servers, I can provide information about how to implement a server that uses the Minecraft protocol. This is a complex topic, and I'd need to know which version of Minecraft you're targeting (e.g., 1.19.4, 1.20.1, etc.) and what language you want to use (e.g., Java, Python, C++). I can also provide links to existing libraries that handle the protocol. * **Minecraft Coder Pack (MCP):** If you're referring to the tool used to decompile, deobfuscate, and recompile Minecraft code, I can explain how it works and where to find it. However, I cannot provide the actual decompiled Minecraft code, as that would likely violate copyright. * **A specific application or system named MCP:** If you're referring to a specific application or system that uses the acronym MCP, please provide more context. What does the MCP do? Who developed it? Once you provide more details, I can give you a more helpful and accurate response. In the meantime, here's a general example of a very basic (and incomplete) Minecraft server in Python, just to illustrate the concept: ```python # This is a VERY basic example and not a functional Minecraft server. # It's just to illustrate the concept. You'll need a proper Minecraft # protocol implementation to build a real server. import socket HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 25565 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"Listening on {HOST}:{PORT}") conn, addr = s.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(1024) if not data: break print(f"Received: {data}") # Here you would need to parse the Minecraft protocol data # and respond accordingly. This is where a library like # `mcproto` or similar would be essential. response = b"Hello, client!" # Example response conn.sendall(response) ``` **Important Considerations for a Real Minecraft Server:** * **Minecraft Protocol:** The Minecraft protocol is complex and binary. You'll need to understand how to encode and decode packets. * **Libraries:** Use a library to handle the protocol. Don't try to implement it from scratch unless you have a very good reason. * **Performance:** Minecraft servers need to handle many connections and process data quickly. Choose a language and libraries that are performant. * **Security:** Protect your server from attacks. * **World Generation:** You'll need to generate and manage the game world. * **Player Management:** Handle player authentication, inventory, and other player-related data. Please provide more information about what you're trying to do, and I can give you more specific guidance. --- **Translation to Chinese:** 请更具体地说明。“MCP的服务器代码”太笼统了。 MCP可能指代很多东西。 为了给您提供相关信息,我需要知道您指的是哪个MCP。 例如,您是否在寻找: * **Minecraft协议(MCP):** 如果您指的是用于Minecraft服务器的协议,我可以提供有关如何实现使用Minecraft协议的服务器的信息。 这是一个复杂的主题,我需要知道您要针对哪个版本的Minecraft(例如,1.19.4、1.20.1等)以及您想使用哪种语言(例如,Java,Python,C ++)。 我还可以提供指向现有库的链接,这些库可以处理该协议。 * **Minecraft Coder Pack(MCP):** 如果您指的是用于反编译,反混淆和重新编译Minecraft代码的工具,我可以解释它的工作原理以及在哪里可以找到它。 但是,我无法提供实际的反编译Minecraft代码,因为这可能会侵犯版权。 * **名为MCP的特定应用程序或系统:** 如果您指的是使用首字母缩写词MCP的特定应用程序或系统,请提供更多上下文。 MCP做什么? 谁开发的? 一旦您提供更多详细信息,我就可以给您更有效和准确的答复。 同时,这是一个非常基本的(且不完整的)Python中的Minecraft服务器示例,仅用于说明概念: ```python # 这是一个非常基本的例子,而不是一个功能齐全的Minecraft服务器。 # 这只是为了说明概念。 您需要一个适当的Minecraft协议实现来构建一个真正的服务器。 import socket HOST = '127.0.0.1' # 标准环回接口地址(localhost) PORT = 25565 # 要监听的端口(非特权端口> 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"Listening on {HOST}:{PORT}") conn, addr = s.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(1024) if not data: break print(f"Received: {data}") # 在这里,您需要解析Minecraft协议数据 # 并做出相应的回应。 在这里,像`mcproto`这样的库 # 或类似的东西将是必不可少的。 response = b"Hello, client!" # 示例响应 conn.sendall(response) ``` **实际Minecraft服务器的重要注意事项:** * **Minecraft协议:** Minecraft协议复杂且是二进制的。 您需要了解如何编码和解码数据包。 * **库:** 使用库来处理协议。 除非您有充分的理由,否则不要尝试从头开始实现它。 * **性能:** Minecraft服务器需要处理许多连接并快速处理数据。 选择一种性能良好的语言和库。 * **安全性:** 保护您的服务器免受攻击。 * **世界生成:** 您需要生成和管理游戏世界。 * **玩家管理:** 处理玩家身份验证,库存和其他与玩家相关的数据。 请提供有关您要执行的操作的更多信息,我可以为您提供更具体的指导。

ディーゼロ開発環境用 MCPサーバー

ディーゼロ開発環境用 MCPサーバー

D-Zero 前端编码 MCP 服务器

RapidAPI MCP Server

RapidAPI MCP Server

以下是将 RapidAPI Global Patent API 集成到 MCP 服务器并使用 SQLite 存储的实现方案: **标题:基于 RapidAPI Global Patent API 的 MCP 服务器实现,并使用 SQLite 存储** **概述:** 本方案描述了如何构建一个 MCP (Minimal Control Protocol) 服务器,该服务器利用 RapidAPI 的 Global Patent API 来检索专利数据,并将检索到的数据存储在 SQLite 数据库中。 该服务器将接收来自客户端的请求,调用 RapidAPI 的 Global Patent API,解析响应,并将结果存储到 SQLite 数据库中。 **组件:** * **MCP 服务器:** 负责监听客户端请求,处理请求,调用 RapidAPI,并将结果返回给客户端。 * **RapidAPI Global Patent API:** 提供专利数据检索服务。 * **SQLite 数据库:** 用于存储检索到的专利数据。 * **客户端:** 发送请求到 MCP 服务器,并接收响应。 **技术栈:** * **编程语言:** Python (推荐,易于使用,拥有丰富的库) * **MCP 框架:** 可以使用现有的 MCP 框架,或者自行实现简单的 MCP 协议处理。 * **RapidAPI 客户端库:** 可以使用 `requests` 库或其他 HTTP 客户端库来调用 RapidAPI。 * **SQLite 数据库库:** `sqlite3` (Python 内置) **实现步骤:** 1. **环境搭建:** * 安装 Python。 * 安装必要的 Python 库:`pip install requests` * 安装 SQLite (通常操作系统自带)。 2. **RapidAPI 密钥获取:** * 在 RapidAPI 注册并订阅 Global Patent API。 * 获取 API 密钥 (通常在 RapidAPI 控制面板中)。 3. **SQLite 数据库设计:** * 设计数据库表结构,用于存储专利数据。 例如: * `patents` 表: * `id` (INTEGER PRIMARY KEY AUTOINCREMENT) * `patent_number` (TEXT UNIQUE) * `title` (TEXT) * `abstract` (TEXT) * `inventors` (TEXT) * `assignees` (TEXT) * `filing_date` (TEXT) * `publication_date` (TEXT) * `raw_data` (TEXT) (存储完整的 API 响应,方便后续处理) * `created_at` (TIMESTAMP DEFAULT CURRENT_TIMESTAMP) * 创建数据库和表。 4. **MCP 服务器实现:** * **监听端口:** 服务器监听指定的端口,等待客户端连接。 * **接收请求:** 接收客户端发送的 MCP 请求。 * **解析请求:** 解析 MCP 请求,提取请求参数 (例如,搜索关键词,专利号等)。 * **调用 RapidAPI:** 使用 RapidAPI 密钥和请求参数,调用 Global Patent API。 * **解析响应:** 解析 RapidAPI 返回的 JSON 响应。 * **存储数据到 SQLite:** 将解析后的专利数据存储到 SQLite 数据库中。 * **返回响应:** 将结果 (例如,成功/失败,专利 ID 等) 封装成 MCP 响应,返回给客户端。 5. **客户端实现 (可选):** * 编写客户端程序,用于发送 MCP 请求到服务器,并接收响应。 **代码示例 (Python):** ```python import sqlite3 import requests import json # RapidAPI 配置 RAPIDAPI_KEY = "YOUR_RAPIDAPI_KEY" # 替换为你的 RapidAPI 密钥 RAPIDAPI_HOST = "global-patent.p.rapidapi.com" RAPIDAPI_ENDPOINT = "/patents/search" # SQLite 数据库配置 DATABASE_FILE = "patents.db" def create_table(): conn = sqlite3.connect(DATABASE_FILE) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS patents ( id INTEGER PRIMARY KEY AUTOINCREMENT, patent_number TEXT UNIQUE, title TEXT, abstract TEXT, inventors TEXT, assignees TEXT, filing_date TEXT, publication_date TEXT, raw_data TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() conn.close() def search_patents(query): url = f"https://{RAPIDAPI_HOST}{RAPIDAPI_ENDPOINT}" headers = { "X-RapidAPI-Key": RAPIDAPI_KEY, "X-RapidAPI-Host": RAPIDAPI_HOST } querystring = {"q": query} response = requests.get(url, headers=headers, params=querystring) if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code} - {response.text}") return None def store_patent_data(patent_data): conn = sqlite3.connect(DATABASE_FILE) cursor = conn.cursor() try: patent_number = patent_data.get("patent_number") title = patent_data.get("title") abstract = patent_data.get("abstract") inventors = ", ".join(patent_data.get("inventors", [])) assignees = ", ".join(patent_data.get("assignees", [])) filing_date = patent_data.get("filing_date") publication_date = patent_data.get("publication_date") raw_data = json.dumps(patent_data) cursor.execute(""" INSERT INTO patents (patent_number, title, abstract, inventors, assignees, filing_date, publication_date, raw_data) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, (patent_number, title, abstract, inventors, assignees, filing_date, publication_date, raw_data)) conn.commit() print(f"Patent {patent_number} stored successfully.") except sqlite3.IntegrityError: print(f"Patent {patent_number} already exists in the database.") except Exception as e: print(f"Error storing patent data: {e}") conn.rollback() finally: conn.close() # 示例 MCP 服务器 (简化版) def handle_mcp_request(request): # 假设请求格式为 "SEARCH:关键词" if request.startswith("SEARCH:"): query = request[7:] print(f"Searching for: {query}") patent_results = search_patents(query) if patent_results and patent_results.get("results"): for patent in patent_results["results"]: store_patent_data(patent) return "SEARCH_SUCCESS" else: return "SEARCH_FAILED" else: return "INVALID_REQUEST" # 主程序 if __name__ == "__main__": create_table() # 创建数据库表 # 模拟 MCP 请求 mcp_request = "SEARCH:artificial intelligence" response = handle_mcp_request(mcp_request) print(f"MCP Response: {response}") mcp_request = "SEARCH:blockchain technology" response = handle_mcp_request(mcp_request) print(f"MCP Response: {response}") print("Done.") ``` **关键点:** * **错误处理:** 在调用 RapidAPI 和操作 SQLite 数据库时,需要进行充分的错误处理,例如处理网络错误,API 错误,数据库错误等。 * **数据清洗:** RapidAPI 返回的数据可能需要进行清洗和转换,才能更好地存储到数据库中。 * **并发处理:** 如果服务器需要处理大量的并发请求,需要考虑使用多线程或异步编程来提高性能。 * **安全性:** 保护 RapidAPI 密钥,避免泄露。 对客户端请求进行验证,防止恶意请求。 * **MCP 协议:** 根据实际需求,定义合适的 MCP 协议,包括请求格式,响应格式,错误码等。 * **分页处理:** 如果 RapidAPI 返回的结果集很大,需要进行分页处理,避免一次性加载所有数据。 * **速率限制:** 注意 RapidAPI 的速率限制,避免超过限制导致请求失败。 可以实现速率限制机制,例如使用令牌桶算法。 * **数据更新:** 可以定期更新数据库中的专利数据,以保持数据的最新性。 **改进方向:** * **使用更完善的 MCP 框架:** 例如 Twisted, asyncio 等。 * **添加缓存机制:** 使用 Redis 或 Memcached 等缓存数据库,缓存常用的查询结果,提高响应速度。 * **实现更复杂的搜索功能:** 例如,支持按发明人,申请人,申请日期等进行搜索。 * **提供 API 接口:** 将 MCP 服务器封装成 RESTful API,方便其他应用程序调用。 * **使用 ORM:** 使用 SQLAlchemy 等 ORM 框架,简化数据库操作。 **总结:** 本方案提供了一个将 RapidAPI Global Patent API 集成到 MCP 服务器并使用 SQLite 存储的基本框架。 您可以根据实际需求,对该方案进行修改和扩展,以满足您的特定需求。 请务必替换 `YOUR_RAPIDAPI_KEY` 为您自己的 RapidAPI 密钥。 这个示例代码只是一个起点,你需要根据你的具体需求进行修改和完善。

IACR Cryptology ePrint Archive MCP Server

IACR Cryptology ePrint Archive MCP Server

镜子 (jìng zi)

Grasshopper MCP サーバー

Grasshopper MCP サーバー

用于 Rhinoceros/Grasshopper 集成的模型上下文协议 (MCP) 服务器实现,使 AI 模型能够与参数化设计工具交互。

mcptime

mcptime

Here's the translation of "Simple MCP server to return the current time" into Chinese, along with a few options depending on the nuance you want to convey: **Option 1 (Most Literal and General):** * **简单的 MCP 服务器,用于返回当前时间** (Jiǎndān de MCP fúwùqì, yòng yú fǎnhuí dāngqián shíjiān) * This is a direct translation and is suitable for most contexts. **Option 2 (More Technical, Emphasizing Functionality):** * **一个简单的 MCP 服务器,功能是返回当前时间** (Yī gè jiǎndān de MCP fúwùqì, gōngnéng shì fǎnhuí dāngqián shíjiān) * This emphasizes the *function* of the server. **Option 3 (Slightly More Concise):** * **返回当前时间的简单 MCP 服务器** (Fǎnhuí dāngqián shíjiān de jiǎndān MCP fúwùqì) * This is a bit more concise and reads well in Chinese. **Explanation of Terms:** * **简单 (jiǎndān):** Simple * **的 (de):** A possessive particle (like "of" or "'s" in English) * **MCP 服务器 (MCP fúwùqì):** MCP server (MCP is usually kept as is) * **用于 (yòng yú):** Used for / for the purpose of * **功能是 (gōngnéng shì):** The function is * **返回 (fǎnhuí):** Return * **当前时间 (dāngqián shíjiān):** Current time * **一个 (yī gè):** A / One Choose the option that best fits the specific context where you'll be using the translation. Option 1 is generally a safe and accurate choice.

Weather App

Weather App

Okay, this is a complex request, but I'll provide a conceptual outline and code snippets to illustrate how you might implement a minimal MCP (Microservice Communication Protocol) server for weather data in Python, along with testing and pre-commit setup. I'll focus on clarity and structure rather than production-readiness. **Conceptual Overview** 1. **MCP Definition (Protocol Buffer):** Define the data structures and service interface using Protocol Buffers. This is the core of MCP. 2. **Server Implementation (Python):** Implement a gRPC server in Python that serves weather data based on the MCP definition. 3. **Client (Example):** A simple client to demonstrate how to request data from the server. 4. **Testing (pytest):** Write unit tests to verify the server's functionality. 5. **Pre-commit Hooks:** Configure pre-commit to run linters (e.g., `flake8`, `black`) and tests before committing code. **1. MCP Definition (weather.proto)** Create a file named `weather.proto`: ```protobuf syntax = "proto3"; package weather; service WeatherService { rpc GetWeather(WeatherRequest) returns (WeatherResponse) {} } message WeatherRequest { string city = 1; } message WeatherResponse { string city = 1; float temperature = 2; string condition = 3; } ``` **Explanation:** * `syntax = "proto3";`: Specifies the Protocol Buffer version. * `package weather;`: Defines the package name for the generated code. * `service WeatherService`: Defines the service with a single RPC method `GetWeather`. * `WeatherRequest`: The request message, containing the city name. * `WeatherResponse`: The response message, containing weather information. **2. Generate gRPC Code (Python)** You'll need the `grpcio-tools` package: ```bash pip install grpcio-tools ``` Then, compile the `.proto` file: ```bash python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. weather.proto ``` This will generate two Python files: `weather_pb2.py` (the data structures) and `weather_pb2_grpc.py` (the gRPC service definitions). **3. Server Implementation (server.py)** ```python import grpc from concurrent import futures import weather_pb2 import weather_pb2_grpc class WeatherServicer(weather_pb2_grpc.WeatherServiceServicer): def GetWeather(self, request, context): city = request.city # Simulate weather data (replace with actual data source) if city == "London": temperature = 15.0 condition = "Cloudy" elif city == "New York": temperature = 25.0 condition = "Sunny" else: temperature = 10.0 condition = "Unknown" return weather_pb2.WeatherResponse(city=city, temperature=temperature, condition=condition) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) weather_pb2_grpc.add_WeatherServiceServicer_to_server(WeatherServicer(), server) server.add_insecure_port('[::]:50051') # Listen on all interfaces, port 50051 server.start() server.wait_for_termination() if __name__ == '__main__': print("Starting gRPC server...") serve() ``` **Explanation:** * `WeatherServicer`: Implements the `WeatherServiceServicer` interface defined in `weather_pb2_grpc.py`. * `GetWeather`: The actual implementation of the RPC method. It receives a `WeatherRequest` and returns a `WeatherResponse`. This example uses hardcoded data for simplicity. In a real application, you'd fetch weather data from an external API or database. * `serve`: Creates a gRPC server, registers the `WeatherServicer`, and starts the server. **4. Client (client.py)** ```python import grpc import weather_pb2 import weather_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = weather_pb2_grpc.WeatherServiceStub(channel) city = "London" request = weather_pb2.WeatherRequest(city=city) response = stub.GetWeather(request) print(f"Weather in {response.city}:") print(f" Temperature: {response.temperature}°C") print(f" Condition: {response.condition}") if __name__ == '__main__': run() ``` **Explanation:** * Creates a gRPC channel to connect to the server. * Creates a `WeatherServiceStub` to make RPC calls. * Sends a `WeatherRequest` for the city "London". * Prints the received `WeatherResponse`. **5. Testing (test_server.py)** Install `pytest` and `grpcio-testing`: ```bash pip install pytest grpcio-testing ``` ```python import pytest import grpc from grpc import aio from concurrent import futures import weather_pb2 import weather_pb2_grpc from server import WeatherServicer # Import your server implementation @pytest.fixture def grpc_server(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) weather_pb2_grpc.add_WeatherServiceServicer_to_server(WeatherServicer(), server) port = server.add_insecure_port('[::]:0') # Let the OS choose a port server.start() yield server, port # Provide the server and port to the tests server.stop(0) def test_get_weather(grpc_server): server, port = grpc_server with grpc.insecure_channel(f'localhost:{port}') as channel: stub = weather_pb2_grpc.WeatherServiceStub(channel) request = weather_pb2.WeatherRequest(city="London") response = stub.GetWeather(request) assert response.city == "London" assert response.temperature == 15.0 assert response.condition == "Cloudy" def test_get_weather_new_york(grpc_server): server, port = grpc_server with grpc.insecure_channel(f'localhost:{port}') as channel: stub = weather_pb2_grpc.WeatherServiceStub(channel) request = weather_pb2.WeatherRequest(city="New York") response = stub.GetWeather(request) assert response.city == "New York" assert response.temperature == 25.0 assert response.condition == "Sunny" def test_get_weather_unknown(grpc_server): server, port = grpc_server with grpc.insecure_channel(f'localhost:{port}') as channel: stub = weather_pb2_grpc.WeatherServiceStub(channel) request = weather_pb2.WeatherRequest(city="SomeRandomCity") response = stub.GetWeather(request) assert response.city == "SomeRandomCity" assert response.temperature == 10.0 assert response.condition == "Unknown" ``` **Explanation:** * `grpc_server` fixture: Creates and starts a gRPC server before each test and stops it afterward. It uses a dynamically assigned port to avoid conflicts. * `test_get_weather`: Tests the `GetWeather` method for a specific city ("London"). * `test_get_weather_new_york`: Tests the `GetWeather` method for a specific city ("New York"). * `test_get_weather_unknown`: Tests the `GetWeather` method for an unknown city. Run the tests: ```bash pytest ``` **6. Pre-commit Setup** Install `pre-commit`: ```bash pip install pre-commit ``` Create a `.pre-commit-config.yaml` file in the root of your project: ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 # Use the latest stable version hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-added-large-files - repo: https://github.com/psf/black rev: 24.2.0 # Use the latest stable version hooks: - id: black - repo: https://github.com/pycqa/flake8 rev: 7.0.0 # Use the latest stable version hooks: - id: flake8 additional_dependencies: ["flake8-protobuf"] # Add protobuf support - repo: local hooks: - id: pytest name: pytest entry: pytest language: system types: [python] pass_filenames: false ``` **Explanation:** * This configuration uses several popular pre-commit hooks: * `trailing-whitespace`, `end-of-file-fixer`, `check-yaml`, `check-added-large-files`: Basic cleanup and checks. * `black`: Code formatter. * `flake8`: Linter. The `additional_dependencies` line adds support for linting Protocol Buffer-related code. * `pytest`: Runs your tests. Install the pre-commit hooks: ```bash pre-commit install ``` Now, every time you commit, pre-commit will run these checks and formatters. If any of them fail, the commit will be aborted. **Running the Example** 1. **Generate gRPC code:** `python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. weather.proto` 2. **Start the server:** `python server.py` (in a separate terminal) 3. **Run the client:** `python client.py` 4. **Run the tests:** `pytest` 5. **Commit your changes:** `git commit -m "Your commit message"` (pre-commit will run) **Important Considerations and Improvements** * **Error Handling:** The server implementation lacks proper error handling. You should handle exceptions and return appropriate gRPC status codes. * **Data Source:** The server uses hardcoded weather data. Replace this with a real data source (e.g., an API or database). * **Authentication/Authorization:** For production systems, you'll need to add authentication and authorization to secure your gRPC service. * **Logging:** Implement logging for debugging and monitoring. * **Configuration:** Use environment variables or configuration files to manage server settings (e.g., port number, data source connection details). * **Asynchronous gRPC:** Consider using `grpc.aio` for asynchronous gRPC, which can improve performance, especially for I/O-bound operations. * **Health Checks:** Implement a health check endpoint to allow monitoring systems to verify the server's availability. * **Code Generation:** Consider using a build system (e.g., `make`, `nox`) to automate the code generation process. * **Dependency Management:** Use a tool like `poetry` or `pipenv` to manage your project's dependencies. * **CI/CD:** Integrate your tests and pre-commit hooks into a CI/CD pipeline to automate the build, test, and deployment process. This comprehensive example provides a solid foundation for building a gRPC-based microservice with testing and pre-commit setup. Remember to adapt and extend it to meet the specific requirements of your application.

Playcanvas_editor Mcp Server

Playcanvas_editor Mcp Server

镜子 (jìng zi)

mcp-tools-cli

mcp-tools-cli

用于与模型上下文协议 (MCP) 服务器交互的命令行客户端。