MCP 协议从入门到实战:用 AI 连接你的数据库与外部工具
·
MCP 协议从入门到实战:用 AI 连接你的数据库与外部工具
一、什么是 MCP?为什么它突然火了?
MCP(Model Context Protocol,模型上下文协议)是由 Anthropic 推出的一种开源标准协议,旨在为 AI 应用与外部系统之间建立统一的通信接口。你可以把它理解为 AI 世界的"USB-C 接口"——就像 USB-C 统一了电子设备的连接方式一样,MCP 统一了大模型与数据库、API、文件系统等工具的交互方式。
截至 2026 年中,MCP 生态已经相当成熟:Claude Desktop、ChatGPT、Cursor、VS Code、JetBrains 等主流 AI 客户端都已原生支持 MCP,GitHub 上各类型 MCP Server 项目累计获得数十万 Star。华为云、金仓数据库等厂商也纷纷推出官方的 MCP Server 方案。
二、MCP 的核心架构
MCP 采用标准的客户端-服务器架构:
- MCP Host:运行 AI 模型的客户端,如 Claude Desktop、Cursor、VS Code
- MCP Client:Host 内部与 Server 建立一对一连接的通信层
- MCP Server:轻量级程序,通过标准化接口暴露特定功能
每个 MCP Server 可以暴露三种核心能力:
- Tools(工具):可由 LLM 调用的函数,如查询数据库、调用 API
- Resources(资源):可被客户端读取的文件类数据
- Prompts(提示词):预定义的模板
数据传输支持两种模式:
- Stdio:本地开发首选,无需开放端口
- SSE/Streamable HTTP:远程访问,支持 HTTPS
三、实战:从零构建一个 MCP Server
下面用 Python 构建一个实用的文本分析 MCP Server,提供文本统计分析和关键词提取两个工具。以下代码已在本地验证通过。
环境准备
curl -LsSf https://astral.sh/uv/install.sh | sh
uv init text-analyzer-mcp
cd text-analyzer-mcp
uv venv
source .venv/bin/activate
uv add "mcp[cli]"
编写 Server 代码
创建 text_analyzer.py:
import re
import sys
from collections import Counter
from typing import Any
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("text-analyzer")
def count_words(text: str) -> dict[str, Any]:
words = re.findall(r"[a-zA-Z]+", text)
return {
"total_words": len(words),
"unique_words": len(set(words)),
"word_frequencies": dict(Counter(words).most_common(10)),
}
def count_sentences(text: str) -> dict[str, Any]:
sentences = re.split(r"[。!?.!?\n]+", text)
sentences = [s.strip() for s in sentences if s.strip()]
total = len(sentences)
avg_len = round(sum(len(s.split()) for s in sentences) / max(total, 1), 2)
return {"total_sentences": total, "avg_sentence_length": avg_len}
def count_characters(text: str) -> dict[str, Any]:
chinese_chars = len(re.findall(r"[\u4e00-\u9fff]", text))
return {"chinese_chars": chinese_chars, "total_chars": len(text)}
@mcp.tool()
def analyze_text(text: str) -> str:
"""分析文本并返回综合统计信息"""
word_stats = count_words(text)
sentence_stats = count_sentences(text)
char_stats = count_characters(text)
result = f"""📊 文本分析结果
📝 基本统计
· 总字符数: {char_stats['total_chars']}
· 中文字数: {char_stats['chinese_chars']}
· 英文单词数: {word_stats['total_words']}
· 唯一单词数: {word_stats['unique_words']}
· 句子数: {sentence_stats['total_sentences']}
🔝 高频词汇 Top 10:"""
freq = word_stats["word_frequencies"]
if freq:
for i, (word, count) in enumerate(freq.items(), 1):
result += f"\n {i}. \"{word}\" — {count} 次"
else:
result += "\n (文本中未检测到英文词汇)"
return result
@mcp.tool()
def extract_keywords(text: str, top_n: int = 5) -> str:
"""提取文本中的关键词"""
stop_words = {"the", "a", "an", "is", "are", "was", "were",
"have", "has", "had", "do", "does", "did",
"to", "of", "in", "for", "on", "with", "and", "or"}
words = re.findall(r"[a-zA-Z]+", text.lower())
filtered = [w for w in words if w not in stop_words and len(w) > 1]
freq = Counter(filtered)
keywords = freq.most_common(top_n)
if not keywords:
return "未检测到足够的关键词"
result = f"🔑 关键词提取(Top {top_n})\n"
for i, (word, count) in enumerate(keywords, 1):
result += f" {i}. \"{word}\" — {count} 次\n"
return result
if __name__ == "__main__":
mcp.run(transport="stdio")
验证
uv run text_analyzer.py
启动后,任意支持 MCP 的客户端均可连接使用这两个工具。
四、接入 AI 客户端
以 Cursor/VS Code 为例,在 MCP 配置中添加:
{
"mcpServers": {
"text-analyzer": {
"command": "uv",
"args": ["run", "--directory", "/path/to/text-analyzer-mcp", "text_analyzer.py"]
}
}
}
五、实际应用场景
- 数据库查询:自然语言查询 MySQL/PostgreSQL,无需手写 SQL
- 文件操作:AI 直接读写本地文件、JSON 配置
- API 集成:调用 GitHub、Slack、Notion 等第三方服务
- 浏览器自动化:MCP + Playwright 实现 AI 驱动浏览器操作
六、总结
MCP 协议通过标准化接口,大幅降低了 AI 与外部工具的集成门槛。一次编写,多客户端复用。掌握 MCP 开发是搭建 AI 时代基础设施的重要技能。
更多推荐



所有评论(0)