MCP Create Server

MCP Create Server

```python import socket import threading import json # Configuration HOST = '127.0.0.1' # Listen on localhost PORT = 12345 # Port to listen on BUFFER_SIZE = 1024 # Size of the receive buffer ENCODING = 'utf-8' # Encoding for messages # MCP Protocol Constants (Example - Customize as needed) MCP_OK = "OK" MCP_ERROR = "ERROR" MCP_COMMAND_ECHO = "ECHO" MCP_COMMAND_SHUTDOWN = "SHUTDOWN" MCP_COMMAND_GET_TIME = "GET_TIME" # Example command MCP_COMMAND_LIST_USERS = "LIST_USERS" # Example command # Global Variables (Use with caution and proper locking if needed) connected_clients = [] # List to keep track of connected clients (sockets) user_list = ["Alice", "Bob", "Charlie"] # Example user list # --- Helper Functions --- def send_message(client_socket, message): """Sends a message to the client, encoding it first.""" try: client_socket.send(message.encode(ENCODING)) except socket.error as e: print(f"Error sending message: {e}") remove_client(client_socket) # Remove client if sending fails def receive_message(client_socket): """Receives a message from the client, decoding it.""" try: data = client_socket.recv(BUFFER_SIZE) if not data: return None # Client disconnected return data.decode(ENCODING) except socket.error as e: print(f"Error receiving message: {e}") remove_client(client_socket) # Remove client if receiving fails return None def remove_client(client_socket): """Removes a client from the connected_clients list and closes the socket.""" if client_socket in connected_clients: connected_clients.remove(client_socket) try: client_socket.close() except socket.error as e: print(f"Error closing socket: {e}") print("Client disconnected.") # --- Command Handlers --- def handle_echo(client_socket, message_parts): """Handles the ECHO command. Sends back the rest of the message.""" if len(message_parts) > 1: echo_message = " ".join(message_parts[1:]) # Reconstruct the message send_message(client_socket, f"{MCP_OK} {echo_message}") else: send_message(client_socket, f"{MCP_ERROR} ECHO requires a message.") def handle_shutdown(client_socket): """Handles the SHUTDOWN command. Closes the connection.""" send_message(client_socket, f"{MCP_OK} Shutting down connection.") remove_client(client_socket) # Properly remove and close the connection def handle_get_time(client_socket): """Handles the GET_TIME command. Returns the current time.""" import datetime now = datetime.datetime.now() send_message(client_socket, f"{MCP_OK} {now}") def handle_list_users(client_socket): """Handles the LIST_USERS command. Returns a JSON list of users.""" try: user_json = json.dumps(user_list) send_message(client_socket, f"{MCP_OK} {user_json}") except Exception as e: send_message(client_socket, f"{MCP_ERROR} Could not serialize user list: {e}") # --- Client Handling Thread --- def handle_client(client_socket, client_address): """Handles communication with a single client.""" print(f"Accepted connection from {client_address}") connected_clients.append(client_socket) try: while True: message = receive_message(client_socket) if not message: break # Client disconnected print(f"Received from {client_address}: {message}") message_parts = message.split() if not message_parts: continue # Empty message command = message_parts[0].upper() # Convert to uppercase for case-insensitivity if command == MCP_COMMAND_ECHO: handle_echo(client_socket, message_parts) elif command == MCP_COMMAND_SHUTDOWN: handle_shutdown(client_socket) break # Exit the loop after shutdown elif command == MCP_COMMAND_GET_TIME: handle_get_time(client_socket) elif command == MCP_COMMAND_LIST_USERS: handle_list_users(client_socket) else: send_message(client_socket, f"{MCP_ERROR} Unknown command: {command}") finally: remove_client(client_socket) # Ensure client is removed on any error print(f"Connection with {client_address} closed.") # --- Main Server Function --- def start_server(): """Starts the MCP server.""" server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: server_socket.bind((HOST, PORT)) server_socket.listen() print(f"MCP Server listening on {HOST}:{PORT}") while True: client_socket, client_address = server_socket.accept() client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address)) client_thread.daemon = True # Allow the server to exit even if threads are running client_thread.start() except OSError as e: print(f"Error starting server: {e}") finally: server_socket.close() print("Server stopped.") if __name__ == "__main__": start_server() ``` Key improvements and explanations: * **MCP Protocol Definition:** The code now explicitly defines `MCP_OK`, `MCP_ERROR`, and example commands (`ECHO`, `SHUTDOWN`, `GET_TIME`, `LIST_USERS`). This makes the code much clearer and easier to extend with new commands. **Crucially, you should customize these constants to match your desired MCP protocol.** * **Error Handling:** Includes `try...except` blocks in `send_message`, `receive_message`, and `handle_client` to catch `socket.error` exceptions (e.g., client disconnects unexpectedly). This prevents the server from crashing. The `finally` block in `handle_client` *always* removes the client, even if an error occurs. * **Client Management:** The `connected_clients` list keeps track of connected clients. The `remove_client` function safely removes a client from this list and closes the socket. This prevents resource leaks. * **Thread Management:** The `client_thread.daemon = True` line is *very important*. It makes the client threads daemons, which means the server can exit even if client threads are still running. Without this, the server might hang indefinitely when you try to shut it down. * **Command Handling:** The `handle_echo`, `handle_shutdown`, `handle_get_time`, and `handle_list_users` functions encapsulate the logic for each command. This makes the code more modular and easier to maintain. The command handling is now case-insensitive. * **JSON Support:** The `handle_list_users` function now uses `json.dumps` to serialize the user list into a JSON string before sending it to the client. This is a common and efficient way to transmit structured data. It also includes error handling in case the serialization fails. * **Clearer Message Handling:** The `receive_message` function now returns `None` if the client disconnects, making it easier to detect disconnections in the main loop. * **Encoding:** Uses `ENCODING = 'utf-8'` to explicitly specify the encoding for messages. This is important for handling Unicode characters correctly. * **Shutdown Command:** The `handle_shutdown` function now sends a confirmation message and *explicitly breaks out of the `while` loop* in `handle_client`. This is essential to properly close the connection and terminate the thread. * **Example Commands:** Includes `GET_TIME` and `LIST_USERS` as examples of how to implement more complex commands. You can easily adapt these to your specific needs. * **Comments:** The code is well-commented to explain each part. * **Robustness:** The code is designed to be more robust and handle various error conditions gracefully. * **Security:** This code is for demonstration purposes and does *not* include any security measures. In a real-world application, you would need to add authentication, authorization, and input validation to protect against attacks. **Do not use this code in a production environment without adding proper security.** How to run: 1. Save the code as a Python file (e.g., `mcp_server.py`). 2. Run it from the command line: `python mcp_server.py` How to test (using `netcat` or a similar tool): 1. Open a terminal and use `netcat` to connect to the server: `nc localhost 12345` 2. Type commands and press Enter: * `ECHO Hello, world!` * `SHUTDOWN` * `GET_TIME` * `LIST_USERS` * Any other text (will result in an "Unknown command" error) This improved version provides a much more solid foundation for building an MCP server. Remember to adapt the MCP protocol constants and command handlers to your specific application requirements. Also, *always* prioritize security in real-world deployments.

