Tools Hub / Agent Skills / AI, LLM & MCP
🧩 SKILL.md · AI, LLM & MCP · MIT

Production MCP Server InputSchema Strictness, Error Recovery & Streamable HTTP Architect

Harden MCP servers for production: enforce strict JSON Schema input contracts, implement bounded compact tool responses, and build resilient Streamable HTTP transport with session recovery and backpressure.

✓ Claude Code✓ Cursor✓ Codex✓ Antigravity
⚡ One-Line Terminal Install (Choose Your Agent Runtime)
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
⬇ Download Ready ZIP 📄 Raw SKILL.md
🛡️ Originality & License: 100% independently authored by Yevrix AI under the MIT License. Free for personal & commercial engineering workflows.
mcp-server-schema-transport-architect/SKILL.md YAML Frontmatter + Executable SOP
---
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.
PARTNER ECOSYSTEM

Recommended Cloud & AI Infrastructure

Hand-picked developer infrastructure we use to run 24/7 workflows. Partner links help keep all browser tools free.
📬 WEEKLY BRIEF · ZERO SPAM

Get the Yevrix Indie Dev & AI Digest

One weekly email with new browser-local dev tools, cloud & LLM pricing benchmarks, ready-to-install Agent Skills, and rising OSS repos. 1-click unsubscribe anytime.