MCP 協(xié)議由一個(gè) client 和多個(gè) server 組成。用戶(hù)發(fā)出請(qǐng)求后,client 會(huì)去調(diào)用 server 執(zhí)行邏輯并返回給用戶(hù)。

client 就是用戶(hù)的對(duì)話(huà)框,server 是一些我們提前寫(xiě)好的代碼,用來(lái)完成我們想實(shí)現(xiàn)的系統(tǒng)調(diào)用。client 和 server 都可以自行開(kāi)發(fā)。

核心概念

工具 (Tools)

工具是服務(wù)器編寫(xiě),可由客戶(hù)端調(diào)用并由 LLM 用來(lái)執(zhí)行操作的可執(zhí)行函數(shù)。

當(dāng)前對(duì)其支持較多,主要的邏輯都通過(guò)工具來(lái)實(shí)現(xiàn)。

提示 (Prompts)

可以理解為預(yù)設(shè)好的提示詞模版,用于補(bǔ)充用戶(hù)的輸入。

假設(shè)用戶(hù)輸入的是:

def add(a, b):
return a + b

生成的提示可能是:

Explain how this Python code works:
def add(a, b):
return a + b

當(dāng)前對(duì)其的支持相對(duì)較少。

資源 (Resources)

提供服務(wù)端的資源給客戶(hù)端。

當(dāng)前對(duì)其支持相對(duì)較少,一般只有客戶(hù)端顯示調(diào)用的時(shí)候才會(huì)使用。

工作流程

MCP 的工作流程可以在這里找到:https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/clients/simple-chatbot

簡(jiǎn)單總結(jié)如下:

  1. 初始化:客戶(hù)端訪問(wèn)服務(wù)端的接口,獲取 tools,prompts,resources 等資源。
  2. 客戶(hù)端接收用戶(hù)輸入,并攜帶著上述資源的上下文一起發(fā)送給大模型
  3. 客戶(hù)端判斷通過(guò)大模型輸出判斷是否需要調(diào)用資源,如果需要就去調(diào)用,并把調(diào)用的結(jié)果返回給大模型
  4. 大模型分析,整合結(jié)果后返回給客戶(hù)端。

提示詞

官方 demo 中的提示詞如下

system_message = (
"You are a helpful assistant with access to these tools:\n\n"
f"{tools_description}\n"
"Choose the appropriate tool based on the user's question. "
"If no tool is needed, reply directly.\n\n"
"IMPORTANT: When you need to use a tool, you must ONLY respond with "
"the exact JSON object format below, nothing else:\n"
"{\n"
' "tool": "tool-name",\n'
' "arguments": {\n'
' "argument-name": "value"\n'
" }\n"
"}\n\n"
"After receiving a tool's response:\n"
"1. Transform the raw data into a natural, conversational response\n"
"2. Keep responses concise but informative\n"
"3. Focus on the most relevant information\n"
"4. Use appropriate context from the user's question\n"
"5. Avoid simply repeating the raw data\n\n"
"Please use only the tools that are explicitly defined above."
)

使用 MCP,我們需要:

下面使用 Claude模型,使用 Claude Desktop 作為 MCP Client,自己開(kāi)發(fā) MCP Server 進(jìn)行使用。(也可以直接使用官方的 MCP Server)

Server 開(kāi)發(fā)流程

使用 python sdk 開(kāi)發(fā),前置需要 Mac,并安裝 python uv 和 Claudedesktop。

官網(wǎng)給出的開(kāi)發(fā)流程:https://modelcontextprotocol.io/quickstart/server

創(chuàng)建環(huán)境

使用 uv 創(chuàng)建開(kāi)發(fā)環(huán)境

# Create a new directory for our project
uv init 項(xiàng)目名
cd 項(xiàng)目名

# Create virtual environment and activate it
uv venv
source .venv/bin/activate

# Install dependencies
uv add "mcp[cli]" httpx

編寫(xiě) mcp server 代碼

官網(wǎng)上有 demo (https://modelcontextprotocol.io/quickstart/server) 可以直接丟給大模型仿照這個(gè)寫(xiě)。

寫(xiě)提示詞的時(shí)候要注意下 mcp server 的提示詞來(lái)源,閱讀源代碼發(fā)現(xiàn)它有兩種方式:用戶(hù)手動(dòng)指定 description,就是自己寫(xiě)提示詞,如果用戶(hù)不手動(dòng)指定的話(huà),就默認(rèn)使用 mcp server 代碼的注釋作為提示詞。

配置 claude desktop

編寫(xiě)完代碼,測(cè)試能成功運(yùn)行之后,需要修改 claude desktop 的配置使其識(shí)別到這個(gè) server,配置路徑:

~/Library/Application\ Support/Claude/claude_desktop_config.json

配置的格式

{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"/Users/wpy/downloads/mcp-test",
"run",
"hello.py"
]
}
}
}

保存并退出之后,重啟 Claudedesktop,就能看到對(duì)話(huà)框的右下角出現(xiàn)一個(gè)錘子標(biāo)志:

出現(xiàn)這個(gè)標(biāo)志就表明 desktop 已經(jīng)識(shí)別到了編寫(xiě)的 server,接下來(lái)就可以開(kāi)始使用了。

針對(duì)提出的問(wèn)題,模型會(huì)自主判斷是否要使用這些 server,并在使用的時(shí)候發(fā)出提示:

Server demo1:查看本地文件

實(shí)現(xiàn)

