К основному содержанию
скилл CX Codex

mcp-patterns — скилл для Claude Code: что делает и как установить

Скилл mcp-patterns для Claude Code и Codex помогает проектировать серверы Model Context Protocol. Включается при настройке транспортов, авторизации через OAuth, кэшировании ресурсов и защите от инъекций.

MIT 191 установок ★ 305 обновлён 2026-11-14

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add yonatangross/orchestkit --skill mcp-patterns -a claude-code
Открыть на GitHub

Что делает mcp-patterns

Скилл передаёт агенту правила архитектуры MCP-серверов на базе спецификации 2025-11-25. Набор инструкций охватывает выбор между stdio и Streamable HTTP, жизненный цикл FastMCP, последовательную и параллельную композицию инструментов, а также подключение интерфейсов через @mcp-ui.

Все примеры на Python написаны под SDK v1, поэтому требуют фиксации зависимости mcp в диапазоне >=1.28.0,<2.0.0. В релизе 2.0 класс FastMCP в том же виде не представлен. Для TypeScript-проектов библиотека @modelcontextprotocol/sdk должна быть не ниже версии 1.31.0.

Какие задачи решает

  • выбрать транспорт между stdio и Streamable HTTP
  • настроить авторизацию по стандарту OAuth 2.1 с PKCE
  • защитить сервер MCP от инъекций промптов и подмены инструментов
  • организовать кэширование ресурсов с вытеснением по LRU

Примеры запросов агенту

  • Спроектируй MCP-сервер на TypeScript с транспортом Streamable HTTP
  • Настрой авторизацию через OAuth 2.1 с PKCE для нашего MCP-сервера
  • Проверь обработчики инструментов MCP на уязвимости к prompt injection

Как установить mcp-patterns

1Через Skills CLI (Vercel)

npx skills add yonatangross/orchestkit --skill mcp-patterns -a claude-code

2Вручную: положить файлы

~/.claude/skills/mcp-patterns/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/mcp-patterns/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о mcp-patterns

Как установить mcp-patterns в Claude Code?

Выполните команду npx skills add yonatangross/orchestkit --skill mcp-patterns -a claude-code. Файл навыка сохранится по пути ~/.claude/skills/mcp-patterns/SKILL.md.

Что делает mcp-patterns?

Предоставляет агенту инженерные правила для разработки MCP-серверов по спецификации 2025-11-25. Навык помогает настраивать сетевые транспорты, авторизацию, кэш ресурсов и проверку безопасности.

Что нужно для работы mcp-patterns?

Нужен Claude Code версии 2.1.277 или новее. Для кода на Python требуется библиотека mcp версий >=1.28.0,<2.0.0, а для TypeScript — пакет @modelcontextprotocol/sdk от версии 1.31.0.

Исходный текст

SKILL.md · MIT
---
name: mcp-patterns
license: MIT
compatibility: "Claude Code 2.1.277+."
description: MCP server building, advanced patterns, and security hardening. Use when building MCP servers, implementing tool handlers, choosing a transport, adding OAuth, wiring MCP Apps UI with @mcp-ui, hardening MCP security, or debugging MCP integrations.
user-invocable: false
effort: high
targets:
  - library: "@modelcontextprotocol/sdk"
    version: ">=1.31.0"
  # Upper bound is deliberate, not a lag. `pip install mcp` now resolves to 2.x,
  # and the 2.0 README says to keep a `<2` bound until you have migrated. Every
  # Python snippet in this skill is v1 (`from mcp.server.fastmcp import FastMCP`),
  # and FastMCP is not mentioned anywhere in the 2.0 README. Verified 2026-07-31.
  # Remove the ceiling only together with a migration of rules/*.md.
  - library: "mcp"
    version: ">=1.28.0,<2.0.0"
metadata:
  category: mcp-enhancement
  spec-version: "2025-11-25"
  version: "3.1.0"
  author: "OrchestKit"
  complexity: "high"
  tags: "mcp, server, tools, resources, security, prompt-injection, oauth, elicitation, sampling, mcp-apps, fastmcp"
