🧩 SKILL.md · 大模型与 MCP 开发 · MIT
生产级 MCP Server 契约设计、紧凑返回节流与异常自恢复构建
为生产环境加固 MCP Server:强制严格的 JSON Schema 输入契约,实现有界紧凑的工具返回,并构建具备会话恢复与背压能力的弹性 Streamable HTTP 传输。
✓ Claude Code✓ Cursor✓ Codex✓ Antigravity
⚡ 选择你的 AI 编程工具 · 一行终端命令直接安装
mkdir -p ~/.claude/skills/mcp-server-schema-transport-architect && curl -fsSL https://ai.yevrix.com/skills/mcp-server-schema-transport-architect/SKILL.md -o ~/.claude/skills/mcp-server-schema-transport-architect/SKILL.md
🛡️ 版权与原创声明:本技能规范由 Yevrix AI 独立原创编写,遵循 MIT 开源协议发布,您可免费用于个人或商业研发团队并自由二次修改。
---
name: mcp-server-schema-transport-architect
description: Enforce strict MCP tool input schemas, compact bounded responses, and resilient Streamable HTTP transport with session recovery and backpressure. Use when hardening an MCP server for production traffic.
---
# Production MCP Server InputSchema Strictness, Error Recovery & Streamable HTTP Architect
## When to Trigger
- Your MCP server accepts tool calls but clients send malformed or extra fields that silently corrupt state.
- Tool responses exceed client context windows or stall on large payloads.
- Streamable HTTP sessions drop mid-stream, leak memory, or fail to resume after network blips.
- You need deterministic error codes (`-32602` invalid params, `-32603` internal) instead of opaque 500s.
- You are moving from stdio to HTTP transport and need session IDs, SSE resumability, and backpressure.
## Step 1 — Audit the current tool contract surface
Inventory every tool and its `inputSchema`. Find permissive schemas (`additionalProperties` unset, missing `required`, `type: object` without properties).
```bash
# List tool definitions from a running server (Streamable HTTP)
curl -sS -X POST http://localhost:3000/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq '.result.tools[] | {name, inputSchema}'
# Grep source for loose schemas
rg -n 'inputSchema|additionalProperties|z\.object|z\.any' src/ --glob '!node_modules'
```
Record: tools with no `required`, tools accepting `z.any()`, tools returning unbounded arrays, and any handler that catches all errors and returns `{ ok: false }`.
## Step 2 — Enforce strict input schemas
Use Zod (TS) or Pydantic (Py) with `.strict()` / `extra="forbid"`, explicit `required`, and bounded primitives. Reject unknown keys at the boundary, not deep in handlers.
```ts
// tools/search.ts — strict contract
import { z } from 'zod';
export const SearchInput = z.object({
query: z.string().min(1).max(512),
limit: z.number().int().min(1).max(50).default(10),
cursor: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),
}).strict(); // rejects unknown keys
export const searchTool = {
name: 'search',
description: 'Full-text search. Returns at most `limit` hits.',
inputSchema: {
type: 'object',
additionalProperties: false,
required: ['query'],
properties: {
query: { type: 'string', minLength: 1, maxLength: 512 },
limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
cursor: { type: 'string', pattern: '^[A-Za-z0-9_-]{1,128}$' },
},
},
};
```
```python
# tools/search.py — Pydantic strict
from pydantic import BaseModel, Field, ConfigDict
class SearchInput(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
query: str = Field(min_length=1, max_length=512)
limit: int = Field(default=10, ge=1, le=50)
cursor: str | None = Field(default=None, pattern=r"^[A-Za-z0-9_-]{1,128}$")
```
Validate before dispatch and map failures to JSON-RPC `-32602` with a machine-readable `data.errors` array (path + message). Never echo raw stack traces.
## Step 3 — Bound and compact tool responses
Cap every response by item count and byte size. Prefer compact JSON (no pretty-print), strip nulls, and paginate with opaque cursors.
```ts
const MAX_BYTES = 64 * 1024;
const MAX_ITEMS = 50;
function compact(payload: unknown): string {
const s = JSON.stringify(payload, (k, v) => (v === null || v === undefined ? undefined : v));
if (Buffer.byteLength(s) > MAX_BYTES) {
throw new McpError(-32603, 'response_too_large', { maxBytes: MAX_BYTES });
}
return s;
}
async function handleSearch(input: z.infer<typeof SearchInput>) {
const rows = await db.search(input.query, input.limit + 1, input.cursor);
const hasMore = rows.length > input.limit;
const items = rows.slice(0, input.limit);
return {
content: [{ type: 'text', text: compact({ items, nextCursor: hasMore ? items.at(-1)!.id : null }) }],
isError: false,
};
}
```
For streaming tools, emit `notifications/progress` with `progressToken` and throttle to ≤10 updates/sec; drop intermediate frames rather than buffering unboundedly.
## Step 4 — Resilient Streamable HTTP transport
Implement session IDs via `Mcp-Session-Id` header, SSE resumability via `Last-Event-ID`, and per-session backpressure. Reject new streams when a session exceeds concurrency limits.
```ts
// transport.ts (Express-style pseudocode, real headers)
app.post('/mcp', async (req, res) => {
const sessionId = req.header('Mcp-Session-Id');
const accept = req.header('Accept') ?? '';
if (!accept.includes('application/json') && !accept.includes('text/event-stream')) {
return res.status(406).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Accept must include application/json or text/event-stream' }, id: null });
}
const session = sessionId ? sessions.get(sessionId) : sessions.create();
if (!session) return res.status(404).json({ jsonrpc: '2.0', error: { code: -32001, message: 'session_not_found' }, id: null });
if (session.inflight >= session.maxInflight) {
return res.status(429).set('Retry-After', '1').json({ jsonrpc: '2.0', error: { code: -32002, message: 'backpressure' }, id: null });
}
res.set('Mcp-Session-Id', session.id);
// ... dispatch, write SSE frames with id: <eventId>
});
```
On client reconnect with `Last-Event-ID`, replay from a bounded ring buffer (e.g. last 256 events per session); if the ID is evicted, respond `-32003 event_gone` so the client re-initializes. Expire idle sessions after 5 minutes with a `setInterval` sweeper, and clear timers on `session.close()`.
## High-Risk Anti-Patterns (Bad vs Good)
**Permissive schema**
```ts
// BAD: accepts anything, silently drops unknown keys
const Input = z.object({ query: z.string() });
// GOOD: strict, bounded, explicit
const Input = z.object({ query: z.string().min(1).max(512) }).strict();
```
**Unbounded response**
```ts
// BAD: returns entire table
return { content: [{ type: 'text', text: JSON.stringify(await db.all()) }] };
// GOOD: capped + cursor
return { content: [{ type: 'text', text: compact({ items, nextCursor }) }] };
```
**Swallowed errors**
```ts
// BAD: hides root cause, breaks client retry logic
try { return await handler(args); } catch { return { isError: true }; }
// GOOD: typed JSON-RPC error with code + data
try { return await handler(args); }
catch (e) {
if (e instanceof z.ZodError) throw new McpError(-32602, 'invalid_params', { errors: e.issues });
throw new McpError(-32603, 'internal_error', { requestId: ctx.id });
}
```
**Session leak**
```ts
// BAD: sessions map grows forever
sessions.set(id, session);
// GOOD: TTL + sweeper
sessions.set(id, session);
sweeper = setInterval(() => { for (const [k, s] of sessions) if (Date.now() - s.lastSeen > 300_000) { s.close(); sessions.delete(k); } }, 60_000);
```
## Verification Gate Checklist
- [ ] Every tool has `additionalProperties: false` and explicit `required`.
- [ ] Invalid input returns JSON-RPC `-32602` with `data.errors` (path + message), no stack traces.
- [ ] All tool responses ≤ configured byte cap; large result sets paginate via cursor.
- [ ] Progress notifications throttled; no unbounded buffering.
- [ ] `Mcp-Session-Id` issued on initialize; unknown session returns `-32001`.
- [ ] `Last-Event-ID` replay works; evicted events return `-32003`.
- [ ] Backpressure returns `429` with `Retry-After` when inflight limit hit.
- [ ] Idle sessions swept; timers cleared on close (verify with `process._getActiveHandles()` in tests).
- [ ] `curl` smoke test passes for `tools/list`, `tools/call`, and reconnect flow.
- [ ] Load test (e.g. `k6 run --vus 50 --duration 30s`) shows no memory growth and stable p95 latency.
开发者生态推荐
推荐云主机与 AI 算力基础设施
精选适合部署独立站、自动化脚本与大模型工作流的云底座;通过推广链接注册不增加任何费用,同时支持本站永久免费。
📬 每周精选 · 零垃圾邮件
订阅 Yevrix 独立开发者周刊
每周一封邮件:最新上线免费本地工具、云主机/AI API 实测对比、原创 Agent Skill 与 GitHub 飙升项目精选,随时一键退订。