mcp-patterns
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "mcp-patterns":https://skillpi.com/zh/skills/deepskill-a056fc3cec7a8da4e5cc1ccbf496406f33128b754e41b1799d83cec5c398612f。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
用于 MCP 服务器设计的模式说明,涵盖工具模式、资源、stdio/SSE 与能力协商相关要点。触发条件包括 MCP(模型上下文协议)、JSON‑RPC、stdio、SSE 以及 Claude Desktop。
介绍来源: third_party · softspark · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: mcp-patterns
description: "MCP server design: tool schemas, resources, stdio/SSE, capability negotiation. Triggers: MCP, Model Context Protocol, JSON-RPC, stdio, SSE, Claude Desktop."
effort: medium
user-invocable: false
allowed-tools: ReadMCP Patterns Skill
MCP Specification (2025-06-18)
Core Concepts
| Concept | Description |
|---|---|
| Server | Exposes tools, resources, prompts to clients |
| Client | Connects to servers, invokes tools |
| Transport | Communication layer (stdio, HTTP, SSE) |
| Tool | Executable function with JSON Schema |
| Resource | Read-only data (files, URLs) |
| Prompt | Reusable prompt template |
Tool Definition Pattern
// TypeScript with @modelcontextprotocol/sdk
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{
name: "search_kb",
description: "Search the knowledge base",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query"
},
limit: {
type: "number",
description: "Max results",
default: 10
}
},
required: ["query"]
},
annotations: {
readOnlyHint: true, // Doesn't modify state
idempotentHint: true, // Same input = same output
openWorldHint: false // Bounded result set
}
}]
}));
Tool Annotations
| Annotation | Meaning | Use When |
|---|---|---|
readOnlyHint |
No side effects | Read operations |
destructiveHint |
Deletes/modifies data | Write operations |
idempotentHint |
Safe to retry | GET-like operations |
openWorldHint |
Results may change | External API calls |
How to Write a Tool Description
The description is the only signal the model uses to route a request. The schema constrains the call; the description decides whether the call happens at all. Treat it as a routing contract, not API prose. A good one has five parts, in this order:
- One-line purpose — what the tool does, in plain terms. Lead with a verb.
Search indexed knowledge-base documents and return ranked passages.Skip the HTTP verb and endpoint;calls GET /v2/searchtells the model nothing about intent. - WHEN TO USE — concrete trigger phrasings the user might say, not abstract categories. List the actual shapes: "find docs about X", "what does the KB say about Y", "look up the runbook for Z". Models match on surface form, so give them surface forms.
- WHEN NOT TO USE — the section that does most of the disambiguation work. Name the near-miss tools and the boundary that separates them. This is where you prevent the model from firing the wrong tool on a request that looks similar. Empty WHEN NOT TO USE = the tool is under-specified.
- CRITICAL — one line for the single non-obvious failure mode. The constraint a reader would not guess from the schema: a required ordering, an ID that must come from another call, a cost/irreversibility warning. One line, not a checklist.
- Self-test — close with a question the model can apply to itself to decide fit.
Ask: is the user looking up existing content, or asking me to create new content? This tool is read-only — if they want to create, stop.
Why negative examples outweigh positive ones
Positive triggers tell the model when a tool could apply; negative ones are what stop it firing on overlapping requests. When two tools have similar purposes (search_kb vs search_code, get_document vs list_documents), the only thing keeping the model off the wrong one is each description naming the other and drawing the line. Budget more words for the boundary than the bullseye.
Disambiguating near-miss tools
When tools overlap, make each WHEN NOT TO USE point at its neighbour and state the discriminator explicitly:
search_kb
WHEN NOT TO USE: do not use to fetch a document you already have the id for —
that is get_document. Use search_kb only when you need to discover *which*
document, by meaning or keyword.
get_document
WHEN NOT TO USE: do not use to find a document by topic or keyword — you must
already hold an exact id (from search_kb results). For discovery, use search_kb.
Worked example
name: cancel_workflow
description: |
Stop a running agent workflow and discard its in-flight results.
WHEN TO USE: the user says "cancel the workflow", "stop run abc123",
"kill that job", or asks to halt a workflow that get_workflow_status
reports as RUNNING.
WHEN NOT TO USE:
- To inspect progress without stopping — use get_workflow_status.
- To start a fresh run — use start_workflow.
- On a workflow already in a terminal state (COMPLETED/FAILED) — the call
is a no-op and signals the model misread the status.
CRITICAL: cancellation is irreversible and drops partial output. Confirm the
workflowId came from list_workflows or get_workflow_status — never type one
from memory.
Self-test: am I stopping work that is genuinely still RUNNING, or did I confuse
"check status" with "cancel"? If I have not seen a RUNNING status, do not call this.
A description that survives this rubric routes correctly without the model reading your source. One that skips WHEN NOT TO USE will misfire the moment a second, similar tool exists in the same server.
Transport Patterns
1. stdio (Default)
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
const transport = new StdioServerTransport();
await server.connect(transport);
2. HTTP with SSE
# FastAPI implementation
from fastapi import FastAPI
from sse_starlette.sse import EventSourceResponse
app = FastAPI()
@app.get("/mcp/sse")
async def sse_endpoint():
async def event_generator():
while True:
# Yield MCP events
yield {"event": "message", "data": json.dumps(response)}
return EventSourceResponse(event_generator())
@app.post("/mcp")
async def jsonrpc_endpoint(request: Request):
body = await request.json()
response = await handle_jsonrpc(body)
return JSONResponse(response)
3. Streamable HTTP (Modern)
Single /mcp endpoint handling GET (SSE) and POST (JSON-RPC):
@app.api_route("/mcp", methods=["GET", "POST"])
async def mcp_endpoint(request: Request):
if request.method == "GET":
# SSE streaming
return EventSourceResponse(stream_generator())
else:
# JSON-RPC
body = await request.json()
return JSONResponse(await handle_jsonrpc(body))
JSON-RPC 2.0 Pattern
Request Format
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "search_kb",
"arguments": {"query": "test", "limit": 5}
}
}
Response Format
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{"type": "text", "text": "Search results..."}
]
}
}
Error Format
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found"
}
}
Standard Error Codes
| Code | Meaning |
|---|---|
| -32700 | Parse error |
| -32600 | Invalid request |
| -32601 | Method not found |
| -32602 | Invalid params |
| -32603 | Internal error |
Completion Support
Enable intelligent argument suggestions:
server.setRequestHandler(CompletionCompleteRequestSchema, async (request) => {
const { argument } = request.params;
if (argument.name === "service") {
return {
completion: {
values: ["nginx", "postgresql", "redis", "qdrant"],
hasMore: false
}
};
}
return { completion: { values: [], hasMore: false } };
});
Session Management
// Generate secure session ID
const sessionId = crypto.randomUUID();
// Validate Origin header
const allowedOrigins = ["http://localhost:3000", "https://claude.ai"];
if (!allowedOrigins.includes(request.headers.origin)) {
throw new Error("Invalid origin");
}
// Session storage (don't expose to client)
const sessions = new Map<string, SessionData>();
Batching Support
Handle multiple requests in single HTTP call:
async def handle_jsonrpc(body):
if isinstance(body, list):
# Batch request
return [await process_single(req) for req in body]
else:
# Single request
return await process_single(body)
Best Practices
Security
- [ ] Validate all inputs against JSON Schema
- [ ] Validate Origin header
- [ ] Implement rate limiting
- [ ] Use environment variables for secrets
- [ ] No secrets in logs or errors
Performance
- [ ] Connection pooling
- [ ] Response caching where appropriate
- [ ] Streaming for large responses
- [ ] Batch support for efficiency
Logging
- [ ] Log to stderr (never stdout)
- [ ] Structured JSON logs
- [ ] Request/response tracing
- [ ] Error logging with context
Documentation
- [ ] Document all tools clearly
- [ ] Include example usage
- [ ] Version your API
- [ ] Maintain changelog
RAG-MCP MCP Tools
| Tool | Description |
|---|---|
smart_query |
Primary search with auto-routing |
hybrid_search_kb |
Raw vector + text search |
get_document |
Full document content |
crag_search |
Self-correcting search |
multi_hop_search |
Complex reasoning |
start_workflow |
Start agent workflow |
get_workflow_status |
Check workflow progress |
list_workflows |
List all workflows |
cancel_workflow |
Cancel workflow |
版本历史
-
v6.2.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
原版更新说明
## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0
-
v5.5.0
GitHub ↗
原版更新说明
### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0
-
v5.4.2
GitHub ↗
原版更新说明
## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- MCP 是 AI 应用开发中的核心协议,该 Skill 提供了完整的设计模式、最佳实践和代码示例
- 涵盖工具定义、传输模式、JSON-RPC、会话管理等关键主题,对开发者有极高实用价值
- 包含详细的工具描述编写指南和最佳实践,帮助用户构建高质量的 MCP 服务器
亮点
- 触发词精准完整,覆盖 MCP、Model Context Protocol、JSON-RPC、stdio、SSE、Claude Desktop 等多种变体
- 边界清晰,能够准确识别相关场景
亮点
- Phase/步骤清晰,有出口条件,含端到端示例
- frontmatter完整,单文件≤500行,结构规范良好
- 包含详细的代码示例和最佳实践清单
亮点
- 工具来源明确,参数正确,覆盖主要异常
- 不可逆操作有确认机制,安全性考虑周全
- 包含完整的错误处理和安全最佳实践
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
文档引用的域名或地址
这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。
- claude.ai
- localhost
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。