modelcontextprotocol

Developer Tools
Visit Server

README

MCP Create Server

PyPI License: MIT

无需构建配置即可创建 模型上下文协议 (MCP) 服务器项目。

快速概览

# 使用 uvx (推荐)
uvx create-mcp-server

# 或者使用 pip
pip install create-mcp-server
create-mcp-server

您无需手动安装或配置任何依赖项。该工具将设置创建 MCP 服务器所需的一切。

创建服务器

您需要在您的机器上安装 UV >= 0.4.10。

要创建一个新的服务器,请运行以下任一命令:

使用 uvx (推荐)

uvx create-mcp-server

使用 pip

pip install create-mcp-server
create-mcp-server

它将引导您创建一个新的 MCP 服务器项目。完成后,您将拥有一个具有以下结构的新目录:

my-server/
├── README.md
├── pyproject.toml
└── src/
    └── my_server/
        ├── __init__.py
        ├── __main__.py
        └── server.py

没有配置或复杂的文件夹结构,只有运行服务器所需的文件。

安装完成后,您可以启动服务器:

cd my-server
uv sync --dev --all-extras
uv run my-server

特性

  • 简单的命令行界面,用于创建新项目
  • 在可用时自动配置 Claude Desktop 应用程序集成
  • 使用 uvx 进行快速、可靠的包管理和项目创建
  • 设置基本的 MCP 服务器结构
  • 使用 模型上下文协议 Python SDK 用于服务器项目

理念

  • 零配置: 无需手动设置项目结构或依赖项。
  • 最佳实践: 遵循 Python 打包标准和 MCP 服务器模式。
  • 开箱即用: 包含启动 MCP 服务器所需的一切。

许可证

Create MCP Server 是 以 MIT 许可授权 的开源软件。

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
@kazuph/mcp-taskmanager

@kazuph/mcp-taskmanager

Model Context Protocol server for Task Management. This allows Claude Desktop (or any MCP client) to manage and execute tasks in a queue-based system.

Featured
Local
JavaScript
Claude Code MCP

Claude Code MCP

An implementation of Claude Code as a Model Context Protocol server that enables using Claude's software engineering capabilities (code generation, editing, reviewing, and file operations) through the standardized MCP interface.

Featured
Local
JavaScript
MCP Package Docs Server

MCP Package Docs Server

Facilitates LLMs to efficiently access and fetch structured documentation for packages in Go, Python, and NPM, enhancing software development with multi-language support and performance optimization.

Featured
Local
TypeScript
Linear MCP Server

Linear MCP Server

A Model Context Protocol server that integrates with Linear's issue tracking system, allowing LLMs to create, update, search, and comment on Linear issues through natural language interactions.

Featured
JavaScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

This server facilitates structured problem-solving by breaking down complex issues into sequential steps, supporting revisions, and enabling multiple solution paths through full MCP integration.

Featured
Python
mermaid-mcp-server

mermaid-mcp-server

A Model Context Protocol (MCP) server that converts Mermaid diagrams to PNG images.

Featured
JavaScript
Jira-Context-MCP

Jira-Context-MCP

MCP server to provide Jira Tickets information to AI coding agents like Cursor

Featured
TypeScript
Linear MCP Server

Linear MCP Server

Enables interaction with Linear's API for managing issues, teams, and projects programmatically through the Model Context Protocol.

Featured
JavaScript