在多智能体系统中,不同语言开发的智能体、异构服务之间的通信效率往往受制于接口兼容性问题。MCP(Model Context Protocol)协议通过标准化接口定义与跨语言工具链,实现了“服务能力像积木一样自由拼接”的目标。本文将结合实战案例,带你掌握MCP接口开发的核心技术,让你的智能体轻松对接各类服务。
MCP要求每个服务接口必须明确声明:
create_branch
、commit_code
)示例:GitHub创建分支接口函数声明(Python伪代码)
def create_branch(
repo_owner: str, # 必传:仓库所有者
repo_name: str, # 必传:仓库名称
branch_name: str, # 必传:分支名称
base_branch: str = "main" # 可选:基础分支,默认main
) -> dict:
"""
创建仓库分支
:return: {"status": "success", "branch_url": "https://..."} 成功响应
:raises: MCPError(403, "权限不足") 错误示例
"""
通过JSON Schema定义接口的输入输出格式,确保数据校验自动化:
{
"type": "object",
"required": ["repo_owner", "repo_name", "branch_name"],
"properties": {
"repo_owner": {"type": "string", "minLength": 1},
"repo_name": {"type": "string", "minLength": 1},
"branch_name": {"type": "string", "pattern": "^[a-z0-9-]+$"}, # 分支名格式校验
"base_branch": {"type": "string", "default": "main"}
}
}
{
"type": "object",
"oneOf": [ # 成功响应或错误响应
{
"properties": {
"status": {"const": "success"},
"branch_url": {"type": "string", "format": "uri"}
}
},
{
"properties": {
"status": {"const": "error"},
"code": {"type": "number", "minimum": 400},
"message": {"type": "string"}
}
}
]
}
优势:
jsonschema
库自动校验请求数据,拦截非法输入MCP通过OpenAPI规范实现接口定义的语言无关性,配合代码生成工具,可快速生成Python/TypeScript/Kotlin等语言的客户端SDK。
# 初始化客户端(自动加载证书与鉴权信息)
from mcp_sdk import MCP_CLIENT
client = MCP_CLIENT(
service_id="github-service",
auth_token="your-personal-access-token"
)
# 调用创建分支接口
response = client.create_branch(
repo_owner="your-username",
repo_name="your-repo",
branch_name="feature/new-endpoint"
)
print(f"分支创建结果:{response['status']}")
// 类型安全的接口调用
import { GitHubClient } from 'mcp-sdk-ts';
const client = new GitHubClient({
authToken: 'your-personal-access-token'
});
async function createBranch() {
const result = await client.createBranch({
repoOwner: 'your-username',
repoName: 'your-repo',
branchName: 'feature/new-endpoint'
});
console.log(`分支URL:${result.branchUrl}`); // 自动推导类型
}
// 协程友好的异步调用
val client = MCPRetrofit.create<GitHubService>(
baseUrl = "https://api.github.com",
authToken = "your-personal-access-token"
)
suspend fun createBranch() {
val response = client.createBranch(
repoOwner = "your-username",
repoName = "your-repo",
branchName = "feature/new-endpoint"
)
if (response.status == "success") {
println("分支创建成功:${response.branchUrl}")
}
}
核心价值:
功能 | MCP接口名 | GitHub API端点 | 认证方式 |
---|---|---|---|
创建分支 | create_branch |
POST /repos/{owner}/{repo}/git/refs |
OAuth Token |
提交代码 | commit_code |
POST /repos/{owner}/{repo}/git/commits |
Personal Access Token |
def create_branch(
self, repo_owner: str, repo_name: str, branch_name: str, base_branch: str = "main"
):
# 获取基础分支SHA
base_sha = self._get_base_branch_sha(repo_owner, repo_name, base_branch)
# 构造GitHub API请求
url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/git/refs"
payload = {
"ref": f"refs/heads/{branch_name}",
"sha": base_sha
}
headers = {
"Authorization": f"token {self.auth_token}",
"Accept": "application/vnd.github.v3+json"
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return {"status": "success", "branch_url": response.json()["url"]}
def _get_base_branch_sha(self, repo_owner, repo_name, base_branch):
# 获取基础分支的最新提交SHA
url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/branches/{base_branch}"
response = requests.get(url, headers=self.headers)
return response.json()["commit"]["sha"]
def commit_code(
self,
repo_owner: str,
repo_name: str,
branch_name: str,
file_path: str,
content: str,
commit_message: str
):
# 获取分支最新SHA(用于创建树)
head_sha = self._get_branch_head_sha(repo_owner, repo_name, branch_name)
# 创建树(包含文件变更)
tree = self._create_tree(repo_owner, repo_name, head_sha, file_path, content)
# 创建提交
commit_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/git/commits"
commit_payload = {
"message": commit_message,
"tree": tree["sha"],
"parents": [head_sha]
}
response = requests.post(commit_url, json=commit_payload, headers=self.headers)
return {"status": "success", "commit_url": response.json()["url"]}
def _create_tree(self, repo_owner, repo_name, base_sha, file_path, content):
# 编码文件内容为Base64
encoded_content = base64.b64encode(content.encode()).decode()
# 创建树对象
tree_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/git/trees"
tree_payload = {
"base_tree": base_sha,
"tree": [
{
"path": file_path,
"mode": "100644", # 文件类型(可执行文件为100755)
"type": "blob",
"content": encoded_content
}
]
}
response = requests.post(tree_url, json=tree_payload, headers=self.headers)
return response.json()
https://mcp-gateway/github-service/create-branch
{
"repo_owner": "your-username",
"repo_name": "your-repo",
"branch_name": "feature/mcp-sdk"
}
{
"status": "success",
"branch_url": "https://api.github.com/repos/your-username/your-repo/branches/feature/mcp-sdk"
}
/v1/github/create-branch
),避免 breaking change4xx
用户错误,5xx
服务端错误),返回详细错误信息通过MCP协议的标准化接口设计与跨语言SDK支持,开发者无需关注底层通信细节,即可快速实现智能体与外部服务的对接。本文的GitHub实战案例展示了如何将复杂的第三方API转化为简洁的MCP接口,这正是多智能体系统“松耦合、高扩展”的核心优势。
下一篇我们将深入探讨多智能体通信协议优化,教你如何让智能体在高并发场景下“高效对话”。欢迎关注系列课程,一起解锁智能协作的更多可能!