Discover Awesome MCP Servers

Extend your agent with 15,370 capabilities via MCP servers.

All15,370
MCP DateTime Server

MCP DateTime Server

Provides current local datetime information with timezone support. Serves as a minimal blueprint for building simple, single-purpose MCP servers.

Tiger MCP

Tiger MCP

Enables trading and market analysis through Tiger Brokers API integration. Provides real-time market data, portfolio management, order execution, and technical analysis tools with a comprehensive web dashboard for monitoring.

UK Bus Departures MCP Server

UK Bus Departures MCP Server

Enables users to get real-time UK bus departure information and validate bus stop ATCO codes by scraping bustimes.org. Provides structured data including service numbers, destinations, scheduled and expected departure times for any UK bus stop.

Interzoid Weather City API MCP Server

Interzoid Weather City API MCP Server

An MCP server that provides access to the Interzoid GetWeatherCity API, allowing users to retrieve weather information for specified cities through natural language interactions.

Canteen MCP

Canteen MCP

A Model Context Protocol server that provides structured access to canteen lunch menus for specific dates through a simple API integration.

MCP Tailwind Gemini Server

MCP Tailwind Gemini Server

Advanced Model Context Protocol server that integrates Gemini AI with Tailwind CSS, providing intelligent component generation, class optimization, and cross-platform design assistance across major development environments.

Freedcamp MCP Server

Freedcamp MCP Server

A Model Context Protocol server that enables seamless integration with Freedcamp API for enterprise-level project management with advanced filtering, full CRUD operations, and extensive customization options.

MCP Servers for Teams

MCP Servers for Teams

MCPサーバーのデプロイ例

Google Search MCP Server

Google Search MCP Server

Enables users to perform Google Custom Search queries through the Model Context Protocol. Requires Google API credentials and Custom Search Engine configuration for web search functionality.

Arcjet - MCP Server

Arcjet - MCP Server

Arcjet Model Context Protocol (MCP) server. Help your AI agents implement bot detection, rate limiting, email validation, attack protection, data redaction.

SAP BusinessObjects BI MCP Server by CData

SAP BusinessObjects BI MCP Server by CData

This project builds a read-only MCP server. For full read, write, update, delete, and action capabilities and a simplified setup, check out our free CData MCP Server for SAP BusinessObjects BI (beta): https://www.cdata.com/download/download.aspx?sku=GJZK-V&type=beta

My Coding Buddy MCP Server

My Coding Buddy MCP Server

A personal AI coding assistant that connects to various development environments and helps automate tasks, provide codebase insights, and improve coding decisions by leveraging the Model Context Protocol.

mcp-server-cloudbrowser

mcp-server-cloudbrowser

NexusMind

NexusMind

An MCP server that leverages graph structures to perform sophisticated scientific reasoning through an 8-stage processing pipeline, enabling AI systems to handle complex scientific queries with dynamic confidence scoring.

Xero MCP Server

Xero MCP Server

Xero会計ソフトと連携できるMCPサーバー

Simple MCP Search Server

Simple MCP Search Server

FastMCP Server Generator

FastMCP Server Generator

カスタムMCPサーバーの作成を支援する専門的なMCPサーバー

Mcp Akshare

Mcp Akshare

AKShareは、Pythonをベースとした金融データインターフェースライブラリであり、株式、先物、オプション、ファンド、外国為替、債券、指数、暗号通貨などの金融商品のファンダメンタルデータ、リアルタイムおよび過去の相場データ、派生データを、データ収集、データクレンジングからデータ格納まで一貫して行うためのツールです。主に学術研究を目的としています。

MCP Montano Server

MCP Montano Server

ETH Price Current Server

ETH Price Current Server

A minimal Model Context Protocol (MCP) server that fetches the current Ethereum (ETH) price in USD. Data source: the public CoinGecko API (no API key required). This MCP is designed to simulate malicious behavior, specifically an attempt to mislead LLM to return incorrect results.

A MCP server for Godot RAG

A MCP server for Godot RAG

このMCPサーバーは、Godot RAGモデルにGodotドキュメントを提供するために使用されます。

