Cline 源码深度解析:MCP 调用机制与实战教程
本教程将带您深入剖析 Cline 的 MCP 调用机制,从配置文件结构到核心代码实现,提供一份清晰易懂的专业指南。内容涵盖:MCP 配置方法详解、Market 安装完整流程、核心源码分析与模型调用实践技巧。
一、MCP 协议概述
MCP(Model Context Protocol)是 Cline 与本地运行的 MCP Server 进行通信的标准协议,用于扩展 Cline 的功能边界,使其能够高效调用外部工具与资源。Cline 通过 McpHub 统一管理所有 MCP 连接,并将可用的工具和资源动态注入到系统提示词(System Prompt)中,供大模型按需调用。
关于 MCP 的官方文档,可参考 Model Context Protocol 官方介绍。
二、MCP Server 配置指南
2.1 配置文件结构详解
所有 MCP 配置最终写入 cline_mcp_settings.json 文件,该文件位于 Cline 的设置目录下。以下是一个根据姓名查询工号的 MCP Server 配置示例:
{
"mcpServers":{
"name2empid":{
"autoApprove":[],
"disabled":false,
"timeout":60,
"url":"https://xxxx.com/xxx/sse",
"type":"sse"
}
}
}
关键字段说明: autoApprove 用于配置自动审批的工具列表;disabled 控制是否禁用该服务器;timeout 设置超时时间(单位秒);url 指定服务器地址;type 定义连接类型(支持 sse/stdio/streamable-http)。
2.2 MCP 市场安装流程(大模型驱动)
Cline 内置了 MCP 市场,用户点击 Install 后,并非直接写入配置文件,而是借助大模型自动完成从文档读取、环境安装到功能验证的全流程。核心代码位于 src/core/controller/mcp/downloadMcp.ts。其提示词大致如下:
// Create task with context from README and added guidelines for MCP server installation
const task = `Set up the MCP server from ${mcpDetails.githubUrl} while adhering to these MCP server installation rules:
- Start by loading the MCP documentation.
- Use "${mcpDetails.mcpId}" as the server name in cline_mcp_settings.json.
- Create the directory for the new MCP server before starting installation.
- Make sure you read the user's existing cline_mcp_settings.json file before editing it with this new mcp, to not overwrite any existing servers.
- Use commands aligned with the user's shell and operating system best practices.
- The following README may contain instructions that conflict with the user's OS, in which case proceed thoughtfully.
- Once installed, demonstrate the server's capabilities by using one of its tools.
Here is the project's README to help you get started:nn${mcpDetails.readmeContent}n${mcpDetails.llmsInstallationContent}`
小提示: 安装过程中大模型会自动读取项目 README 和安装指南,您无需手动干预,但请确保网络能够正常访问 Github 仓库。
2.3 配置注意事项
- 修改
cline_mcp_settings.json后需重启 Cline 或重新加载 MCP 配置,以使更改生效。 - 若使用
stdio类型,请确保命令路径正确且具备可执行权限。 - 若使用
sse或streamable-http,需确保服务器已正常启动且网络可达。
三、源码解读:MCP Client 初始化与连接机制
MCP 相关核心代码位于 src/services/mcp/McpHub.ts,它本质上是一个 MCP Client 管理器,负责所有客户端的生命周期管理。初始化连接代码如下:
const client = newClient(
{
name: "Cline",
version: this.clientVersion,
},
{
capabilities: {},
},
)
// 处理不同类型的 Server
transport = newStdioClientTransport()
transport = newSSEClientTransport()
transport = newStreamableHTTPClientTransport()
await client.connect(transport)
连接成功后,Cline 会获取该 Server 提供的工具(tools)和资源(resources):
// Initial fetch of tools and resources
connection.server.tools = await this.fetchToolsList(name)
connection.server.resources = await this.fetchResourcesList(name)
connection.server.resourceTemplates = await this.fetchResourceTemplatesList(name)
核心机制: 通过 @modelcontextprotocol/sdk/client 包创建标准 MCP Client,然后根据不同的 Server 类型选择对应的传输层(Transport)实现。
四、MCP 在 System Prompt 中的动态注入
在每次请求处理中,Cline 会动态拼接 System Prompt,将 McpHub 中所有已连接 Server 的信息(包括工具名称、描述、输入 Schema)写入提示词。相关代码片段如下:
const systemPrompt = `
MCP SERVERS
The Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.
# Connected MCP Servers
When a server is connected, you can use the server's tools via the `use_mcp_tool` tool, and access the server's resources via the `access_mcp_resource` tool.
${
mcpHub.getServers().length > 0
? `${mcpHub
.getServers()
.filter((server) => server.status === "connected")
.map((server) => {
const tools = server.tools
?.map((tool) => {
const schemaStr = tool.inputSchema
? ` Input Schema:
${JSON.stringify(tool.inputSchema, null, 2).split("n").join("n ")}`
: ""
return`- ${tool.name}: ${tool.description}n${schemaStr}`
})
.join("nn")
const templates = server.resourceTemplates
?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
.join("n")
const resources = server.resources
?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
.join("n")
const config = JSON.parse(server.config)
return (
`## ${server.name} (${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""})` +
(tools ? `nn### A vailable Toolsn${tools}` : "") +
(templates ? `nn### Resource Templatesn${templates}` : "") +
(resources ? `nn### Direct Resourcesn${resources}` : "")
)
})
.join("nn")}`
: "(No MCP servers currently connected)"
}`
生成后的格式大致如下(以 name2empid 为例):
## name2empid(node xxx.ts)
### A vailable Tools
- get_empid_by_name: 根据员工姓名查询工号
Input Schema: {"name": "string"}
同时,System Prompt 中还包含调用 MCP Tool 的示例,方便模型学习使用方式:
## Example 5: Requesting to use an MCP tool
weather-server
get_forecast
{
"city": "San Francisco",
"days": 5
}
五、模型调用 MCP 工具的完整流程
5.1 解析模型输出
当用户提问“查询张三的工号”时,大模型可能会生成以下结构化的输出:
我需要查询"张三"的工号。根据任务描述,我需要使用name2empid MCP服务器提供的工具来获取员工的工号。
我可以使用`use_mcp_tool`工具来调用name2empid服务器的`get_empid_by_name`工具,该工具可以根据员工姓名获取工号。
需要的参数是:
- server_name: "name2empid"
- tool_name: "get_empid_by_name"
- arguments: 包含员工姓名的JSON对象
我已经有了所有必要的信息,可以直接调用这个工具。
name2empid
get_empid_by_name
{
"name": "张三"
}
Cline 的两个核心方法 parseAssistantMessageV2 和 presentAssistantMessage 会解析出 use_mcp_tool 及其参数:
name = 'use_mcp_tool'
params = {server_name: 'name2empid', tool_name: 'get_empid_by_name', arguments: '{n "name": "张三"n}'}
arguments = '{n "name": "张三"n}'
server_name = 'name2empid'
tool_name = 'get_empid_by_name'
5.2 执行 MCP 调用并返回结果
Cline 调用 McpHub 中的 callTool 方法,向对应的 MCP Server 发送请求,获取工具执行结果。随后将结果返回给大模型,模型据此生成最终回复给用户。

