MCP 만들면서 원리 파헤쳐보기

MCP 만들면서 원리 파헤쳐보기

Okay, here's a breakdown of the server and client implementation for a system conceptually similar to the MCP (Master Control Program) from the movie Tron, along with considerations for a modern implementation. Keep in mind that a real-world MCP would be incredibly complex, so this is a simplified, illustrative example. **Conceptual Overview** The MCP, in essence, is a central control system. In a modern context, we can think of it as a distributed system with the following key components: * **Server (MCP Core):** The central authority. It manages resources, schedules tasks, enforces security policies, and monitors the overall system health. * **Clients (Programs/Processes):** These are the individual applications or processes that interact with the MCP to request resources, execute tasks, and report their status. * **Communication Protocol:** A well-defined protocol for clients and the server to exchange information. **Implementation Considerations** * **Language Choice:** Python is a good choice for prototyping and scripting due to its readability and extensive libraries. For performance-critical components, consider languages like Go, Rust, or C++. * **Communication:** gRPC, ZeroMQ, or even a simple TCP socket-based protocol can be used for communication between the server and clients. gRPC is a modern, high-performance RPC framework that's well-suited for this kind of system. * **Security:** Authentication and authorization are crucial. Use strong authentication mechanisms (e.g., TLS certificates, API keys) and implement role-based access control (RBAC) to restrict access to sensitive resources. * **Resource Management:** The MCP needs to track available resources (CPU, memory, disk space, network bandwidth) and allocate them to clients based on their needs and priorities. * **Task Scheduling:** A scheduler determines the order in which tasks are executed. Prioritization, deadlines, and dependencies should be considered. * **Monitoring and Logging:** Comprehensive monitoring and logging are essential for detecting errors, performance bottlenecks, and security breaches. * **Fault Tolerance:** The MCP should be designed to be fault-tolerant. Consider using techniques like redundancy, replication, and failover to ensure that the system remains operational even if some components fail. **Simplified Python Example (Illustrative)** This is a very basic example to demonstrate the core concepts. It's not production-ready. ```python # server.py (MCP Core) import socket import threading import json import time HOST = '127.0.0.1' PORT = 65432 # Resource Management (very basic) available_cpu = 100 resource_lock = threading.Lock() def handle_client(conn, addr): print(f"Connected by {addr}") while True: try: data = conn.recv(1024).decode() if not data: break try: request = json.loads(data) print(f"Received request: {request}") if request['action'] == 'request_cpu': cpu_units = request['cpu_units'] with resource_lock: global available_cpu if available_cpu >= cpu_units: available_cpu -= cpu_units response = {'status': 'granted', 'cpu_units': cpu_units} print(f"Granted {cpu_units} CPU units. Remaining: {available_cpu}") else: response = {'status': 'denied', 'reason': 'Insufficient CPU'} conn.sendall(json.dumps(response).encode()) elif request['action'] == 'report_status': status = request['status'] print(f"Client reported status: {status}") conn.sendall(json.dumps({'status': 'received'}).encode()) elif request['action'] == 'release_cpu': cpu_units = request['cpu_units'] with resource_lock: available_cpu += cpu_units response = {'status': 'released', 'cpu_units': cpu_units} print(f"Released {cpu_units} CPU units. Remaining: {available_cpu}") conn.sendall(json.dumps(response).encode()) else: response = {'status': 'error', 'message': 'Invalid action'} conn.sendall(json.dumps(response).encode()) except json.JSONDecodeError: response = {'status': 'error', 'message': 'Invalid JSON'} conn.sendall(json.dumps(response).encode()) except ConnectionResetError: print(f"Connection reset by {addr}") break except Exception as e: print(f"Error handling client: {e}") break print(f"Closing connection with {addr}") conn.close() def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"MCP Server listening on {HOST}:{PORT}") while True: conn, addr = s.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() if __name__ == "__main__": main() ``` ```python # client.py (Program/Process) import socket import json import time HOST = '127.0.0.1' PORT = 65432 def request_cpu(conn, cpu_units): request = {'action': 'request_cpu', 'cpu_units': cpu_units} conn.sendall(json.dumps(request).encode()) response = json.loads(conn.recv(1024).decode()) return response def report_status(conn, status): request = {'action': 'report_status', 'status': status} conn.sendall(json.dumps(request).encode()) response = json.loads(conn.recv(1024).decode()) return response def release_cpu(conn, cpu_units): request = {'action': 'release_cpu', 'cpu_units': cpu_units} conn.sendall(json.dumps(request).encode()) response = json.loads(conn.recv(1024).decode()) return response def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) # Request CPU cpu_request_response = request_cpu(s, 20) print(f"CPU Request Response: {cpu_request_response}") if cpu_request_response['status'] == 'granted': # Report status status_response = report_status(s, 'Running task...') print(f"Status Response: {status_response}") time.sleep(5) # Simulate work # Release CPU cpu_release_response = release_cpu(s, 20) print(f"CPU Release Response: {cpu_release_response}") else: print("CPU request denied.") report_status(s, "Exiting") if __name__ == "__main__": main() ``` **How to Run:** 1. Save the code as `server.py` and `client.py`. 2. Run the server: `python server.py` 3. Run the client: `python client.py` (You can run multiple clients in separate terminals). **Explanation:** * **Server (server.py):** * Listens for incoming connections on a specified port. * Handles each client connection in a separate thread. * Receives JSON-encoded requests from clients. * Implements basic CPU resource management (request, release). * Responds to clients with JSON-encoded responses. * **Client (client.py):** * Connects to the server. * Sends JSON-encoded requests to the server (request CPU, report status, release CPU). * Receives JSON-encoded responses from the server. * Simulates a simple task that requests CPU, reports its status, and releases the CPU. **Improvements and Next Steps:** * **Error Handling:** Add more robust error handling to both the server and client. * **Authentication/Authorization:** Implement a proper authentication and authorization system. * **Resource Management:** Expand the resource management to include memory, disk space, and other resources. Implement a more sophisticated resource allocation algorithm. * **Task Scheduling:** Implement a task scheduler that can prioritize tasks, handle dependencies, and enforce deadlines. * **Monitoring:** Integrate monitoring tools to track system health and performance. * **Logging:** Use a logging library (e.g., `logging` in Python) to record events and errors. * **Concurrency:** Use asynchronous programming (e.g., `asyncio` in Python) for better concurrency and scalability. * **gRPC:** Migrate to gRPC for a more efficient and robust communication protocol. Define a gRPC service definition (a `.proto` file) that specifies the available RPC calls. * **Database:** Use a database to store information about users, resources, tasks, and system state. * **Distributed System:** Design the MCP as a distributed system with multiple server nodes for fault tolerance and scalability. Consider using a distributed consensus algorithm (e.g., Raft or Paxos) to ensure consistency across the nodes. **Translation to Chinese** Here's a translation of the conceptual overview and the improvements/next steps into Chinese: **概念概述 (Gài niàn ǒugài - Conceptual Overview)** MCP 本质上是一个中央控制系统。 在现代背景下,我们可以将其视为一个分布式系统,具有以下关键组件: * **服务器 (MCP 核心):** 中央权威。 它管理资源、调度任务、执行安全策略并监控整个系统健康状况。 * **客户端 (程序/进程):** 这些是与 MCP 交互以请求资源、执行任务和报告其状态的各个应用程序或进程。 * **通信协议:** 客户端和服务器交换信息的明确定义的协议。 **改进和下一步 (Gǎi jìn hé xià yī bù - Improvements and Next Steps)** * **错误处理 (Cuòwù chǔlǐ):** 向服务器和客户端添加更强大的错误处理。 * **身份验证/授权 (Shēnfèn yànzhèng/shòuquán):** 实施适当的身份验证和授权系统。 * **资源管理 (Zīyuán guǎnlǐ):** 扩展资源管理以包括内存、磁盘空间和其他资源。 实施更复杂的资源分配算法。 * **任务调度 (Rènwù diàodù):** 实施一个任务调度程序,可以优先处理任务、处理依赖关系并强制执行截止日期。 * **监控 (Jiānkòng):** 集成监控工具以跟踪系统健康状况和性能。 * **日志记录 (Rìzhì jìlù):** 使用日志记录库(例如 Python 中的 `logging`)来记录事件和错误。 * **并发 (Bìngfā):** 使用异步编程(例如 Python 中的 `asyncio`)以获得更好的并发性和可伸缩性。 * **gRPC:** 迁移到 gRPC 以获得更高效和强大的通信协议。 定义一个 gRPC 服务定义(一个 `.proto` 文件),指定可用的 RPC 调用。 * **数据库 (Shùjùkù):** 使用数据库来存储有关用户、资源、任务和系统状态的信息。 * **分布式系统 (Fēn bù shì xìtǒng):** 将 MCP 设计为具有多个服务器节点的分布式系统,以实现容错和可伸缩性。 考虑使用分布式共识算法(例如 Raft 或 Paxos)来确保节点之间的一致性。 This provides a starting point for building a system inspired by the MCP. Remember to prioritize security, scalability, and fault tolerance as you develop your implementation. Good luck!