MCP Demo Server

MCP Demo Server

A minimal fastmcp demonstration server that provides a simple addition tool through the MCP protocol, supporting deployment via Docker with multiple transport modes.

Taximail

Taximail

Cars MCP Server

Cars MCP Server

Okay, here's a basic example of an MCP (Minecraft Protocol) server integrated with Spring AI, along with explanations to help you understand the code and concepts. This is a simplified example to illustrate the core ideas. A real-world MCP server is significantly more complex. **Conceptual Overview** 1. **MCP Server:** This is the core of your Minecraft server. It listens for incoming connections from Minecraft clients, handles authentication, and manages game logic. We'll use a very basic socket server for demonstration. 2. **Spring AI:** This framework provides abstractions for interacting with AI models (like large language models). We'll use it to process player commands or generate content. 3. **Integration:** The MCP server receives a command from a player. It passes this command to Spring AI for processing. The AI generates a response, and the MCP server sends that response back to the player. **Code Example (Java with Spring Boot)** ```java // build.gradle.kts (or pom.xml) // Add these dependencies: // implementation("org.springframework.boot:spring-boot-starter-web") // implementation("org.springframework.ai:spring-ai-openai-spring-boot-starter:0.8.0") // Or the latest version // implementation("org.springframework.ai:spring-ai-spring-boot-starter:0.8.0") // Core Spring AI // implementation("org.springframework.boot:spring-boot-starter-websocket") // For potential WebSocket communication // implementation("org.springframework.boot:spring-boot-starter-integration") // For integration components // implementation("org.slf4j:slf4j-api") // Logging // runtimeOnly("ch.qos.logback:logback-classic") // Logging implementation import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.client.AiClient; import org.springframework.ai.client.AiResponse; import org.springframework.ai.prompt.PromptTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @SpringBootApplication public class McpAiServerApplication { private static final Logger logger = LoggerFactory.getLogger(McpAiServerApplication.class); @Autowired private AiClient aiClient; @Value("${mcp.server.port:25565}") // Default Minecraft port private int serverPort; @Value("${spring.ai.prompt.template:You are a helpful Minecraft assistant. Respond to the user's command: {command}}") private String promptTemplateString; public static void main(String[] args) { SpringApplication.run(McpAiServerApplication.class, args); } @Bean public CommandLineRunner commandLineRunner() { return args -> { ExecutorService executor = Executors.newFixedThreadPool(10); // Thread pool for handling clients try (ServerSocket serverSocket = new ServerSocket(serverPort)) { logger.info("MCP Server started on port: {}", serverPort); while (true) { Socket clientSocket = serverSocket.accept(); logger.info("Client connected: {}", clientSocket.getInetAddress().getHostAddress()); executor.submit(new ClientHandler(clientSocket, aiClient, promptTemplateString)); } } catch (IOException e) { logger.error("Server exception: {}", e.getMessage(), e); } finally { executor.shutdown(); } }; } private static class ClientHandler implements Runnable { private final Socket clientSocket; private final AiClient aiClient; private final String promptTemplateString; public ClientHandler(Socket socket, AiClient aiClient, String promptTemplateString) { this.clientSocket = socket; this.aiClient = aiClient; this.promptTemplateString = promptTemplateString; } @Override public void run() { try ( PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())) ) { String inputLine; while ((inputLine = in.readLine()) != null) { logger.info("Received command: {}", inputLine); // Process the command with Spring AI String aiResponse = processCommandWithAI(inputLine); // Send the AI response back to the client out.println(aiResponse); } } catch (IOException e) { logger.error("Client handler exception: {}", e.getMessage(), e); } finally { try { clientSocket.close(); logger.info("Client disconnected: {}", clientSocket.getInetAddress().getHostAddress()); } catch (IOException e) { logger.error("Error closing socket: {}", e.getMessage(), e); } } } private String processCommandWithAI(String command) { PromptTemplate promptTemplate = new PromptTemplate(promptTemplateString); Map<String, Object> model = new HashMap<>(); model.put("command", command); String prompt = promptTemplate.render(model); AiResponse response = aiClient.generate(prompt); return response.getGeneration().getText(); } } } ``` **Explanation:** 1. **Dependencies:** The `build.gradle.kts` (or `pom.xml`) file includes the necessary Spring Boot, Spring AI, and logging dependencies. Make sure you have these in your project. The `spring-ai-openai-spring-boot-starter` is crucial if you're using OpenAI. If you're using a different AI provider, include the appropriate starter. 2. **`McpAiServerApplication`:** * This is the main Spring Boot application class. * `@SpringBootApplication`: Marks this as a Spring Boot application. * `@Autowired AiClient aiClient`: Injects the `AiClient` bean, which is configured by Spring AI to interact with your chosen AI model. You'll need to configure your `application.properties` or `application.yml` file with your AI provider's API key (see below). * `@Value("${mcp.server.port:25565}")`: Injects the server port from the application properties. The default value is 25565 (the standard Minecraft port). * `@Value("${spring.ai.prompt.template: ...}")`: Injects the prompt template from the application properties. This allows you to customize the prompt sent to the AI model. * `commandLineRunner()`: This `CommandLineRunner` bean is executed after the application starts. It contains the main server logic. * `ExecutorService`: A thread pool is used to handle multiple client connections concurrently. * `ServerSocket`: Listens for incoming connections on the specified port. * `ClientHandler`: A `Runnable` class that handles communication with a single client. It's submitted to the `ExecutorService` for execution. 3. **`ClientHandler`:** * `run()`: This method is executed in a separate thread for each client. * `PrintWriter` and `BufferedReader`: Used for sending and receiving data from the client. * The `while` loop reads commands from the client. * `processCommandWithAI()`: This method takes the command, constructs a prompt using the `PromptTemplate`, and sends it to the AI model using the `AiClient`. It then returns the AI's response. * The AI's response is sent back to the client. * The `finally` block ensures that the socket is closed when the client disconnects. 4. **`processCommandWithAI()`:** * `PromptTemplate`: Creates a prompt template from the configured string. * `Map<String, Object> model`: Creates a map to hold the command that will be inserted into the prompt template. * `promptTemplate.render(model)`: Renders the prompt template with the command. * `aiClient.generate(prompt)`: Sends the prompt to the AI model and receives a response. * `response.getGeneration().getText()`: Extracts the text from the AI's response. **Configuration (application.properties or application.yml)** You'll need to configure your Spring AI provider in your `application.properties` or `application.yml` file. Here's an example for OpenAI: ```properties # application.properties spring.ai.openai.api-key=YOUR_OPENAI_API_KEY spring.ai.openai.chat.options.model=gpt-3.5-turbo # Or gpt-4, etc. mcp.server.port=25565 spring.ai.prompt.template=You are a helpful Minecraft assistant. Respond to the user's command: {command} ``` Or, in `application.yml`: ```yaml spring: ai: openai: api-key: YOUR_OPENAI_API_KEY chat: options: model: gpt-3.5-turbo # Or gpt-4, etc. mcp: server: port: 25565 spring: ai: prompt: template: You are a helpful Minecraft assistant. Respond to the user's command: {command} ``` **Important Notes:** * **Replace `YOUR_OPENAI_API_KEY` with your actual OpenAI API key.** You can get an API key from the OpenAI website. * **Error Handling:** This example has basic error handling, but you'll need to add more robust error handling for a production environment. Consider handling exceptions related to network connections, AI API calls, and invalid commands. * **Security:** This example doesn't include any security measures. In a real-world server, you'll need to implement authentication and authorization to protect your server from unauthorized access. * **Minecraft Protocol:** This example uses a very simplified text-based protocol. The real Minecraft protocol is binary and much more complex. You'll need to use a library like `mcprotocollib` or similar to handle the actual Minecraft protocol. * **AI Cost:** Using AI models can be expensive. Be mindful of your API usage and costs. * **Rate Limiting:** AI providers often have rate limits. Implement rate limiting in your server to avoid exceeding these limits. * **Prompt Engineering:** The quality of the AI's responses depends heavily on the prompt you provide. Experiment with different prompts to get the best results. * **Asynchronous Processing:** For a more responsive server, consider using asynchronous processing (e.g., Spring's `@Async` annotation or Reactive Streams) to handle AI requests in the background. This will prevent the server from blocking while waiting for the AI to respond. * **WebSocket:** For real-time communication with the client, consider using WebSockets instead of plain sockets. Spring Boot provides excellent support for WebSockets. **How to Run:** 1. Make sure you have Java and Maven or Gradle installed. 2. Create a new Spring Boot project. 3. Add the dependencies to your `build.gradle.kts` or `pom.xml` file. 4. Create the `McpAiServerApplication` class. 5. Configure your `application.properties` or `application.yml` file with your OpenAI API key and other settings. 6. Run the application. **Testing:** You can test the server using a simple telnet client or a custom Minecraft client that sends text-based commands. For example, you could use `telnet localhost 25565` and then type commands like "What is the recipe for a wooden pickaxe?" **Next Steps:** 1. **Implement the Minecraft Protocol:** Use a library like `mcprotocollib` to handle the actual Minecraft protocol. 2. **Add Authentication:** Implement authentication to verify the identity of players. 3. **Implement Game Logic:** Add game logic to handle player actions, world generation, and other game-related tasks. 4. **Improve AI Integration:** Experiment with different prompts and AI models to improve the quality of the AI's responses. 5. **Add a User Interface:** Create a user interface for managing the server and interacting with the AI. This example provides a basic foundation for building an MCP server with Spring AI. You'll need to expand on this example to create a fully functional server. Good luck! **Japanese Translation of Key Concepts:** * **MCP (Minecraft Protocol):** Minecraftプロトコル * **Spring AI:** Spring AI (スプリングAI) * **AI Model:** AIモデル * **Prompt:** プロンプト * **Server:** サーバー * **Client:** クライアント * **API Key:** APIキー * **Authentication:** 認証 (にんしょう) * **Authorization:** 認可 (にんか) * **Game Logic:** ゲームロジック * **Thread Pool:** スレッドプール * **Socket:** ソケット * **Dependency:** 依存関係 (いぞんかんけい) * **Configuration:** 設定 (せってい) * **Error Handling:** エラー処理 (しょり) * **Asynchronous Processing:** 非同期処理 (ひどうきしょり) * **Rate Limiting:** レート制限 (せいげん) This should give you a good starting point. Remember to adapt the code and configuration to your specific needs and AI provider. Let me know if you have any more questions.