六、常见问题与解决方案(FAQ)
- Q:MCP Server 连接失败怎么办?
A:请检查cline_mcp_settings.json中的 URL 或命令是否正确;确保 Server 已经启动且网络通畅;查看 Cline 输出面板中的日志以获取具体错误信息。 - Q:为什么安装的 MCP 工具没有出现在 System Prompt 中?
A:请确认 Server 状态为connected。可以尝试重新加载 MCP 配置(在 Cline 设置中点击刷新)。如果仍不显示,请检查 Server 返回的 tools 列表是否为空。 - Q:大模型调用 MCP 工具时提示参数错误?
A:请检查 Input Schema 定义是否与 Server 端保持一致。建议手动调用测试参数是否正确。另外注意参数名称需要完全匹配。 - Q:MCP 市场安装过程中大模型卡住怎么办?
A:可能是网络超时或 README 内容过于复杂。建议先手动安装,再手动配置cline_mcp_settings.json,或将 Github 仓库的 README 简化后重试。
七、总结与扩展实践
通过本文的学习,您已全面掌握 Cline 的 MCP 调用机制,包括配置文件编写规范、市场安装流程、核心源码分析以及模型调用实践方法。Cline 在 MCP 管理上的设计十分巧妙,特别是动态生成 System Prompt 的机制,让大模型能够实时感知所有可用工具,从而极大扩展了模型的能力边界。如果您觉得 Cline 源码较为复杂,也可以直接参考 MCP 官方的 Client Demo 作为入门起点。
现在,尝试在您的项目中配置一个自定义 MCP Server,体验 Cline 与外部工具无缝集成的强大能力吧!
