MCP协议入门实战:从零实现一个GitHub Issue管理AI工具
手把手教程:理解MCP(Model Context Protocol)核心概念,并用Python实现一个连接GitHub API的自定义MCP工具。
什么是MCP?为什么重要?
MCP(Model Context Protocol)是由Anthropic在2025年提出的开放协议,它定义了AI模型与外部工具之间的标准通信方式。简单说,MCP就是”AI的USB接口”——让任何AI模型都能插上任何工具。
2026年,MCP已经成为AI Agent接入外部工具的事实标准。OpenAI、DeepSeek、Claude均原生支持。
本文教你从零实现一个MCP工具,让AI助手直接管理GitHub Issue。
MCP核心概念
┌─────────────┐ MCP JSON-RPC ┌──────────────┐
│ AI Model │ ◄─────────────────────► │ MCP Server │
│ (客户端) │ (stdio/HTTP) │ (工具端) │
└─────────────┘ └──────┬───────┘
│
┌──────┴───────┐
│ GitHub API │
└──────────────┘
核心通信格式是JSON-RPC 2.0。MCP Server需要实现三个基本方法:list_tools、call_tool、resource_access。
第一步:环境准备
pip install mcp httpx
MCP官方Python SDK提供了完整的Server基类,我们只需继承它。
第二步:实现MCP Server
import httpx
from mcp.server import Server
from mcp.types import Tool, TextContent
# 初始化Server
server = Server("github-issue-manager")
@server.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="create_issue",
description="在指定GitHub仓库创建Issue",
input_schema={
"type": "object",
"properties": {
"repo": {"type": "string", "description": "仓库名,如 owner/repo"},
"title": {"type": "string", "description": "Issue标题"},
"body": {"type": "string", "description": "Issue正文"}
},
"required": ["repo", "title"]
}
),
Tool(
name="list_issues",
description="列出仓库的开放Issues",
input_schema={
"type": "object",
"properties": {
"repo": {"type": "string"},
"state": {"type": "string", "enum": ["open", "closed"]}
},
"required": ["repo"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
headers = {"Authorization": f"Bearer {arguments.pop('token', os.environ['GITHUB_TOKEN'])}"}
async with httpx.AsyncClient() as client:
if name == "create_issue":
repo = arguments["repo"]
res = await client.post(
f"https://api.github.com/repos/{repo}/issues",
json={"title": arguments["title"], "body": arguments.get("body", "")},
headers=headers
)
data = res.json()
return [TextContent(type="text", text=f"Issue created: {data['html_url']}")]
elif name == "list_issues":
res = await client.get(
f"https://api.github.com/repos/{arguments['repo']}/issues",
params={"state": arguments.get("state", "open")},
headers=headers
)
issues = res.json()
summary = "\n".join([f"- #{i['number']} {i['title']} ({i['state']})" for i in issues[:10]])
return [TextContent(type="text", text=summary)]
第三步:启动Server
if __name__ == "__main__":
server.run(transport="stdio")
两种传输模式:
stdio:AI客户端通过子进程通信,适合本地使用http:暴露为HTTP服务,可远程调用
第四步:连接AI客户端
以Claude Desktop为例,在配置文件中添加:
{
"mcpServers": {
"github-issues": {
"command": "python",
"args": ["path/to/your/server.py"],
"env": {
"GITHUB_TOKEN": "your_token_here"
}
}
}
}
之后Claude就能直接帮你创建、查询、管理GitHub Issues了。
进阶:添加资源(Resource)
除了Tool,MCP还支持”Resource”——让AI读取外部数据。比如加入获取Issue详情的功能:
@server.list_resources()
async def list_resources() -> list[Resource]:
return [Resource(uri="issue://latest", name="最新的Issue", mime_type="application/json")]
总结
至此,你已经实现了一个完整的MCP工具。整个过程不过100行代码,但让你的AI助手具备了真实的软件工程能力。MCP的魅力在于:任何API都可以在两小时内变成AI可调用的工具。 工作中遇到重复性操作,不妨自己做一个小MCP Server,效率翻倍。