SeolYoungKim

开发者工具
访问服务器

README

通过制作 MCP 深入了解其原理

img.png

MCP 客户端

  • 与 LLM 通信,并与 MCP 服务器通信
  • 例如:克劳德桌面版
  • 也许直接实现的机会不多。如果公司提供某种 AI 服务,也许会有制作的机会?

MCP 服务器

  • 实现要提供的服务
  • 也许开发者们会更多地实现 MCP 服务器,而不是 MCP 客户端?
  • 似乎只支持 JDK17? 使用 21 会报错
    • 运行没有错误,但是克劳德尝试使用 MCP 服务器时会报错,无法运行
    • 也许很快就会支持

大致运行一下

在克劳德桌面版的 claude_desktop_config.json 文件中编写以下内容 img_3.png

  • command 中填写命令。感觉类似于在 Dockerfile 中填写。因为我需要运行 jar 文件,所以填写了 java
  • args 中填写要放入 java 命令的参数。我放入了 -jar 选项和要运行的 jar 文件的绝对路径

img_2.png

  • 如果配置正确,运行克劳德桌面版时会像上面一样显示 running

img_1.png

  • 我在 @Tool 的 description 中放入了 Get the current weather information by city name.。由此推断,如果我命令克劳德 “{城市名称} 的天气”,它应该会利用我的 MCP 服务器,所以我输入了 “水原 天气”,结果确认它按照我编写的脚本进行了响应!

看起来 MCP 服务器可以做很多事情。想想可以尝试做什么吧!

整理学习内容的地方

https://kimsy8979.notion.site/AI-MCP-1c5cbb7e0307805aba8bc8fc4d9a470f?pvs=4

推荐服务器

Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
MCP Package Docs Server

MCP Package Docs Server

促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。

精选
本地
TypeScript
Claude Code MCP

Claude Code MCP

一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。

精选
本地
JavaScript
@kazuph/mcp-taskmanager

@kazuph/mcp-taskmanager

用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。

精选
本地
JavaScript
mermaid-mcp-server

mermaid-mcp-server

一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。

精选
JavaScript
Jira-Context-MCP

Jira-Context-MCP

MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。

精选
TypeScript
Linear MCP Server

Linear MCP Server

一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

精选
JavaScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

精选
Python
Curri MCP Server

Curri MCP Server

通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。

官方
本地
JavaScript