mcp_server

mcp_server

Okay, I understand. You want me to describe how to implement a weather MCP (Message Passing Communication) server that can be called by a client IDE like Cursor. Here's a breakdown of the implementation, covering key aspects and considerations: **1. Core Concepts and Technologies** * **MCP (Message Passing Communication):** The server and client will communicate by exchanging messages. This is a general concept, and you'll need to choose a specific protocol for message formatting and transport. Common choices include: * **JSON-RPC:** A simple, lightweight RPC protocol that uses JSON for message encoding. It's well-suited for this kind of application. * **gRPC:** A high-performance RPC framework developed by Google. It uses Protocol Buffers for message serialization and supports multiple languages. It's more complex than JSON-RPC but offers better performance and type safety. * **WebSockets:** Provides full-duplex communication over a single TCP connection. Useful if you want real-time updates or a persistent connection. * **Server-Side Language/Framework:** Choose a language and framework suitable for building a server. Good options include: * **Python (with Flask or FastAPI):** Easy to learn, has excellent libraries for web development and JSON handling. Flask is a microframework, while FastAPI is a modern, high-performance framework. * **Node.js (with Express):** JavaScript runtime environment. Express is a popular web framework. * **Go (with net/http or Gin):** A fast, efficient language. Gin is a lightweight web framework. * **Java (with Spring Boot):** A robust and widely used framework for building enterprise applications. * **Weather Data Source:** You'll need an API to fetch weather data. Popular options include: * **OpenWeatherMap:** Offers a free tier with limitations and paid plans for more features. * **WeatherAPI.com:** Another popular option with a free tier and paid plans. * **AccuWeather:** Provides weather data and forecasts. * **National Weather Service (NWS) API (US):** Free and open data, but only for the US. * **IDE Client (Cursor):** You'll need to write code within Cursor (or a similar IDE) to send requests to the weather server and display the results. This will likely involve using the IDE's capabilities for making HTTP requests or establishing a WebSocket connection. **2. Server-Side Implementation (Example using Python and Flask/FastAPI with JSON-RPC)** ```python # Example using Flask from flask import Flask, request, jsonify import requests import os app = Flask(__name__) # Replace with your actual API key and weather API endpoint WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY") # Get API key from environment variable WEATHER_API_URL = "http://api.openweathermap.org/data/2.5/weather" def get_weather(city): """Fetches weather data from the OpenWeatherMap API.""" try: params = { 'q': city, 'appid': WEATHER_API_KEY, 'units': 'metric' # Use Celsius } response = requests.get(WEATHER_API_URL, params=params) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) data = response.json() return { 'city': data['name'], 'temperature': data['main']['temp'], 'description': data['weather'][0]['description'], 'humidity': data['main']['humidity'], 'wind_speed': data['wind']['speed'] } except requests.exceptions.RequestException as e: return {'error': f"Error fetching weather data: {e}"} except KeyError: return {'error': "Invalid weather data format received."} except Exception as e: return {'error': f"An unexpected error occurred: {e}"} @app.route('/', methods=['POST']) def handle_request(): """Handles JSON-RPC requests.""" try: request_data = request.get_json() method = request_data.get('method') params = request_data.get('params', {}) request_id = request_data.get('id') if method == 'get_weather': city = params.get('city') if not city: result = {'error': 'City parameter is required'} else: result = get_weather(city) else: result = {'error': 'Method not found'} response = { 'jsonrpc': '2.0', 'result': result, 'id': request_id } return jsonify(response) except Exception as e: response = { 'jsonrpc': '2.0', 'error': str(e), 'id': None } return jsonify(response), 500 # Internal Server Error if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000) # Listen on all interfaces ``` **Explanation of the Python/Flask Example:** 1. **Imports:** Imports necessary libraries (Flask, requests, jsonify). 2. **API Key:** Stores the OpenWeatherMap API key. **Important:** It's best practice to store API keys in environment variables rather than hardcoding them in your script. The code uses `os.environ.get("WEATHER_API_KEY")` to retrieve the key from the environment. 3. **`get_weather(city)` Function:** * Takes a city name as input. * Constructs the API request URL with the city and API key. * Uses the `requests` library to make the API call. * Handles potential errors (e.g., network errors, invalid API key, city not found). * Parses the JSON response from the weather API and extracts relevant information (temperature, description, etc.). * Returns a dictionary containing the weather data or an error message. 4. **`handle_request()` Function:** * This is the Flask route that handles incoming requests. It's mapped to the root URL (`/`) and only accepts POST requests. * Parses the JSON request body using `request.get_json()`. * Extracts the `method`, `params`, and `id` from the JSON-RPC request. * If the `method` is `get_weather`: * Extracts the `city` parameter from the `params`. * Calls the `get_weather()` function to fetch the weather data. * Constructs a JSON-RPC response with the `result` (weather data or error) and the original `id`. * Returns the JSON response using `jsonify()`. * Includes error handling to catch exceptions and return appropriate JSON-RPC error responses. 5. **`if __name__ == '__main__':` Block:** * Starts the Flask development server when the script is run directly. * `debug=True` enables debugging mode (useful during development). **Important:** Disable debugging mode in production. * `host='0.0.0.0'` makes the server accessible from any IP address (useful for testing on different machines). In production, you might want to bind to a specific IP address. * `port=5000` specifies the port the server will listen on. **Example using FastAPI** ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel import requests import os app = FastAPI() WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY") WEATHER_API_URL = "http://api.openweathermap.org/data/2.5/weather" class WeatherResponse(BaseModel): city: str temperature: float description: str humidity: int wind_speed: float class ErrorResponse(BaseModel): error: str @app.post("/get_weather", response_model=WeatherResponse, responses={500: {"model": ErrorResponse}}) async def get_weather(city: str): """Fetches weather data for a given city.""" try: params = { 'q': city, 'appid': WEATHER_API_KEY, 'units': 'metric' } response = requests.get(WEATHER_API_URL, params=params) response.raise_for_status() data = response.json() return WeatherResponse( city=data['name'], temperature=data['main']['temp'], description=data['weather'][0]['description'], humidity=data['main']['humidity'], wind_speed=data['wind']['speed'] ) except requests.exceptions.RequestException as e: raise HTTPException(status_code=500, detail=f"Error fetching weather data: {e}") except KeyError: raise HTTPException(status_code=500, detail="Invalid weather data format received.") except Exception as e: raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}") ``` **Explanation of the Python/FastAPI Example:** 1. **Imports:** Imports necessary libraries (FastAPI, pydantic, requests). 2. **API Key:** Same as Flask example, retrieves API key from environment variable. 3. **Data Models (Pydantic):** Defines `WeatherResponse` and `ErrorResponse` models using Pydantic. This provides type validation and automatic data serialization/deserialization. 4. **`get_weather(city: str)` Function:** * Uses FastAPI's dependency injection to receive the `city` as a query parameter. * The rest of the logic is similar to the Flask example, but it uses `raise HTTPException` to return HTTP error responses with appropriate status codes and error messages. * Returns a `WeatherResponse` object if successful. 5. **FastAPI Decorators:** * `@app.post("/get_weather", response_model=WeatherResponse, responses={500: {"model": ErrorResponse}})`: This decorator defines the endpoint: * `/get_weather`: The URL path. * `response_model=WeatherResponse`: Specifies the data model for successful responses. * `responses={500: {"model": ErrorResponse}}`: Specifies the data model for 500 Internal Server Error responses. **3. Client-Side Implementation (Cursor IDE)** ```javascript // Example JavaScript code to run within Cursor (or a similar IDE) async function getWeather(city) { const serverUrl = 'http://localhost:5000/'; // Replace with your server URL const requestBody = { jsonrpc: '2.0', method: 'get_weather', params: { city: city }, id: 1 // Unique ID for the request }; try { const response = await fetch(serverUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) }); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); if (data.error) { console.error('Error from server:', data.error); return null; // Or handle the error appropriately } const weatherData = data.result; if (weatherData.error) { console.error('Error from weather API:', weatherData.error); return null; } console.log('Weather in', weatherData.city); console.log('Temperature:', weatherData.temperature, '°C'); console.log('Description:', weatherData.description); console.log('Humidity:', weatherData.humidity, '%'); console.log('Wind Speed:', weatherData.wind_speed, 'm/s'); return weatherData; // Return the weather data } catch (error) { console.error('Error:', error); return null; // Or handle the error appropriately } } // Example usage: getWeather('London') .then(weather => { if (weather) { // Do something with the weather data (e.g., display it in the IDE) console.log('Weather data received:', weather); } else { console.log('Failed to get weather data.'); } }); ``` **Explanation of the JavaScript Client Code:** 1. **`getWeather(city)` Function:** * Takes a city name as input. * Defines the `serverUrl` (the address of your weather server). **Important:** Make sure this URL is correct. * Constructs the JSON-RPC request body with the `method`, `params`, and `id`. * Uses the `fetch` API to make a POST request to the server. * Sets the `Content-Type` header to `application/json`. * Stringifies the request body using `JSON.stringify()`. * Handles potential errors (e.g., network errors, server errors). * Parses the JSON response from the server using `response.json()`. * Checks for errors in the response (both JSON-RPC errors and errors from the weather API). * Extracts the weather data from the `data.result` field. * Logs the weather information to the console. * Returns the weather data. 2. **Example Usage:** * Calls the `getWeather()` function with a city name. * Uses a `.then()` block to handle the result of the asynchronous `getWeather()` function. * If the weather data is successfully retrieved, it logs the data to the console. * If there's an error, it logs an error message. **How to Use in Cursor:** 1. **Create a JavaScript File:** Create a new JavaScript file (e.g., `weather_client.js`) in your Cursor project. 2. **Paste the Code:** Paste the JavaScript code into the file. 3. **Modify the `serverUrl`:** Make sure the `serverUrl` in the code points to the correct address of your weather server (e.g., `http://localhost:5000/`). 4. **Run the Code:** You can run the code in Cursor's integrated terminal or by using a JavaScript execution environment within the IDE. The output (weather information or error messages) will be displayed in the console. **4. Key Considerations and Enhancements** * **Error Handling:** Implement robust error handling on both the server and client sides. This includes handling network errors, API errors, invalid input, and unexpected exceptions. Return informative error messages to the client. * **API Key Security:** Never hardcode your API key directly in your code. Store it in an environment variable or a configuration file and load it at runtime. This prevents your API key from being exposed if you share your code. * **Rate Limiting:** Be aware of the rate limits of the weather API you're using. Implement caching or other strategies to avoid exceeding the rate limits. * **Data Validation:** Validate the input data (e.g., city name) on the server side to prevent errors and security vulnerabilities. * **Asynchronous Operations:** Use asynchronous operations (e.g., `async/await` in JavaScript and Python) to avoid blocking the main thread and improve performance. * **Logging:** Implement logging on the server side to track requests, errors, and other important events. This can be helpful for debugging and monitoring. * **Authentication/Authorization:** If you need to restrict access to your weather server, implement authentication and authorization mechanisms. * **Deployment:** Consider how you will deploy your weather server. Options include: * **Local Development:** Run the server on your local machine for testing. * **Cloud Platform (e.g., AWS, Google Cloud, Azure):** Deploy the server to a cloud platform for production use. * **Containerization (Docker):** Package the server in a Docker container for easy deployment and portability. * **Testing:** Write unit tests and integration tests to ensure that your server and client code are working correctly. * **Documentation:** Document your API and code to make it easier for others (and yourself) to understand and use. * **JSON-RPC Library:** Consider using a dedicated JSON-RPC library for your chosen language. These libraries can simplify the process of handling JSON-RPC requests and responses. For example, in Python, you could use `jsonrpcserver`. * **CORS (Cross-Origin Resource Sharing):** If your client-side code is running in a browser and your server is running on a different domain, you'll need to configure CORS on the server to allow cross-origin requests. Flask and FastAPI have built-in support for CORS. **Example JSON-RPC Request (from Client to Server):** ```json { "jsonrpc": "2.0", "method": "get_weather", "params": { "city": "New York" }, "id": 123 } ``` **Example JSON-RPC Response (from Server to Client - Success):** ```json { "jsonrpc": "2.0", "result": { "city": "New York", "temperature": 25.5, "description": "Clear sky", "humidity": 60, "wind_speed": 5.2 }, "id": 123 } ``` **Example JSON-RPC Response (from Server to Client - Error):** ```json { "jsonrpc": "2.0", "error": "City not found", "id": 123 } ``` This comprehensive guide should give you a solid foundation for implementing your weather MCP server and client. Remember to adapt the code and configurations to your specific needs and environment. Good luck!

ms_salespower_mcp

ms_salespower_mcp

MCPサーバーを介して、一般的なAIチャット内で使用できる、有用なセールスユースケースを有効にします。

GS Robot MCP Server

GS Robot MCP Server

A Model Control Protocol plugin for controlling GS cleaning robots, supporting robot listing, status monitoring, navigation commands, task execution, and remote control operations.

MCP Server for Coroot

MCP Server for Coroot

A Model Context Protocol server that provides seamless integration with Coroot observability platform, enabling monitoring of applications, analysis of performance metrics, examination of logs and traces, and management of infrastructure through Coroot's comprehensive API.

Chinese Calendar Mcp

Chinese Calendar Mcp

GLM-4.5V MCP Server

GLM-4.5V MCP Server

Enables multimodal AI capabilities through GLM-4.5V API for image processing, visual querying with OCR/QA/detection modes, and file content extraction from various formats including PDFs, documents, and images.