MCP Server 運(yùn)行在本地,直接訪問(wèn)本地的文件。

server 代碼:

import os
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("file")

@mcp.tool()
async def list_directory_contents(directory: str) -> str:
"""List the contents of a directory.

Args:
directory: The path of the directory to list.
"""
try:
# Get the list of files and directories in the specified path
directory_contents = os.listdir(directory)

if not directory_contents:
return "The directory is empty."

# Format the contents into a readable list
contents = "\n".join(directory_contents)
return f"Contents of {directory}:\n{contents}"
except FileNotFoundError:
return f"Directory {directory} not found."
except PermissionError:
return f"Permission denied to access {directory}."
except Exception as e:
return f"An error occurred: {str(e)}"

if __name__ == "__main__":
# Initialize and run the server
mcp.run(transport='stdio')

Claude desktop 的配置文件:

{
"file": {
"command": "uv",
"args": [
"--directory",
"/Users/wpy/downloads/file-mcp",
"run",
"hello.py"
]
}
}
}

效果

可以查看本地目錄下的文件。

Server demo2:查詢(xún) vlogs 日志

實(shí)現(xiàn)

本地運(yùn)行 vlogs server,通過(guò) MCP 的 Server 去訪問(wèn)。

server 代碼:

import os
import requests
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("file")

# Define the URL for the API endpoint
API_URL = "http://localhost:8428/queryLogsByParams"
HEADERS = {
"Content-Type": "application/json",
"Authorization": "Bearer my-token"
}

@mcp.tool()
async def get_logs(time: str, namespace: str, app: str, limit: str, pod: list, container: list, keyword: str) -> str:
"""Get logs from the API by passing parameters.

Args:
time: The time filter for logs (e.g., "10h").
namespace: The namespace of the application (e.g., "gpu-operator").
app: The name of the application (e.g., "gpu-operator").
limit: The limit for the number of logs to retrieve.
pod: The list of pods to query.
container: The list of containers to query.
keyword: The keyword to filter logs by.
"""
data = {
"time": time,
"namespace": namespace,
"app": app,
"limit": limit,
"jsonMode": "false",
"stderrMode": "true",
"numberMode": "false",
"numberLevel": "h",
"pod": pod,
"container": container,
"keyword": keyword,
"jsonQuery": []
}

try:
# Make the POST request to the API
response = requests.post(API_URL, headers=HEADERS, json=data)

if response.status_code == 200:
# If the request was successful, return the log data
return f"Logs retrieved successfully:\n{response.text}"
else:
return f"Failed to retrieve logs. Status code: {response.status_code}"

except requests.exceptions.RequestException as e:
return f"An error occurred while accessing the API: {str(e)}"

if __name__ == "__main__":
# Initialize and run the server
mcp.run(transport='stdio')

Claude desktop 的配置文件:

{
"mcpServers": {
"vlogs-server": {
"command": "uv",
"args": [
"--directory",
"/Users/wpy/downloads/vlogs-mcp",
"run",
"hello.py"
]
}
}
}

效果

可以實(shí)現(xiàn)使用 AI 查詢(xún)并分析用戶(hù)的日志。

從效果上看,可以滿(mǎn)足我們的部分需求。

總結(jié)

從效果上看,像上面的 demo 一樣,開(kāi)發(fā)一套 MCP Server 和 Client 可以滿(mǎn)足我們的部分需求,實(shí)現(xiàn) AI 的工程化接入。

能實(shí)現(xiàn)的需求包括:

還可以根據(jù)其官方和社區(qū)提供的各種 MCP Server 思考新的功能

官方 SDK 存在的問(wèn)題

之前的 demo 中 MCP Server 的開(kāi)發(fā)都依賴(lài)了官方的 SDK,但是官方的 SDK 存在一些問(wèn)題

后續(xù)迭代思路

依賴(lài)官方 SDK,開(kāi)發(fā) MCP Server 和 Client

可以通過(guò)一些操作解決之前提到的問(wèn)題,而不重寫(xiě) SDK。

總結(jié):本地 AI-Coding 就在 cline 基礎(chǔ)上內(nèi)置一些 MCP 和環(huán)境信息,Web 網(wǎng)站上就在 Nextjs 端做一下 MCP 即可。

根據(jù)官方的 SDK 重寫(xiě),然后開(kāi)發(fā) MCP Server 和 Client

Claude 的 SDK 都開(kāi)源了 (例如 python-sdk 位于 https://github.com/modelcontextprotocol/python-sdk),可以仿照開(kāi)發(fā)出其他語(yǔ)言的 SDK。

通過(guò)重寫(xiě) SDK,可以把 MCP Server 放在遠(yuǎn)程并支持其他模型,用戶(hù)本地不需要安裝一堆的 server,除了一個(gè) client,其他都放在遠(yuǎn)程:

采用這個(gè)方案,成本更高,但是可以完全符合我們的需求,并且可以考慮后續(xù)和其官方社區(qū)合作。

不使用 mcp 協(xié)議,選用其他方案

MCP 協(xié)議稍微有點(diǎn)復(fù)雜,不過(guò)其中的一些設(shè)計(jì)理念可以參考。

本文轉(zhuǎn)載自公眾號(hào)@sealos

上一篇:

Serper API搜索引擎數(shù)據(jù)查詢(xún) API 的全面指南

下一篇:

什么是端側(cè)大模型:技術(shù)進(jìn)展、應(yīng)用場(chǎng)景與未來(lái)趨勢(shì)
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)