MCP Server开发和调试

MCP Server 开发

      我们基于python,使用官方提供的MCP库开发一个代码审计的MCP Server。MCP主要可以三种类型的功能,

  • 1.Resources:客户端可以读取的类似文件的数据(例如 API 响应或文件内容)
  • 2.Tools:可由 LLM 调用的函数
  • 3.Prompts:预先编写的模板,帮助用户完成特定任务

      如果需要做一个简单的代码审计的MCP Server,首先需要通过API函数去依次读取文件的内容,然后将文件的内容和文件路径传递给LLM,通过LLM研判这个文件是否存在高危漏洞。@tools只是实现相对应的逻辑,研判分析的任务交给LLM,不需要将研判的任务写入代码中。

      将所需要的库添加到代码中

1
2
3
4
5
6
import os
from fastmcp import FastMCP
from typing import Dict, Any
import requests
import json
mcp = FastMCP("Code Audit Server") #初始化MCP Server名字

      然后添加Tools功能函数,这个函数需要使用@mcp.tool()进行修饰,这个函数功能是通过传入文件夹路径,读取这个文件夹下所有的文件的内容,传出一个dict,这个字典包含文件夹路径和文件内容。主要的实现功能重新封装在另外一个函数中。

1
2
3
4
@mcp.tool()
def audit_code(directory: str) -> Dict[str, Any]:
file_contents = read_files_from_directory(directory)
return {"directory": directory, "file_contents": file_contents}

      接着实现文件内容的读取操作

1
2
3
4
5
6
7
8
9
10
11
12
def read_files_from_directory(directory: str) -> Dict[str, str]:
file_contents = {}
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
file_contents[file] = content
except Exception as e:
print(f"Error reading file {file_path}: {e}")
return file_contents

      最后,初始化运行MCP Server即可。transport指定传输的方式,目前主要有两种传输方式:1)stdio传输和2)http传输

1
2
if __name__ == "__main__":
mcp.run(transport='stdio')

      通过python server.py即可运行MCP Server。
mark

MCP Inspector 调试使用

      我们可以使用MCP Inspector调试开发好的MCP Server。MCP Inspector基于Node.js开发,需提前安装Node.js,然后执行npm install -g @modelcontextprotocol/inspector命令安装MCP Inspector。如果使用全局安装,只需要运行mcp-inspector启动MCP Inspector
mark

      执行完mcp-inspector命令之后,会生成一个Session token,一个带有session token的链接,以及一个不带session token的链接。这个session token后续链接MCP Servcer需要用上。通过浏览器打开http://127.0.0.1:6274。因为上文是通过python.exe运行server.py来运行MCP Server。只需要将页面左侧的Command和Arguments分别填入python和server.py的绝对地址。内嵌的环境变量就能自动识别。
mark

      如果通过不带session token的链接访问。在连接MCP Server的时候会出现Connection Error - Did you add the proxy session token in Configuration?报错,只需要在“Configuration”的“Proxy Session Token”选项中填入之前出现的Session token值即可。

cline 客户端配置

      安装好cline插件之后,在cline-mcp-settings.json文件中设置相对应的配置即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
"mcpServers": {
"Code Audit Server": {
"autoApprove": [
"audit_code"
],
"disabled": false,
"timeout": 60,
"command": "python",
"args": [
"C:\\Users\\zxcv\\Desktop\\audit_code\\server.py"
],
"transportType": "stdio"
},
"Auto Arms Server": {
"autoApprove": [
"auto_arms"
],
"disabled": false,
"timeout": 60,
"command": "python",
"args": [
"C:\\Users\\zxcv\\Desktop\\AutoArms\\server.py"
],
"transportType": "stdio"
}
}
}

mark