Discover Awesome MCP Servers

Extend your agent with 17,214 capabilities via MCP servers.

All17,214
Cars MCP Server

Cars MCP Server

Okay, here's a basic example of how you might set up a simple Minecraft Protocol (MCP) server using Spring AI concepts. Keep in mind that this is a *very* high-level outline. Building a full MCP server is a complex undertaking. This example focuses on illustrating how Spring AI *could* be integrated for certain aspects, not on providing a complete, production-ready server. **Conceptual Overview** The core idea is to use Spring AI to handle certain aspects of the server logic, such as: * **Natural Language Command Processing:** Allow players to issue commands in natural language, which Spring AI can then translate into specific server actions. * **Dynamic Content Generation:** Use AI to generate quests, stories, or even world elements on the fly. * **NPC Behavior:** Control the behavior of non-player characters (NPCs) using AI models. **Simplified Example (Focusing on Command Processing)** Let's focus on the command processing aspect for this example. **1. Project Setup (Maven/Gradle)** You'll need a Spring Boot project. Here's a basic `pom.xml` (Maven) with the necessary dependencies: ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> <!-- Use the latest Spring Boot version --> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mcp-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mcp-server</name> <description>Basic MCP Server with Spring AI</description> <properties> <java.version>17</java.version> <spring-ai.version>1.0.0-M2</spring-ai.version> <!-- Use the latest Spring AI version --> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Spring AI Dependencies --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-core</artifactId> <version>${spring-ai.version}</version> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai</artifactId> <version>${spring-ai.version}</version> </dependency> <!-- Netty for MCP Communication (Example) --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.100.Final</version> <!-- Use the latest Netty version --> </dependency> <!-- Lombok for boilerplate code reduction --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project> ``` **Important:** * Replace `3.2.0` and `1.0.0-M2` with the latest stable versions of Spring Boot and Spring AI, respectively. * You'll need an OpenAI API key. Set it as an environment variable or in your `application.properties` file. * This example uses Netty for handling the network communication. You could use other libraries as well. **2. `application.properties` (or `application.yml`)** ```properties spring.ai.openai.api-key=YOUR_OPENAI_API_KEY ``` **3. MCP Server (Simplified with Netty)** ```java package com.example.mcpserver; 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.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import lombok.RequiredArgsConstructor; import org.springframework.ai.client.AiClient; import org.springframework.ai.prompt.PromptTemplate; 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; @SpringBootApplication public class McpServerApplication { public static void main(String[] args) { SpringApplication.run(McpServerApplication.class, args); } @Bean public CommandLineRunner run(McpServer mcpServer) { return args -> { mcpServer.start(); }; } @Bean public McpServer mcpServer(AiClient aiClient, @Value("${server.port:25565}") int port) { return new McpServer(aiClient, port); } } @RequiredArgsConstructor class McpServer { private final AiClient aiClient; private final int port; public void start() 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) { ChannelPipeline p = ch.pipeline(); p.addLast(new StringDecoder(), new StringEncoder(), new McpServerHandler(aiClient)); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); System.out.println("MCP Server started on port " + port); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } @RequiredArgsConstructor class McpServerHandler extends ChannelInboundHandlerAdapter { private final AiClient aiClient; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { String command = (String) msg; System.out.println("Received command: " + command); // Use Spring AI to process the command String aiResponse = processCommand(command); // Send the response back to the client ctx.writeAndFlush(aiResponse + "\n"); } private String processCommand(String command) { // Define a prompt template for command processing String promptString = "You are a Minecraft server assistant. The player said: {command}. Determine the appropriate Minecraft command and explain it to the user. If the command is not valid, respond with an error message."; PromptTemplate promptTemplate = new PromptTemplate(promptString); // Create a prompt with the player's command org.springframework.ai.prompt.Prompt prompt = promptTemplate.create(org.springframework.ai.prompt.PromptTemplate.map("command", command)); // Call the AI model String aiResponse = aiClient.generate(prompt).getGeneration().getText(); return aiResponse; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` **Explanation:** 1. **Dependencies:** The `pom.xml` includes Spring AI, Netty, and Lombok. 2. **`application.properties`:** Sets the OpenAI API key. 3. **`McpServerApplication`:** The main Spring Boot application class. It creates the `McpServer` bean and starts it when the application runs. 4. **`McpServer`:** This class uses Netty to create a simple TCP server. It listens for incoming connections on the specified port. 5. **`McpServerHandler`:** This class handles incoming messages (commands) from clients. * It receives the command as a string. * It uses Spring AI's `AiClient` to process the command. * It sends the AI-generated response back to the client. 6. **`processCommand`:** * Defines a prompt template that instructs the AI model to act as a Minecraft server assistant. * Creates a `Prompt` object with the player's command. * Calls the `AiClient` to generate a response based on the prompt. **How it Works:** 1. The server starts and listens for connections. 2. A player connects to the server. 3. The player sends a command (e.g., "I want to build a house"). 4. The `McpServerHandler` receives the command. 5. The `processCommand` method constructs a prompt for the AI model, including the player's command. 6. The `AiClient` sends the prompt to the OpenAI API. 7. The OpenAI API generates a response (e.g., "To build a house, you'll need wood, stone, and a crafting table. The command to get wood is `/give @p minecraft:oak_log 64`"). 8. The `McpServerHandler` sends the AI-generated response back to the player. **To Run:** 1. Make sure you have Java 17 or later installed. 2. Set the `spring.ai.openai.api-key` property in `application.properties` with your OpenAI API key. 3. Run the Spring Boot application. 4. Use a simple TCP client (like `netcat` or a custom client) to connect to the server on the specified port (default 25565). 5. Send commands to the server. **Important Considerations:** * **Security:** This is a *very* basic example and does not include any security measures. In a real-world MCP server, you would need to implement proper authentication, authorization, and input validation to prevent malicious attacks. * **MCP Protocol:** This example doesn't implement the full Minecraft Protocol. You would need to handle the protocol handshake, packet encoding/decoding, and other protocol-specific details. Libraries like `mc-netty` can help with this. * **Error Handling:** The error handling in this example is minimal. You should add more robust error handling to catch exceptions and provide informative error messages to the player. * **AI Model Cost:** Using OpenAI's API can incur costs. Be mindful of your usage and set up billing alerts. * **Prompt Engineering:** The quality of the AI's responses depends heavily on the prompt you provide. Experiment with different prompts to get the desired behavior. * **Rate Limiting:** The OpenAI API has rate limits. Implement rate limiting in your server to avoid exceeding these limits. * **Context Management:** For more complex interactions, you'll need to manage the context of the conversation with the player. This could involve storing the player's inventory, location, and other relevant information. **Further Development:** * **Implement the full MCP protocol:** Use a library like `mc-netty` to handle the protocol details. * **Add more AI-powered features:** * Dynamic quest generation. * NPC behavior control. * World generation. * **Improve the command processing:** * Add support for more complex commands. * Implement command validation. * Provide more helpful feedback to the player. * **Integrate with a Minecraft server API:** If you want to modify the game world directly, you'll need to integrate with a Minecraft server API like Bukkit or Spigot. **In Portuguese (Translation):** Aqui está um exemplo básico de como você pode configurar um servidor Minecraft Protocol (MCP) simples usando conceitos do Spring AI. Lembre-se de que este é um esboço *muito* geral. Construir um servidor MCP completo é uma tarefa complexa. Este exemplo se concentra em ilustrar como o Spring AI *poderia* ser integrado para certos aspectos, não em fornecer um servidor completo e pronto para produção. **Visão Geral Conceitual** A ideia central é usar o Spring AI para lidar com certos aspectos da lógica do servidor, como: * **Processamento de Comandos em Linguagem Natural:** Permitir que os jogadores emitam comandos em linguagem natural, que o Spring AI pode então traduzir em ações específicas do servidor. * **Geração Dinâmica de Conteúdo:** Usar IA para gerar missões, histórias ou até mesmo elementos do mundo em tempo real. * **Comportamento de NPCs:** Controlar o comportamento de personagens não jogáveis (NPCs) usando modelos de IA. **Exemplo Simplificado (Focando no Processamento de Comandos)** Vamos nos concentrar no aspecto do processamento de comandos para este exemplo. **1. Configuração do Projeto (Maven/Gradle)** Você precisará de um projeto Spring Boot. Aqui está um `pom.xml` básico (Maven) com as dependências necessárias: ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> <!-- Use a versão mais recente do Spring Boot --> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mcp-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mcp-server</name> <description>Basic MCP Server with Spring AI</description> <properties> <java.version>17</java.version> <spring-ai.version>1.0.0-M2</spring-ai.version> <!-- Use a versão mais recente do Spring AI --> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Spring AI Dependencies --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-core</artifactId> <version>${spring-ai.version}</version> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai</artifactId> <version>${spring-ai.version}</version> </dependency> <!-- Netty for MCP Communication (Example) --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.100.Final</version> <!-- Use a versão mais recente do Netty --> </dependency> <!-- Lombok for boilerplate code reduction --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project> ``` **Importante:** * Substitua `3.2.0` e `1.0.0-M2` pelas versões estáveis mais recentes do Spring Boot e Spring AI, respectivamente. * Você precisará de uma chave de API do OpenAI. Defina-a como uma variável de ambiente ou no seu arquivo `application.properties`. * Este exemplo usa Netty para lidar com a comunicação de rede. Você pode usar outras bibliotecas também. **2. `application.properties` (ou `application.yml`)** ```properties spring.ai.openai.api-key=SUA_CHAVE_API_OPENAI ``` **3. Servidor MCP (Simplificado com Netty)** ```java package com.example.mcpserver; 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.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import lombok.RequiredArgsConstructor; import org.springframework.ai.client.AiClient; import org.springframework.ai.prompt.PromptTemplate; 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; @SpringBootApplication public class McpServerApplication { public static void main(String[] args) { SpringApplication.run(McpServerApplication.class, args); } @Bean public CommandLineRunner run(McpServer mcpServer) { return args -> { mcpServer.start(); }; } @Bean public McpServer mcpServer(AiClient aiClient, @Value("${server.port:25565}") int port) { return new McpServer(aiClient, port); } } @RequiredArgsConstructor class McpServer { private final AiClient aiClient; private final int port; public void start() 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) { ChannelPipeline p = ch.pipeline(); p.addLast(new StringDecoder(), new StringEncoder(), new McpServerHandler(aiClient)); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); System.out.println("Servidor MCP iniciado na porta " + port); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } @RequiredArgsConstructor class McpServerHandler extends ChannelInboundHandlerAdapter { private final AiClient aiClient; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { String command = (String) msg; System.out.println("Comando recebido: " + command); // Use Spring AI to process the command String aiResponse = processCommand(command); // Send the response back to the client ctx.writeAndFlush(aiResponse + "\n"); } private String processCommand(String command) { // Define a prompt template for command processing String promptString = "Você é um assistente de servidor Minecraft. O jogador disse: {command}. Determine o comando Minecraft apropriado e explique-o ao usuário. Se o comando não for válido, responda com uma mensagem de erro."; PromptTemplate promptTemplate = new PromptTemplate(promptString); // Create a prompt with the player's command org.springframework.ai.prompt.Prompt prompt = promptTemplate.create(org.springframework.ai.prompt.PromptTemplate.map("command", command)); // Call the AI model String aiResponse = aiClient.generate(prompt).getGeneration().getText(); return aiResponse; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` **Explicação:** 1. **Dependências:** O `pom.xml` inclui Spring AI, Netty e Lombok. 2. **`application.properties`:** Define a chave de API do OpenAI. 3. **`McpServerApplication`:** A classe principal da aplicação Spring Boot. Ela cria o bean `McpServer` e o inicia quando a aplicação é executada. 4. **`McpServer`:** Esta classe usa Netty para criar um servidor TCP simples. Ele escuta as conexões de entrada na porta especificada. 5. **`McpServerHandler`:** Esta classe lida com as mensagens de entrada (comandos) dos clientes. * Ele recebe o comando como uma string. * Ele usa o `AiClient` do Spring AI para processar o comando. * Ele envia a resposta gerada pela IA de volta ao cliente. 6. **`processCommand`:** * Define um modelo de prompt que instrui o modelo de IA a atuar como um assistente de servidor Minecraft. * Cria um objeto `Prompt` com o comando do jogador. * Chama o `AiClient` para gerar uma resposta com base no prompt. **Como Funciona:** 1. O servidor inicia e escuta as conexões. 2. Um jogador se conecta ao servidor. 3. O jogador envia um comando (por exemplo, "Eu quero construir uma casa"). 4. O `McpServerHandler` recebe o comando. 5. O método `processCommand` constrói um prompt para o modelo de IA, incluindo o comando do jogador. 6. O `AiClient` envia o prompt para a API do OpenAI. 7. A API do OpenAI gera uma resposta (por exemplo, "Para construir uma casa, você precisará de madeira, pedra e uma mesa de trabalho. O comando para obter madeira é `/give @p minecraft:oak_log 64`"). 8. O `McpServerHandler` envia a resposta gerada pela IA de volta ao jogador. **Para Executar:** 1. Certifique-se de ter o Java 17 ou posterior instalado. 2. Defina a propriedade `spring.ai.openai.api-key` em `application.properties` com sua chave de API do OpenAI. 3. Execute a aplicação Spring Boot. 4. Use um cliente TCP simples (como `netcat` ou um cliente personalizado) para se conectar ao servidor na porta especificada (padrão 25565). 5. Envie comandos para o servidor. **Considerações Importantes:** * **Segurança:** Este é um exemplo *muito* básico e não inclui nenhuma medida de segurança. Em um servidor MCP real, você precisaria implementar autenticação, autorização e validação de entrada adequadas para evitar ataques maliciosos. * **Protocolo MCP:** Este exemplo não implementa o protocolo Minecraft completo. Você precisaria lidar com o handshake do protocolo, codificação/decodificação de pacotes e outros detalhes específicos do protocolo. Bibliotecas como `mc-netty` podem ajudar com isso. * **Tratamento de Erros:** O tratamento de erros neste exemplo é mínimo. Você deve adicionar um tratamento de erros mais robusto para capturar exceções e fornecer mensagens de erro informativas ao jogador. * **Custo do Modelo de IA:** O uso da API do OpenAI pode gerar custos. Esteja atento ao seu uso e configure alertas de faturamento. * **Engenharia de Prompt:** A qualidade das respostas da IA depende muito do prompt que você fornece. Experimente diferentes prompts para obter o comportamento desejado. * **Limitação de Taxa:** A API do OpenAI tem limites de taxa. Implemente a limitação de taxa em seu servidor para evitar exceder esses limites. * **Gerenciamento de Contexto:** Para interações mais complexas, você precisará gerenciar o contexto da conversa com o jogador. Isso pode envolver o armazenamento do inventário, localização e outras informações relevantes do jogador. **Desenvolvimento Adicional:** * **Implemente o protocolo MCP completo:** Use uma biblioteca como `mc-netty` para lidar com os detalhes do protocolo. * **Adicione mais recursos alimentados por IA:** * Geração dinâmica de missões. * Controle do comportamento de NPCs. * Geração de mundo. * **Melhore o processamento de comandos:** * Adicione suporte para comandos mais complexos. * Implemente a validação de comandos. * Forneça feedback mais útil ao jogador. * **Integre com uma API de servidor Minecraft:** Se você quiser modificar o mundo do jogo diretamente, precisará se integrar a uma API de servidor Minecraft como Bukkit ou Spigot. This provides a starting point. Remember to adapt and expand upon this example to create a more complete and functional MCP server. Good luck!

mcp-jenkins

mcp-jenkins

A integração do Jenkins com o Protocolo de Contexto do Modelo (MCP) é uma implementação de código aberto que conecta o Jenkins com modelos de linguagem de IA seguindo a especificação MCP da Anthropic. Este projeto permite interações de IA seguras e contextuais com ferramentas do Jenkins, mantendo a privacidade e a segurança dos dados.

TWSE MCP Server

TWSE MCP Server

台灣證交所MCPServer

mcp_server

mcp_server

Okay, I understand. You want me to describe how to implement a weather MCP (Message Client Protocol) server that can be called by a client IDE like Cursor. Here's a breakdown of the implementation, covering key aspects and considerations: **1. Understanding the Requirements** * **MCP (Message Client Protocol):** MCP is a relatively simple protocol, often used for communication between applications. It's typically text-based and uses delimiters to separate messages. We'll need to define the specific MCP format for our weather server. * **Weather Data Source:** You'll need a reliable source of weather data. This could be: * **A free weather API:** Examples include OpenWeatherMap, WeatherAPI.com (check their free tiers and usage limits). * **A paid weather API:** Provides more features, higher limits, and potentially better accuracy. * **A local weather data file:** For testing or if you have your own data source. * **Client IDE (Cursor):** The server needs to be designed so that Cursor can easily send requests and receive responses. This means using a standard communication method (like TCP sockets) and a well-defined MCP format. * **Functionality:** At a minimum, the server should be able to: * Get the current weather for a given location (e.g., city, zip code, latitude/longitude). * Potentially provide a forecast for a given location. **2. Defining the MCP Format** This is crucial. Let's define a simple MCP format for our weather server. We'll use a newline character (`\n`) as the delimiter between messages. * **Request Format (Client to Server):** ``` GET_WEATHER <location>\n GET_FORECAST <location>\n ``` * `GET_WEATHER`: Requests the current weather for the specified location. * `GET_FORECAST`: Requests a weather forecast for the specified location. * `<location>`: The location to get weather data for (e.g., "London", "90210", "40.7128,-74.0060"). You'll need to decide how you want to handle different location formats. * **Response Format (Server to Client):** ``` WEATHER <location> <temperature> <condition> <humidity>\n FORECAST <location> <day1_condition> <day1_high> <day1_low> <day2_condition> ...\n ERROR <message>\n ``` * `WEATHER`: Indicates the current weather data. * `<location>`: The location the weather data is for. * `<temperature>`: The current temperature (e.g., in Celsius or Fahrenheit). * `<condition>`: A brief description of the weather (e.g., "Sunny", "Cloudy", "Rainy"). * `<humidity>`: The current humidity (e.g., as a percentage). * `FORECAST`: Indicates the weather forecast data. * `<location>`: The location the forecast is for. * `<day1_condition>`, `<day1_high>`, `<day1_low>`, etc.: Forecast data for each day. You'll need to define how many days of forecast you'll provide and the format of the data. * `ERROR`: Indicates an error occurred. * `<message>`: A description of the error. **3. Server Implementation (Python Example)** Here's a basic Python example using the `socket` module. This is a simplified version; you'll need to add error handling, more robust data parsing, and potentially threading for handling multiple clients concurrently. ```python import socket import json # For parsing JSON responses from weather APIs import requests # For making HTTP requests to weather APIs # Configuration HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) WEATHER_API_KEY = "YOUR_OPENWEATHERMAP_API_KEY" # Replace with your API key WEATHER_API_URL = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}&units=metric" # Example URL def get_weather_data(location): """Fetches weather data from a weather API.""" try: url = WEATHER_API_URL.format(location, WEATHER_API_KEY) response = requests.get(url) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) data = response.json() temperature = data['main']['temp'] condition = data['weather'][0]['description'] humidity = data['main']['humidity'] return temperature, condition, humidity except requests.exceptions.RequestException as e: print(f"Error fetching weather data: {e}") return None, None, None except (KeyError, IndexError) as e: print(f"Error parsing weather data: {e}") return None, None, None def handle_client(conn, addr): """Handles communication with a single client.""" print(f"Connected by {addr}") while True: data = conn.recv(1024) # Receive data from the client if not data: break # Client disconnected message = data.decode('utf-8').strip() print(f"Received: {message}") if message.startswith("GET_WEATHER"): try: location = message.split(" ")[1] temperature, condition, humidity = get_weather_data(location) if temperature is not None: response = f"WEATHER {location} {temperature} {condition} {humidity}\n" else: response = f"ERROR Could not retrieve weather for {location}\n" except IndexError: response = "ERROR Invalid request format. Use GET_WEATHER <location>\n" except Exception as e: response = f"ERROR An unexpected error occurred: {e}\n" elif message.startswith("GET_FORECAST"): # Implement forecast logic here (similar to GET_WEATHER) location = message.split(" ")[1] response = f"ERROR Forecast functionality not yet implemented for {location}\n" else: response = "ERROR Invalid command\n" conn.sendall(response.encode('utf-8')) # Send the response back to the client conn.close() print(f"Connection closed with {addr}") def main(): """Main server function.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"Listening on {HOST}:{PORT}") while True: conn, addr = s.accept() # Accept incoming connections handle_client(conn, addr) # Handle the client in a separate function (or thread) if __name__ == "__main__": main() ``` Key improvements and explanations: * **Error Handling:** Includes `try...except` blocks to catch potential errors during API requests, JSON parsing, and other operations. This prevents the server from crashing and provides more informative error messages to the client. * **Weather API Integration:** Uses the `requests` library to make HTTP requests to a weather API (OpenWeatherMap in this example). You'll need to replace `"YOUR_OPENWEATHERMAP_API_KEY"` with your actual API key. The `get_weather_data` function handles the API call and parses the JSON response. * **JSON Parsing:** Uses the `json` library to parse the JSON response from the weather API. * **Clearer Response Messages:** The server now sends more informative error messages to the client when something goes wrong. * **`handle_client` Function:** The code that handles communication with a single client is now in a separate function, `handle_client`. This makes the code more organized and easier to read. * **UTF-8 Encoding:** Explicitly encodes and decodes messages using UTF-8 to handle a wider range of characters. * **`response.raise_for_status()`:** This line in `get_weather_data` is important. It raises an `HTTPError` if the API returns a bad status code (4xx or 5xx), which indicates a problem with the request or the API itself. * **`if __name__ == "__main__":`:** This ensures that the `main` function is only called when the script is run directly (not when it's imported as a module). **4. Client Implementation (Cursor IDE)** You'll need to write code within Cursor to connect to the server, send requests, and display the responses. Here's a conceptual outline (the exact code will depend on Cursor's API and capabilities): ```python import socket HOST = '127.0.0.1' PORT = 65432 def get_weather(location): """Gets weather data from the server.""" try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) request = f"GET_WEATHER {location}\n" s.sendall(request.encode('utf-8')) data = s.recv(1024) response = data.decode('utf-8').strip() return response except Exception as e: return f"Error: {e}" # Example usage (within Cursor): location = "London" # Or get the location from user input in Cursor weather_data = get_weather(location) print(weather_data) # Display the weather data in Cursor's output window ``` **5. Key Considerations and Enhancements** * **Threading/Asynchronous Handling:** For a production server, use threading or asynchronous I/O (e.g., `asyncio` in Python) to handle multiple client connections concurrently. The basic example above handles only one client at a time. * **Error Handling:** Implement robust error handling on both the client and server sides. Handle network errors, API errors, invalid input, etc. * **Input Validation:** Validate the location input to prevent errors and potential security issues. * **Security:** If you're exposing the server to the internet, consider security measures like authentication and authorization. For local development, this is less critical. * **Configuration:** Use a configuration file (e.g., a `.ini` or `.json` file) to store settings like the host, port, API key, and other parameters. This makes the server more flexible and easier to configure. * **Logging:** Implement logging to track server activity, errors, and other important events. This is helpful for debugging and monitoring. * **Data Caching:** Cache weather data to reduce the number of API calls and improve performance. Use a caching library like `cachetools` or `redis`. * **More Sophisticated MCP:** Consider a more structured MCP format using JSON or another data serialization format for more complex data structures. However, keep it relatively simple for ease of implementation. * **Unit Testing:** Write unit tests to ensure that the server is working correctly. **Example Interaction** 1. **Client (Cursor) sends:** `GET_WEATHER London\n` 2. **Server receives:** `GET_WEATHER London` 3. **Server fetches weather data for London from the API.** 4. **Server sends:** `WEATHER London 15 Cloudy 80\n` (if the temperature is 15 degrees, the condition is cloudy, and the humidity is 80%) 5. **Client (Cursor) receives:** `WEATHER London 15 Cloudy 80` 6. **Client (Cursor) displays:** "Weather in London: 15 degrees, Cloudy, Humidity: 80%" This detailed explanation and the Python example should give you a solid foundation for building your weather MCP server. Remember to adapt the code and the MCP format to your specific needs and the capabilities of Cursor. Good luck!

MMA MCP Server

MMA MCP Server

Enables users to search and query information about military service alternative companies in South Korea through the Military Manpower Administration (MMA) API. Supports filtering by service type, industry, company size, location, and recruitment status.

Agent MCP BrightData

Agent MCP BrightData

An intelligent agent using the Model Context Protocol to iteratively explore and analyze websites in a structured way, with built-in duplicate protection and conversational interface.

MCP Server on Cloudflare Workers & Azure Functions

MCP Server on Cloudflare Workers & Azure Functions

A deployable MCP server for Cloudflare Workers or Azure Functions that provides example tools (time, echo, math), prompt templates for code assistance, and configuration resources. Enables AI assistants to interact with edge-deployed services through the Model Context Protocol.

Bilibili MCP Server

Bilibili MCP Server

Enables interaction with Bilibili (B站) platform through API and web scraping. Supports video search, article search, video info retrieval, comment fetching, danmaku extraction, and article content access.

bio-mcp

bio-mcp

Servidor MCP para bioinformáticos e biólogos computacionais

MCP Montano Server

MCP Montano Server

BinjaLattice

BinjaLattice

Interface de plugin para comunicações remotas com o banco de dados do Binary Ninja e o servidor MCP para interagir com LLMs.

mcpserver-semantickernel-client-demo

mcpserver-semantickernel-client-demo

Absolutely! Here's a breakdown of how you could create a very basic C# MCP (Message Control Protocol) server using Aspire, and then consume it with Semantic Kernel. I'll focus on simplicity and clarity. **Conceptual Overview** 1. **MCP Server (Aspire-Hosted):** * Listens for incoming MCP messages on a specific port. * Parses the message (in this example, a very basic format). * Performs a simple action based on the message content. * Sends a response back to the client. 2. **Semantic Kernel Client:** * Uses Semantic Kernel to orchestrate a task. * As part of that task, it sends an MCP message to the server. * Receives the response from the server. * Uses the response within the Semantic Kernel workflow. **Implementation** **1. Create a new Aspire Application** ```bash dotnet new aspire -o MyAspireApp cd MyAspireApp ``` **2. Create the MCP Server Project** ```bash dotnet new worker -o MyAspireApp.McpServer dotnet add MyAspireApp.McpServer package Microsoft.Extensions.Hosting dotnet add MyAspireApp.McpServer package Microsoft.Extensions.ServiceDiscovery dotnet add MyAspireApp.McpServer package Microsoft.Extensions.Http ``` **3. Create the Semantic Kernel Client Project** ```bash dotnet new console -o MyAspireApp.SemanticKernelClient dotnet add MyAspireApp.SemanticKernelClient package Microsoft.SemanticKernel dotnet add MyAspireApp.SemanticKernelClient package Microsoft.Extensions.Hosting dotnet add MyAspireApp.SemanticKernelClient package Microsoft.Extensions.ServiceDiscovery dotnet add MyAspireApp.SemanticKernelClient package Microsoft.Extensions.Http ``` **4. Add the projects to the solution** ```bash dotnet sln add ./MyAspireApp.McpServer/MyAspireApp.McpServer.csproj dotnet sln add ./MyAspireApp.SemanticKernelClient/MyAspireApp.SemanticKernelClient.csproj ``` **5. Reference the projects in the AppHost** ```bash dotnet add ./MyAspireApp.AppHost/MyAspireApp.AppHost.csproj reference ./MyAspireApp.McpServer/MyAspireApp.McpServer.csproj dotnet add ./MyAspireApp.AppHost/MyAspireApp.AppHost.csproj reference ./MyAspireApp.SemanticKernelClient/MyAspireApp.SemanticKernelClient.csproj ``` **6. MCP Server Code (MyAspireApp.McpServer/Worker.cs)** ```csharp using System.Net; using System.Net.Sockets; using System.Text; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MyAspireApp.McpServer; public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly int _port = 12345; // Choose a port private TcpListener? _listener; public Worker(ILogger<Worker> logger) { _logger = logger; } public override async Task StartAsync(CancellationToken cancellationToken) { _listener = new TcpListener(IPAddress.Any, _port); _listener.Start(); _logger.LogInformation("MCP Server started on port {Port}", _port); await base.StartAsync(cancellationToken); } public override async Task StopAsync(CancellationToken cancellationToken) { _listener?.Stop(); _logger.LogInformation("MCP Server stopped."); await base.StopAsync(cancellationToken); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { if (_listener is null) { return; } try { while (!stoppingToken.IsCancellationRequested) { TcpClient client = await _listener.AcceptTcpClientAsync(stoppingToken); _ = HandleClientAsync(client, stoppingToken); // Fire and forget } } catch (OperationCanceledException) { // Expected when the service is stopping. } catch (Exception ex) { _logger.LogError(ex, "Error in MCP server loop."); } } private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken) { try { _logger.LogInformation("Client connected: {RemoteEndPoint}", client.Client.RemoteEndPoint); NetworkStream stream = client.GetStream(); byte[] buffer = new byte[1024]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken); string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); _logger.LogInformation("Received message: {Message}", message); // **Simple Message Processing** string response = ProcessMessage(message); byte[] responseBytes = Encoding.UTF8.GetBytes(response); await stream.WriteAsync(responseBytes, 0, responseBytes.Length, cancellationToken); _logger.LogInformation("Sent response: {Response}", response); } catch (Exception ex) { _logger.LogError(ex, "Error handling client."); } finally { client.Close(); _logger.LogInformation("Client disconnected: {RemoteEndPoint}", client.Client.RemoteEndPoint); } } private string ProcessMessage(string message) { // **Very Basic Example:** If the message starts with "SUM", return the sum of two numbers. if (message.StartsWith("SUM")) { try { string[] parts = message.Split(' '); if (parts.Length == 3 && int.TryParse(parts[1], out int a) && int.TryParse(parts[2], out int b)) { return $"RESULT {a + b}"; } else { return "ERROR: Invalid SUM format. Use SUM <number1> <number2>"; } } catch (Exception) { return "ERROR: Could not process SUM command."; } } else { return $"ECHO: {message}"; // Just echo the message back. } } } ``` **7. Semantic Kernel Client Code (MyAspireApp.SemanticKernelClient/Program.cs)** ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.SemanticKernel; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using System.Net.Sockets; using System.Text; public class Program { public static async Task Main(string[] args) { using IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.AddHostedService<Worker>(); services.AddHttpClient("McpServer", client => { var mcpServerUri = context.Configuration["McpServerUri"] ?? "http://localhost:12345"; client.BaseAddress = new Uri(mcpServerUri); }); }) .Build(); await host.RunAsync(); } public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly IHttpClientFactory _httpClientFactory; private readonly IConfiguration _configuration; public Worker(ILogger<Worker> logger, IHttpClientFactory httpClientFactory, IConfiguration configuration) { _logger = logger; _httpClientFactory = httpClientFactory; _configuration = configuration; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { // **Semantic Kernel Setup** Kernel kernel = Kernel.CreateBuilder() .Build(); // **Define a simple function (skill)** var mcpSkill = kernel.CreateFunctionFromMethod( (string input) => SendMcpMessageAsync(input, stoppingToken).GetAwaiter().GetResult(), // Synchronously get the result "SendMcpMessage", "Sends a message to the MCP server and returns the response." ); // Import the skill into the kernel kernel.ImportSkill(new { SendMcpMessage = mcpSkill }, "McpSkill"); // **Run a Semantic Kernel "plan"** var result = await kernel.RunAsync( "SUM 10 20", // Input to the plan (MCP message) kernel.Skills.GetFunction("McpSkill", "SendMcpMessage") ); _logger.LogInformation("Semantic Kernel Result: {Result}", result.GetValue<string>()); } catch (Exception ex) { _logger.LogError(ex, "Error in Semantic Kernel client."); } // Keep the service running while (!stoppingToken.IsCancellationRequested) { await Task.Delay(1000, stoppingToken); } } private async Task<string> SendMcpMessageAsync(string message, CancellationToken cancellationToken) { string hostName = _configuration["McpServerHostName"] ?? "localhost"; int port = int.Parse(_configuration["McpServerPort"] ?? "12345"); try { using TcpClient client = new TcpClient(); await client.ConnectAsync(hostName, port, cancellationToken); NetworkStream stream = client.GetStream(); byte[] messageBytes = Encoding.UTF8.GetBytes(message); await stream.WriteAsync(messageBytes, 0, messageBytes.Length, cancellationToken); byte[] buffer = new byte[1024]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken); string response = Encoding.UTF8.GetString(buffer, 0, bytesRead); _logger.LogInformation("Received from MCP server: {Response}", response); return response; } catch (Exception ex) { _logger.LogError(ex, "Error sending MCP message: {Error}", ex.Message); return $"ERROR: Could not connect to MCP server: {ex.Message}"; } } } } ``` **8. Aspire AppHost Code (MyAspireApp.AppHost/Program.cs)** ```csharp var builder = DistributedApplication.CreateBuilder(args); var mcpServer = builder.AddProject<Projects.MyAspireApp_McpServer>("mcpserver"); builder.AddProject<Projects.MyAspireApp_SemanticKernelClient>("semantickernelclient") .WithReference(mcpServer, "McpServerHostName", "McpServerPort"); builder.Build().Run(); ``` **9. Aspire AppHost Code (MyAspireApp.AppHost/appsettings.json)** ```json { "McpServerHostName": "mcpserver", "McpServerPort": "12345" } ``` **Explanation and Key Points** * **MCP Server:** * The `TcpListener` listens for incoming connections. * `HandleClientAsync` processes each client connection in a separate task. * `ProcessMessage` is where you'd implement your MCP logic. This example has a very basic `SUM` command and an echo. * **Semantic Kernel Client:** * The `SendMcpMessageAsync` function establishes a TCP connection to the server, sends the message, and receives the response. * The Semantic Kernel is set up with a simple skill that calls `SendMcpMessageAsync`. * A "plan" is executed to send the `SUM` message and log the result. * **Aspire Integration:** * The `AppHost` project orchestrates the deployment of both the MCP server and the Semantic Kernel client. * It uses service discovery to allow the Semantic Kernel client to find the MCP server's address. * **Error Handling:** Includes basic `try-catch` blocks for error handling. In a real application, you'd want more robust error handling and logging. * **Simplicity:** This is a deliberately simplified example. A real MCP server would likely have a more complex message format, error handling, and security considerations. **How to Run** 1. Make sure you have the .NET 8 SDK and Aspire workload installed. 2. Navigate to the `MyAspireApp` directory in your terminal. 3. Run `dotnet run --project MyAspireApp.AppHost`. **Important Considerations** * **MCP Protocol:** This example uses a very basic text-based protocol. For real-world applications, you'd likely want a more structured protocol (e.g., binary, JSON, Protocol Buffers). * **Security:** This example has no security. In a production environment, you'd need to implement authentication, authorization, and encryption. * **Scalability:** For high-volume scenarios, you might need to consider asynchronous I/O, connection pooling, and other techniques to improve scalability. * **Service Discovery:** Aspire provides a service discovery mechanism that allows the client to locate the server without hardcoding the address. **To Adapt and Extend** * **Message Format:** Change the `ProcessMessage` method to handle different MCP commands and data formats. * **Semantic Kernel Integration:** Create more complex Semantic Kernel skills that use the MCP server to perform various tasks. * **Error Handling:** Add more detailed error handling and logging. * **Configuration:** Use configuration files to manage settings like the port number and server address. Let me know if you'd like help with any of these specific areas!

A simple MCP Server

A simple MCP Server

mcp-server-newbie

mcp-server-newbie

MCP Server Tutorial

MCP Server Tutorial

Java Map Component Platform (Java MCP)

Java Map Component Platform (Java MCP)

Servidor Java MCP

Remote MCP Server on Cloudflare

Remote MCP Server on Cloudflare

A deployable Model Context Protocol server on Cloudflare Workers that enables AI models to access custom tools without authentication requirements.

MCP Weather Server

MCP Weather Server

Enables users to retrieve current weather alerts for US states and detailed weather forecasts by geographic coordinates using the US National Weather Service API. Built with Node.js and TypeScript following Model Context Protocol standards for seamless LLM integration.

MCP2ANP Bridge Server

MCP2ANP Bridge Server

Enables MCP clients like Claude Desktop to interact with ANP (Agent Network Protocol) agents through three core tools: authentication setup, document fetching, and OpenRPC method invocation. Converts ANP's crawler-style interaction paradigm into MCP-compatible tools for seamless agent communication.

KatCoder MySQL MCP Server

KatCoder MySQL MCP Server

A secure MySQL Model Context Protocol server that enables AI agents to interact with MySQL databases through standardized operations. Features comprehensive security with SQL injection prevention, connection pooling, and configurable tool access for database operations.

KIS REST API MCP Server

KIS REST API MCP Server

Um servidor de Protocolo de Contexto de Modelo para interagir com a API REST da Korea Investment & Securities (KIS), permitindo negociação de ações nacionais e estrangeiras, verificação de preços e gerenciamento de contas.

System Information MCP Server

System Information MCP Server

Provides comprehensive system diagnostics and hardware analysis through 10 specialized tools for troubleshooting and environment monitoring. Offers targeted information gathering for CPU, memory, network, storage, processes, and security analysis across Windows, macOS, and Linux platforms.

SQL-Server-MCP

SQL-Server-MCP

Atla MCP Server

Atla MCP Server

Versão inicial de um servidor mcp para agentes interagirem com os modelos da atla.

MCP Finnhub Server

MCP Finnhub Server

Provides comprehensive financial market data and news through the Finnhub API. Enables real-time stock quotes, company profiles, financial metrics, analyst recommendations, and market news access.

FluxCD MCP Server

FluxCD MCP Server

FluxCD MCP Server

Awesome-MCP-ZH

Awesome-MCP-ZH

Seleção de recursos MCP, Guia MCP, Claude MCP, Servidores MCP, Clientes MCP

Google API Discovery Service MCP Server

Google API Discovery Service MCP Server

An MCP server that provides access to Google's API Discovery Service, allowing agents to discover and interact with Google APIs through natural language commands.

mcp-clockify

mcp-clockify

Servidor Clockify MCP

Remote MCP Server on Cloudflare

Remote MCP Server on Cloudflare