diff --git a/07-Other/AI/AI Agent/MCP & Skill.md b/07-Other/AI/AI Agent/MCP & Skill.md index 1d6d9c6..a4ae860 100644 --- a/07-Other/AI/AI Agent/MCP & Skill.md +++ b/07-Other/AI/AI Agent/MCP & Skill.md @@ -23,6 +23,341 @@ - 存储类 - Obsidian MCP:本地哲学笔记库同步与知识图谱构建。 `claude mcp add obsidian -- npx -y @obsidian-mcp/server` - **Mem0 (OpenMemory)**:用户观点长期记忆与思想进化追踪。 `claude mcp add mem0 -- npx -y @mem0/mcp-server` +## MCP案例代码 +根据 MCP 官方文档(2025-2026 版)和 GitHub 上的最新进展,**SSE (Server-Sent Events)** 正在逐渐被更现代的 **Streamable HTTP** 协议所取代。 +以下是两者的核心区别及代码案例: + +### 1. Python 案例 (使用 FastMCP) +在 Python 中,`FastMCP` 库极大地简化了切换过程,你只需要更改一个参数。 +```python +from fastmcp import FastMCP + +mcp = FastMCP("MyRemoteServer") + +@mcp.tool() +async def fetch_bilibili_hot(limit: int = 10): + """获取B站热门视频""" + return f"Retrieved {limit} hot videos" + +# --- 运行方式 --- +# 方案 A: 传统的 SSE 模式 (已不推荐) +# mcp.run(transport="sse", host="0.0.0.0", port=8000) + +# 方案 B: 现代的 Streamable HTTP 模式 (推荐) +if __name__ == "__main__": + mcp.run(transport="streamable-http", host="0.0.0.0", port=8000) +``` +--- + +### 2. TypeScript 案例 (使用 SDK) +在 TypeScript 中,你通常会配合 Express 或 Hono 框架使用。 +这份参考代码将使用 **TypeScript** 和 **Hono** 框架。选择 Hono 是因为它是目前实现 **Streamable HTTP**(基于 Web 标准的 `ReadableStream`)最轻量且跨平台的方案,可以直接在 Node.js、Bun、Deno 或 Cloudflare Workers 上运行。 + +--- + +### 1. 项目初始化 + +首先,你需要安装核心依赖: + +```bash +npm install @modelcontextprotocol/sdk hono + +``` + +### 2. Streamable HTTP 服务端完整代码 + +这份代码展示了如何创建一个支持现代流式传输的 MCP 服务端,并集成一个 Bilibili 视频查询工具。 + +```typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { HttpServerTransport } from "@modelcontextprotocol/sdk/server/http.js"; +import { Hono } from "hono"; +import { cors } from "hono/cors"; + +/** + * 1. 初始化 MCP 核心逻辑 + */ +const server = new McpServer({ + name: "Bilibili-Stream-Server", + version: "1.0.0", +}); + +// 注册一个示例工具:获取视频简讯 +server.tool( + "get_bili_info", + { bvid: "string" }, + async ({ bvid }) => { + // 模拟异步数据获取 + await new Promise(resolve => setTimeout(resolve, 500)); + return { + content: [{ + type: "text", + text: `视频 ${bvid} 的实时数据:点赞 1.2w, 投币 5000 (来自 Streamable HTTP 接口)` + }] + }; + } +); + +/** + * 2. 创建 Hono Web 服务 + */ +const app = new Hono(); + +// 允许跨域(如果 Claude Desktop 或 Web 客户端需要从不同域名访问) +app.use("/*", cors()); + +/** + * 3. 实现 Streamable HTTP 传输层 + * 现代规范中,我们需要处理: + * - GET: 用于建立 SSE/流式连接 + * - POST: 用于接收客户端指令 + */ +let transport: HttpServerTransport; + +// 统一入口点 /mcp +app.all("/mcp", async (c) => { + // 懒加载传输层实例,绑定到当前请求上下文 + if (!transport) { + transport = new HttpServerTransport("/mcp", c.res); + await server.connect(transport); + } + + if (c.req.method === "GET") { + // 建立流式响应 (Event Stream) + return transport.handleGetRequest(c.req.raw, c.res.raw); + } else if (c.req.method === "POST") { + // 处理客户端发来的 JSON-RPC 消息 + return transport.handlePostRequest(c.req.raw, c.res.raw); + } +}); + +export default { + port: 3000, + fetch: app.fetch, +}; + +console.log("🚀 Bilibili MCP Streamable Server running on http://localhost:3000/mcp"); + +``` + +--- + +### 3. 关键实现细节解析 + +* **`HttpServerTransport`**: 这是 SDK 提供的现代封装。它不再像旧版 `SSEServerTransport` 那样需要强制区分两个 URL(如 `/sse` 和 `/message`),你可以通过逻辑判断将它们合并在同一个路由 `/mcp` 下。 +* **会话管理 (Session)**:当你发起 `GET` 请求时,服务端会创建一个 `Mcp-Session-Id`。随后的所有 `POST` 请求都必须携带这个 ID,以便服务端知道该把结果“推”回哪个流。 +* **流式本质**:在 `handleGetRequest` 中,服务器保持连接开启(`Connection: keep-alive`),并以 `text/event-stream` 格式持续输出数据块。 + +### 4. 如何在 Claude 中测试? + +如果你想在 **Claude Desktop** 中连接这个本地流式服务器,修改你的 `claude_desktop_config.json`: + +```json +{ + "mcpServers": { + "bili-remote": { + "command": "curl", + "args": ["-N", "http://localhost:3000/mcp"] + } + } +} + +``` + +*注意:对于远程服务器,通常直接在支持 MCP 的 IDE(如 Cursor 或 Zed)中输入 URL 即可。* + +--- + +### 5. 进阶:如何处理身份验证? + +由于是 HTTP 协议,你可以轻松添加中间件来保护你的 Bilibili 接口: + +```typescript +app.use("/mcp", async (c, next) => { + const token = c.req.header("Authorization"); + if (token !== "Bearer your-secret-key") { + return c.text("Unauthorized", 401); + } + await next(); +}); + +``` + +**这份模板对你构建远程 MCP 有帮助吗?如果你需要将其部署到 Vercel 或 Cloudflare Workers,我可以为你提供特定的环境适配代码。** +#### SSE 模式 (传统) +需要定义两个路由:一个用于保持 SSE 连接,一个用于接收客户端消息。 +```TypeScript +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; +import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; +import express from "express"; + +const server = new Server({ name: "my-server", version: "1.0.0" }, { capabilities: {} }); +const app = express(); + +let transport: SSEServerTransport; + +// 1. 建立 SSE 连接通道 +app.get("/sse", async (req, res) => { + transport = new SSEServerTransport("/messages", res); + await server.connect(transport); +}); + +// 2. 接收客户端发来的消息 +app.post("/messages", async (req, res) => { + if (transport) { + await transport.handlePostMessage(req, res); + } +}); + +app.listen(3000); +``` + +#### Streamable HTTP 模式 (现代) +使用 SDK 提供的 `StreamableHTTPServer` 高层封装(常见于 2025 年后的企业级模版)。 +```TypeScript +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; +import { StreamableHTTPServer } from "@modelcontextprotocol/sdk/server/http.js"; + +const mcpServer = new Server({ name: "modern-server", version: "2.0.0" }, { capabilities: { tools: {} } }); + +// 高层封装会自动处理路由和 Session ID +const server = new StreamableHTTPServer(mcpServer); + +app.post("/mcp", async (req, res) => { + await server.handlePostRequest(req, res); +}); + +app.get("/mcp", async (req, res) => { + // 处理初始化流 + await server.handleGetRequest(req, res); +}); +``` +--- + +### 💡 部署建议 +- **本地开发**:坚持使用 `stdio`。 +- **远程 Web 服务**:请务必选择 **`streamable-http`**。 +- **Cline/Claude 桌面端配置**:在配置远程服务器时,如果对方支持新协议,配置项应为: + ```JSON + "my-remote-tool": { + "type": "streamableHttp", + "url": "https://api.yourserver.com/mcp" + } + ``` +### 详细案例 +#### 1. 项目初始化 +首先,你需要安装核心依赖: +```bash +npm install @modelcontextprotocol/sdk hono +``` + +#### 2. Streamable HTTP 服务端完整代码 +这份代码展示了如何创建一个支持现代流式传输的 MCP 服务端,并集成一个 Bilibili 视频查询工具。 +```Typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { HttpServerTransport } from "@modelcontextprotocol/sdk/server/http.js"; +import { Hono } from "hono"; +import { cors } from "hono/cors"; + +/** + * 1. 初始化 MCP 核心逻辑 + */ +const server = new McpServer({ + name: "Bilibili-Stream-Server", + version: "1.0.0", +}); + +// 注册一个示例工具:获取视频简讯 +server.tool( + "get_bili_info", + { bvid: "string" }, + async ({ bvid }) => { + // 模拟异步数据获取 + await new Promise(resolve => setTimeout(resolve, 500)); + return { + content: [{ + type: "text", + text: `视频 ${bvid} 的实时数据:点赞 1.2w, 投币 5000 (来自 Streamable HTTP 接口)` + }] + }; + } +); + +/** + * 2. 创建 Hono Web 服务 + */ +const app = new Hono(); + +// 允许跨域(如果 Claude Desktop 或 Web 客户端需要从不同域名访问) +app.use("/*", cors()); + +/** + * 3. 实现 Streamable HTTP 传输层 + * 现代规范中,我们需要处理: + * - GET: 用于建立 SSE/流式连接 + * - POST: 用于接收客户端指令 + */ +let transport: HttpServerTransport; + +// 统一入口点 /mcp +app.all("/mcp", async (c) => { + // 懒加载传输层实例,绑定到当前请求上下文 + if (!transport) { + transport = new HttpServerTransport("/mcp", c.res); + await server.connect(transport); + } + + if (c.req.method === "GET") { + // 建立流式响应 (Event Stream) + return transport.handleGetRequest(c.req.raw, c.res.raw); + } else if (c.req.method === "POST") { + // 处理客户端发来的 JSON-RPC 消息 + return transport.handlePostRequest(c.req.raw, c.res.raw); + } +}); + +export default { + port: 3000, + fetch: app.fetch, +}; + +console.log("🚀 Bilibili MCP Streamable Server running on http://localhost:3000/mcp"); +``` +--- + +### 3. 关键实现细节解析 +- **`HttpServerTransport`**: 这是 SDK 提供的现代封装。它不再像旧版 `SSEServerTransport` 那样需要强制区分两个 URL(如 `/sse` 和 `/message`),你可以通过逻辑判断将它们合并在同一个路由 `/mcp` 下。 +- **会话管理 (Session)**:当你发起 `GET` 请求时,服务端会创建一个 `Mcp-Session-Id`。随后的所有 `POST` 请求都必须携带这个 ID,以便服务端知道该把结果“推”回哪个流。 +- **流式本质**:在 `handleGetRequest` 中,服务器保持连接开启(`Connection: keep-alive`),并以 `text/event-stream` 格式持续输出数据块。 + +### 4. 如何在 Claude 中测试? +如果你想在 **Claude Desktop** 中连接这个本地流式服务器,修改你的 `claude_desktop_config.json`: +```JSON +{ + "mcpServers": { + "bili-remote": { + "command": "curl", + "args": ["-N", "http://localhost:3000/mcp"] + } + } +} +``` + + +--- + +### 5. 进阶:如何处理身份验证? +由于是 HTTP 协议,你可以轻松添加中间件来保护你的 Bilibili 接口: +```TypeScript +app.use("/mcp", async (c, next) => { + const token = c.req.header("Authorization"); + if (token !== "Bearer your-secret-key") { + return c.text("Unauthorized", 401); + } + await next(); +}); +``` + # Skill ## Npx Skill 1. npx skills find [query]:寻找Skill。 diff --git a/07-Other/AI/AI Agent/OpenClaw/OpenClaw Multi Agent Prompt.md b/07-Other/AI/AI Agent/OpenClaw/OpenClaw Multi Agent Prompt.md index 2302b1c..ed270ec 100644 --- a/07-Other/AI/AI Agent/OpenClaw/OpenClaw Multi Agent Prompt.md +++ b/07-Other/AI/AI Agent/OpenClaw/OpenClaw Multi Agent Prompt.md @@ -1,6 +1,6 @@ ## # Role -你是一个高度智能的任务调度中枢,负责管理以下六个专业 Agent:【绘图】、【编程】、【信息收集】、【AI偶像】、【快速问答】、【思考问答】。 -你使用OpenClaw的设置的默认模型,之后帮我创建这六个Agent,具体要求如下: +你是一个高度智能的任务调度中枢,负责管理以下六个专业独立Agent:【绘图】、【编程】、【信息收集】、【AI偶像】、【快速问答】、【思考问答】。 +你使用OpenClaw的设置的默认模型,之后帮我创建这六个独立的Agent,具体要求如下: ---