Skip to content

Commit 3309bb3

Browse files
📝 更新MCP文档,增强内容与示例
- 修改了MCP接口标准部分,增加了对OpenAI API风格与MCP的比较,提升文档的实用性与可读性。 - 优化了MCP功能描述,新增采样功能的说明,增强对MCP服务器功能的理解。 - 更新了代码示例,提供了更清晰的Echo服务器实现,提升示例的可操作性。 - 增加了配置文件示例,简化了MCP服务器的配置说明,提升文档的易用性。 - 精简了最佳实践部分,确保信息的清晰度与准确性。
1 parent 8bd55c3 commit 3309bb3

File tree

1 file changed

+55
-185
lines changed

1 file changed

+55
-185
lines changed

docs/docs/后端通识/接口开发.md

Lines changed: 55 additions & 185 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,13 @@ API,全称为 **应用程序编程接口**(Application Programming Interface
1717

1818
### 接口标准
1919

20-
21-
| 维度 | **RESTful API** |**RPC** |
22-
|------|----------------|------------------|
23-
| **设计理念** | 资源为中心(GET /users) | **操作为中心**(调用 `run_code_analysis`|
24-
| **AI 工具友好性** | ⚠️ 一般(需映射工具为资源) |**极佳**(直接暴露函数,参数即输入) |
25-
| **自动文档 & 发现** | ✅ OpenAPI(Swagger)成熟 | ✅ MCP 支持 `list-tools` / JSON Schema |
26-
| **典型用例** | 模型推理 API / 向量数据库查询 / 用户管理 |MCP 工具插件 / Cursor 自定义命令 / LLM 函数调用 |
27-
20+
| 特性 | **OpenAI API 风格** | **MCP** | **OpenAPI** |
21+
|------|-------------------|---------|-------------|
22+
| **类型** | 商业 API 设计 | 开放通信协议 | 开放 API 描述规范 |
23+
| **是否开放治理** | ❌(OpenAI 控制) | ✅(社区驱动) | ✅(Linux 基金会) |
24+
| **是否可自由实现** | ⚠️(法律风险模糊) | ✅(MIT 许可) ||
25+
| **是否有正式规范文档** | ✅(但非标准组织发布) | ✅(mcp.spec) | ✅(openapis.org) |
26+
| **目标** | 调用 LLM | LLM 与工具通信 | 描述 RESTful API |
2827

2928
### 开发框架
3029

@@ -517,219 +516,90 @@ if __name__ == '__main__':
517516
uvicorn.run(app, host=ip_host2, port=80)
518517
```
519518

520-
### MCP
519+
## MCP
521520

522-
**Model Context Protocol(MCP)** 是一种开放协议,旨在标准化应用程序与大型语言模型(LLM)之间的上下文交互。属于 RPC 风格。
521+
**Model Context Protocol(MCP)** 是一种开放协议,旨在标准化应用程序与大型语言模型(LLM)之间的上下文交互。
523522

524-
通过 MCP,开发者可以为 LLM 提供结构化的上下文信息、工具和资源,从而增强模型的功能和性能
523+
MCP最初设计的对象是<Highlight>各类AI客户端(如 Claude Desktop、Cursor),客户端通过配置文件连接 MCP 服务器</Highlight>
525524

526-
MCP 服务器可以暴露三种主要类型的功能
525+
MCP 服务器可以暴露多种类型的功能
527526

528527
- **Resources(资源):** 只读数据源,如文件内容、数据库查询结果等
529528
- **Tools(工具):** LLM 可以调用的函数,用于执行操作或获取动态数据
530529
- **Prompts(提示词):** 预定义的提示词模板,可供 LLM 使用
530+
- **Sampling(采样):** 工具可反向调用大模型为自己生成一些内容
531531

532-
#### 安装
533-
534-
可以使用 `uv` 快速安装:`uv add "mcp[cli]"`
532+
并不是所有的主要类型功能都被支持,其中Tools支持范围最广。
535533

534+
为了更快速的构建MCP,可以使用FastMCP 处理所有复杂的协议细节,专注于构建。大多数情况下,只需装饰一个 Python 函数即可,FastMCP 会处理剩下的工作。
536535

537-
#### 快速开始
536+
参考地址:https://github.com/jlowin/fastmcp
538537

539-
使用 FastMCP 快速创建一个 MCP 服务器:
538+
### 代码示例
540539

541-
```python showLineNumbers
542-
from mcp.server.fastmcp import FastMCP
540+
```python showLineNumbers title="file_server.py"
541+
"""
542+
FastMCP Echo Server
543+
"""
543544

544-
mcp = FastMCP("计算器服务")
545+
from fastmcp import FastMCP
545546

546-
@mcp.tool()
547-
def add(a: float, b: float) -> float:
548-
"""返回两个数字的和"""
549-
return a + b
547+
# Create server
548+
mcp = FastMCP("Echo Server")
550549

551-
if __name__ == "__main__":
552-
mcp.run()
553-
```
554550

555-
#### 客户端调用
551+
@mcp.tool
552+
def echo_tool(text: str) -> str:
553+
"""Echo the input text"""
554+
return text
556555

557-
```python showLineNumbers
558-
from mcp.client import ClientSession, StdioServerParameters
559-
from mcp.client.stdio import stdio_client
560-
561-
async def run_client():
562-
server_params = StdioServerParameters(
563-
command="python",
564-
args=["server.py"]
565-
)
566-
567-
async with stdio_client(server_params) as (read, write):
568-
async with ClientSession(read, write) as session:
569-
await session.initialize()
570-
571-
# 列出工具
572-
tools = await session.list_tools()
573-
574-
# 调用工具
575-
result = await session.call_tool("add", {"a": 1, "b": 2})
576-
print(f"结果: {result.content}")
577556

578-
if __name__ == "__main__":
579-
import asyncio
580-
asyncio.run(run_client())
581-
```
557+
@mcp.resource("echo://static")
558+
def echo_resource() -> str:
559+
return "Echo!"
582560

583-
#### 生产级示例:文件系统服务器
584561

585-
```python showLineNumbers
586-
from mcp.server.fastmcp import FastMCP
587-
import os
588-
import fnmatch
589-
from pathlib import Path
590-
591-
mcp = FastMCP("文件系统服务")
592-
593-
# 配置允许访问的根目录(安全限制)
594-
ALLOWED_ROOTS = ["/home/user/documents", "/home/user/projects"]
595-
596-
def validate_path(path: str) -> Path:
597-
"""验证路径是否在允许的范围内"""
598-
abs_path = Path(path).resolve()
599-
600-
# 检查是否在允许的根目录内
601-
if not any(abs_path.is_relative_to(root) for root in ALLOWED_ROOTS):
602-
raise PermissionError(f"访问被拒绝: {path}")
603-
604-
return abs_path
605-
606-
@mcp.resource("file://{path}")
607-
def read_file(path: str) -> str:
608-
"""读取文件内容"""
609-
validated_path = validate_path(path)
610-
611-
if not validated_path.exists():
612-
raise FileNotFoundError(f"文件不存在: {path}")
613-
614-
if not validated_path.is_file():
615-
raise ValueError(f"不是文件: {path}")
616-
617-
# 限制文件大小(例如最大 10MB)
618-
if validated_path.stat().st_size > 10 * 1024 * 1024:
619-
raise ValueError(f"文件过大: {path}")
620-
621-
with open(validated_path, 'r', encoding='utf-8') as f:
622-
return f.read()
623-
624-
@mcp.tool()
625-
def list_directory(path: str, include_hidden: bool = False) -> dict:
626-
"""列出目录内容"""
627-
validated_path = validate_path(path)
628-
629-
if not validated_path.is_dir():
630-
raise ValueError(f"不是目录: {path}")
631-
632-
files = []
633-
dirs = []
634-
635-
for item in validated_path.iterdir():
636-
if not include_hidden and item.name.startswith('.'):
637-
continue
638-
639-
if item.is_file():
640-
files.append({
641-
"name": item.name,
642-
"size": item.stat().st_size,
643-
"modified": item.stat().st_mtime
644-
})
645-
elif item.is_dir():
646-
dirs.append(item.name)
647-
648-
return {
649-
"path": str(path),
650-
"directories": sorted(dirs),
651-
"files": sorted(files, key=lambda x: x['name'])
652-
}
562+
@mcp.resource("echo://{text}")
563+
def echo_template(text: str) -> str:
564+
"""Echo the input text"""
565+
return f"Echo: {text}"
653566

654-
@mcp.tool()
655-
def search_files(directory: str, pattern: str, max_results: int = 100) -> list[str]:
656-
"""搜索文件(支持通配符)"""
657-
validated_path = validate_path(directory)
658-
659-
if not validated_path.is_dir():
660-
raise ValueError(f"不是目录: {directory}")
661-
662-
matches = []
663-
count = 0
664-
665-
for root, dirs, files in os.walk(validated_path):
666-
# 跳过隐藏目录
667-
dirs[:] = [d for d in dirs if not d.startswith('.')]
668-
669-
for filename in fnmatch.filter(files, pattern):
670-
if count >= max_results:
671-
break
672-
matches.append(os.path.join(root, filename))
673-
count += 1
674-
675-
if count >= max_results:
676-
break
677-
678-
return matches
679-
680-
@mcp.tool()
681-
def get_file_info(path: str) -> dict:
682-
"""获取文件详细信息"""
683-
validated_path = validate_path(path)
684-
685-
if not validated_path.exists():
686-
raise FileNotFoundError(f"文件不存在: {path}")
687-
688-
stat = validated_path.stat()
689-
690-
return {
691-
"path": str(path),
692-
"name": validated_path.name,
693-
"type": "file" if validated_path.is_file() else "directory",
694-
"size": stat.st_size,
695-
"created": stat.st_ctime,
696-
"modified": stat.st_mtime,
697-
"permissions": oct(stat.st_mode)[-3:]
698-
}
699567

700-
if __name__ == "__main__":
701-
mcp.run()
568+
@mcp.prompt("echo")
569+
def echo_prompt(text: str) -> str:
570+
return text
702571
```
703572

704-
#### 配置文件
573+
### 配置文件
705574

706-
客户端(如 Claude Desktop、Cursor)通过配置文件连接 MCP 服务器:
575+
上面的代码我部署在`https://fastmcp.cloud/`中,下面的地址是其为我随机分配的。填入cursor后登录验证即可。
707576

708577
```json showLineNumbers
709578
{
710579
"mcpServers": {
711-
"filesystem": {
712-
"command": "python",
713-
"args": ["file_server.py"],
714-
"env": {
715-
"ALLOWED_PATHS": "/home/user/documents"
716-
}
580+
"fastmcp": {
581+
"url": "https://magnificent-crimson-antlion.fastmcp.app/mcp",
582+
"transport": "http"
717583
}
718584
}
719585
}
720586
```
721587

722-
#### 最佳实践
588+
如果是通过放在本地,则只需要配置全局的`fastmcp`,确保路径正确即可。
723589

724-
1. **工具命名:** 使用描述性的名称,遵循 `category.action` 模式(如 `file.read``database.query`
725-
2. **输入验证:** 使用 JSON Schema 严格定义工具参数
726-
3. **错误处理:** 提供清晰的错误消息,帮助 LLM 理解问题
727-
4. **文档:** 为每个工具、资源和提示词提供详细的描述
728-
5. **安全性:** 验证输入参数,避免路径遍历、SQL 注入等安全问题
729-
6. **性能:** 对于耗时操作,使用异步函数和进度通知
730-
7. **日志记录:** 适当使用日志帮助调试和监控
590+
```json showLineNumbers
591+
{
592+
"mcpServers": {
593+
"local-echo-server": {
594+
"command": "fastmcp",
595+
"args": ["run", "C:\\Users\\allen\\Desktop\\MCP\\server.py"],
596+
"transport": "stdio"
597+
}
598+
}
599+
}
600+
```
731601

732-
MCP 协议为 LLM 应用提供了强大的扩展能力,使 AI 助手能够安全、标准化地访问外部资源和执行操作。更多信息请参考 [MCP 官方文档](https://modelcontextprotocol.github.io/python-sdk/api/)[PyPI 包页面](https://pypi.org/project/mcp/)
602+
更多信息请参考 [MCP 官方文档](https://modelcontextprotocol.github.io/python-sdk/api/)[PyPI 包页面](https://pypi.org/project/mcp/)
733603

734604

735605
## Django

0 commit comments

Comments
 (0)