allowed-tools: "Read Glob Grep WebFetch WebSearch"
paths:
  - ".mcp.json"
  - "**/*.mcp.json"
---

# MCP Patterns

Patterns for building, composing, and securing Model Context Protocol servers. Based on the **2025-11-25 specification** — the latest stable release maintained by the [Agentic AI Foundation](https://agenticaifoundation.org/) (Linux Foundation), co-founded by Anthropic, Block, and OpenAI.

> **Scaffolding a new server?** Use Anthropic's `mcp-builder` skill (from the `anthropics/skills` marketplace: `/plugin marketplace add anthropics/skills`) for project setup and evaluation creation. This skill focuses on **patterns, security, and advanced features** after initial setup.
>
> **Deploying to Cloudflare?** See the `building-mcp-server-on-cloudflare` skill for Workers-specific deployment patterns.

> **Pin `mcp<2` until you migrate.** Every Python snippet in this skill targets the v1 SDK
> (`from mcp.server.fastmcp import FastMCP`). The Python SDK released **2.0.0**, `pip install mcp`
> now resolves to it, and upstream's own README says to keep a `<2` upper bound on your requirement
> until you have migrated. `FastMCP` does not appear anywhere in the 2.0 README, so treat these
> snippets as v1-only rather than assuming they still apply. v1.x continues to receive critical bug
> and security fixes on its own branch. Verified 2026-07-31.
> Migration guide: https://py.sdk.modelcontextprotocol.io/migration/

## Decision Tree — Which Rule to Read

```
What are you building?
│
├── New MCP server
│   ├── Setup & primitives ──────► rules/server-setup.md
│   ├── Transport selection ─────► rules/server-transport.md
│   └── Scaffolding ─────────────► mcp-builder skill (anthropics/skills)
│
├── Authentication & authorization
│   └── OAuth 2.1 + OIDC ───────► rules/auth-oauth21.md
│
├── Advanced server features
│   ├── Tool composition ────────► rules/advanced-composition.md
│   ├── Resource caching ────────► rules/advanced-resources.md
│   ├── Elicitation (user input) ► rules/elicitation.md
│   ├── Sampling (agent loops) ──► rules/sampling-tools.md
│   └── Interactive UI ──────────► rules/apps-ui.md
│
├── Client-side consumption
│   └── Connecting to servers ───► rules/client-patterns.md
│
├── Security hardening
│   ├── Prompt injection defense ► rules/security-injection.md
│   └── Zero-trust & verification ► rules/security-hardening.md
│
├── Testing & debugging
│   └── Inspector + unit tests ──► rules/testing-debugging.md
│
├── Discovery & ecosystem
│   └── Registries & catalogs ──► rules/registry-discovery.md
│
└── Browser-native tools
    └── WebMCP (W3C) ───────────► rules/webmcp-browser.md
```

## Quick Reference

| Category | Rule | Impact | Key Pattern |
|----------|------|--------|-------------|
| **Server** | `server-setup.md` | HIGH | FastMCP lifespan, Tool/Resource/Prompt primitives |
| **Server** | `server-transport.md` | HIGH | stdio for CLI, Streamable HTTP for production |
| **Auth** | `auth-oauth21.md` | HIGH | PKCE, RFC 8707 resource indicators, token validation |
| **Advanced** | `advanced-composition.md` | MEDIUM | Pipeline, parallel, and branching tool composition |
| **Advanced** | `advanced-resources.md` | MEDIUM | Resource caching with TTL, LRU eviction, lifecycle |
| **Advanced** | `elicitation.md` | MEDIUM | Server-initiated structured input from users |
| **Advanced** | `sampling-tools.md` | MEDIUM | Server-side agent loops with tool calling |
| **Advanced** | `apps-ui.md` | MEDIUM | Interactive UI via MCP Apps + @mcp-ui/* SDK |
| **Client** | `client-patterns.md` | MEDIUM | TypeScript/Python MCP client connection patterns |
| **Security** | `security-injection.md` | HIGH | Description sanitization, encoding normalization |
| **Security** | `security-hardening.md` | HIGH | Zero-trust allowlist, hash verification, rug pull detection |
| **Quality** | `testing-debugging.md` | MEDIUM | MCP Inspector, unit tests, transport debugging |
| **Ecosystem** | `registry-discovery.md` | LOW | Official registry API, server metadata |
| **Ecosystem** | `webmcp-browser.md` | LOW | W3C browser-native agent tools (complementary) |

**Total: 14 rules across 6 categories**

## Key Decisions

| Decision | Recommendation |
|----------|----------------|
| Transport | stdio for CLI/Desktop, Streamable HTTP for production (SSE deprecated) |
| Language | TypeScript for production (better SDK support, type safety) |
| Auth | OAuth 2.1 with PKCE (S256) + RFC 8707 resource indicators |
| Server lifecycle | Always use FastMCP lifespan for resource management |
| Error handling | Return errors as text content (Claude can interpret and retry) |
| Tool composition | Pipeline for sequential, `asyncio.gather` for parallel |
| Resource caching | TTL + LRU eviction with memory cap |
| Tool trust model | Zero-trust: explicit allowlist + hash verification |
| User input | Elicitation for runtime input; never request PII via elicitation |
| Interactive UI | MCP Apps with @mcp-ui/* SDK; sandbox all iframes |
| Token handling | Never pass through client tokens to downstream services |
| Large results | Use `_meta["anthropic/maxResultSizeChars"]` annotation (up to 500K) for results that lose meaning when truncated (CC 2.1.91) |

## Spec & Governance

- **Protocol**: Model Context Protocol, spec version **2025-11-25** (latest stable)
- **Governance**: Agentic AI Foundation (Linux Foundation, Dec 2025)
- **Platinum members**: AWS, Anthropic, Block, Bloomberg, Cloudflare, Google, Microsoft, OpenAI
- **Adoption**: 10,000+ servers; Claude, Cursor, Copilot, Gemini, ChatGPT, VS Code
- **Spec URL**: https://modelcontextprotocol.io/specification/2025-11-25
- **2026 model**: Working Groups and Interest Groups are now the primary vehicle for protocol evolution (no more milestone-based releases). Enterprise readiness lands as extensions, not core spec changes.

### Feature Maturity

| Feature | Spec Version | Status |
|---------|-------------|--------|
| Tools, Resources, Prompts | 2024-11-05 | Stable |
| Streamable HTTP transport | 2025-03-26 | Stable (replaces SSE) |
| OAuth 2.1 + Elicitation (form) | 2025-06-18 | Stable |
| Sampling with tool calling | 2025-11-25 | Stable |
| Elicitation URL mode | 2025-11-25 | Stable |
| MCP Apps (UI extension) | 2026-01-26 | Extension (ext-apps) |
| WebMCP (browser-native) | 2026-02-14 | W3C Community Draft |

## SDK landscape (2026-Q2)

| Package | What it is | When to use |
|---------|-----------|-------------|
| `mcp` (PyPI) **>=1.27** | Official Python SDK — includes the `FastMCP` helper, transport adapters, Inspector | New Python servers. This is the canonical package. |
| `@modelcontextprotocol/sdk` (npm) **>=1.29** | Official TypeScript SDK | New TS servers |
| `fastmcp` (PyPI) | Standalone fork by jlowin — predates `mcp`; API-compatible but diverges on lifespan and middleware | Existing projects pinned to it. New projects should prefer `mcp`. |

> The `fastmcp` fork and the `mcp.server.fastmcp` module are *not the same package*. Imports and `pyproject.toml` entries must agree or stacktraces become cryptic.

### Debugging with Claude Code

Pass `--mcp-debug` to Claude Code when troubleshooting server wiring — it surfaces the raw JSON-RPC frames, handshake failures, and tool-registration events that the default logger swallows:

```bash
claude --mcp-debug "query the local test server"
# or per-session:
export CLAUDE_MCP_DEBUG=1
```

Use alongside the MCP Inspector (`npx @modelcontextprotocol/inspector <cmd>`) — Inspector gives you the client-side frame view, `--mcp-debug` gives you what Claude actually saw.

> **CC 2.1.128 — reconnect tool summarization**: when a server reconnects mid-session, re-announced tools are summarized as `mcp__<server>__* (N tools re-registered)` instead of being enumerated line-by-line. Use the **initial connect** event as the source of truth for tool inventory; treat reconnect summaries as deltas only. See `references/mcp-audit-runbook.md` for grep recipes that work across both formats.

> **CC 2.1.133 — MCP OAuth honors HTTP(S)_PROXY / NO_PROXY / mTLS**: the full MCP OAuth flow (discovery, dynamic client registration, token exchange, token refresh) now respects standard proxy and client-certificate env vars end-to-end. Enterprise deployments behind corporate proxies no longer need OAuth-specific workarounds — the same `HTTPS_PROXY` / `NO_PROXY` / `NODE_EXTRA_CA_CERTS` config that already routes MCP transport now also routes auth. See `configure/references/cc-version-settings.md` (CC 2.1.133 section) for the env-var example. The companion deployment skill `building-mcp-server-on-cloudflare` can drop any prior "proxy-aware OAuth requires manual handling" caveat at this floor.

> **CC 2.1.169 — managed MCP policies enforced everywhere:** enterprise `allowedMcpServers`/`deniedMcpServers` now apply on reconnect, IDE-typed configs, `--mcp-config` servers in the first session after install, and before remote settings load (previously all four paths skipped enforcement). Orgs without remote settings also get faster cold starts. If a previously-working server stops connecting after 2.1.169, check the managed policy before debugging the server.

> **CC 2.1.163 — stdio servers get `CLAUDE_CODE_SESSION_ID`:** on `--resume`, stdio MCP servers now receive the same `CLAUDE_CODE_SESSION_ID` env var that hooks and Bash already get. Read it inside the server to correlate logs/telemetry across resumed sessions instead of minting your own session key — but never store auth tokens keyed off it (see Common Mistake #7).

## Example

```python
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("my-server")

@mcp.tool()
async def search(query: str) -> str:
    """Search documents. Returns matching results."""
    results = await db.search(query)
    return "\n".join(r.title for r in results[:10])
```

## Common Mistakes

1. No lifecycle management (connection/resource leaks on shutdown)
2. Missing input validation on tool arguments
3. Returning secrets in tool output (API keys, credentials)
   - CC 2.1.161 mitigates this at the CLI layer: `claude mcp list/get/add` no longer expands `${VAR}` references and redacts credential headers and URL secrets in terminal output — but server code must still never return secrets in tool *results*. `/mcp` also collapses never-signed-in connectors behind a "Show unused connectors" row.
   - CC 2.1.186 adds `claude mcp login <name>` / `claude mcp logout <name>` for OAuth-backed servers (HTTP/SSE/connector). Pass `--no-browser` to print the authorization URL instead of opening a browser — the supported path for SSH/headless/remote sessions (paste the redirect URL back when prompted), so interactive-only auth never blocks automated setup.
4. Unbounded response sizes without `_meta` annotation — use `_meta["anthropic/maxResultSizeChars"]` to declare intentionally large results (DB schemas, API specs) so clients/hooks don't truncate them
5. Trusting tool descriptions without sanitization (injection risk)
6. No hash verification on tool invocations (rug pull vulnerability)
7. Storing auth tokens in session IDs (credential leak)
8. Blocking synchronous code in async server (use `asyncio.to_thread()`)
9. Using SSE transport instead of Streamable HTTP (deprecated since March 2025)
10. Passing through client tokens to downstream services (confused deputy)

## Ecosystem

| Resource | What For |
|----------|----------|
| `mcp-builder` skill (anthropics/skills) | Scaffold new MCP servers + create evals |
| `building-mcp-server-on-cloudflare` skill | Deploy MCP servers on Cloudflare Workers |
| `@mcp-ui/*` packages (npm) | Implement MCP Apps UI standard |
| MCP Registry | Discover servers: https://registry.modelcontextprotocol.io/ |
| MCP Inspector | Debug and test servers interactively |

## Related Skills

- `ork-extras:llm-integration` — LLM function calling patterns
- `ork:security-patterns` — General input sanitization and layered security
- `ork:api-design` — REST/GraphQL API design patterns

© OrchestKit · MIT · yonatangross/orchestkit

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
claude-sdk-integration-patterns manutej Скилл claude-sdk-integration-patterns для Claude Code содержит паттерны интеграции Claude API и TypeScript SDK. Агент применяет их для стриминга, вызова функций и обработки ошибок в приложениях. CX Codex +1 437установок go-mcp-server-generator официальный github Скилл go-mcp-server-generator генерирует готовый проект MCP-сервера на Go с официальным SDK, типизированными инструментами, тестами и документацией. CX Codex +1 9 200установок swift-mcp-server-generator официальный github Скилл swift-mcp-server-generator для GitHub Copilot создаёт проект MCP-сервера на Swift с официальным Swift SDK. Разносит сервер по файлам и добавляет инструменты. CX Codex +1 8 800установок appwrite-typescript appwrite Добавляет знание Appwrite TypeScript SDK. CX Codex +1 2 200установок zapier-sdk zapier Скилл zapier-sdk подключает скрипты к 9,000+ сторонним сервисам через OAuth Zapier. Помогает писать интеграции без возни с отдельными API и ключами каждого сервиса. CX Codex +1 1 100установок mcp-server-architect davila7 Субагент mcp-server-architect для Claude Code проектирует MCP-серверы и помогает реализовать их транспорт и инструменты. Подключается к задачам по архитектуре и соблюдению протокола. CX Codex 1 649установок

Из того же набора86

Весь набор →
configure Интерактивный мастер для настройки OrchestKit: подключение MCP-серверов, права хуков, горячие клавиши, пресеты. Запускается при первой установке плагина и по команде /orchestkit:configure. CX Codex +1 196установок async-jobs Скилл async-jobs для Claude Code содержит правила и шаблоны для настройки очередей задач, повторов и воркфлоу в Celery, ARQ, Redis и Temporal. CX Codex +1 195установок product-frameworks Скилл product-frameworks для Claude Code даёт фреймворки для финансового анализа, приоритизации, метрик и исследований. С его помощью оформляют бизнес-кейсы, PRD и планы пользовательских исследований. CX Codex +1 194установок golden-dataset Скилл golden-dataset для Claude Code описывает жизненный цикл эталонных датасетов: курацию, девятифазное добавление, регрессионные тесты и интеграцию с Langfuse. CX Codex +1 193установок browser-tools Скилл browser-tools для Claude Code добавляет правила безопасности при автоматизации браузера через agent-browser: этику скрейпинга, паузы, обработку локальных URL и аутентификацию. Включается автоматически при такой работе. CX Codex +1 191установок scope-appropriate-architecture Скилл scope-appropriate-architecture определяет уровень проекта из шести и выбирает паттерны под его задачи, чтобы не строить микросервисы для MVP. Срабатывает в начале проектирования и при проверке сложности. CX Codex +1 179установок storybook-mcp-integration Скилл storybook-mcp-integration для Claude Code подключает инструменты Storybook MCP к работе с существующими компонентами. Агент ищет компоненты и их документацию, открывает предпросмотры и запускает тесты историй. CX Codex +1 166установок help Скилл help ищет установленный набор OrchestKit и показывает навыки по категориям. Запускается для выбора workflow или подходящего скилла. CX Codex +1 166установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой