mcp-server-patterns
Build MCP servers with Node/TypeScript SDK — tools, resources, prompts, Zod validation, stdio vs Streamable HTTP. Use Context7 or official MCP docs for latest API.
About this skill
This skill provides a comprehensive collection of patterns and best practices for developing Model Context Protocol (MCP) servers using Node.js and TypeScript. It covers essential aspects like defining AI-callable tools, managing resources, structuring prompts, implementing robust data validation with Zod, and choosing between stdio and Streamable HTTP transport methods. Derived from the 'everything-claude-code' repository, it emphasizes building production-ready systems with robust API design, proper resource management, and effective error handling, ensuring seamless and reliable interaction between your server and AI assistants like Claude. It guides developers through the evolving MCP SDK API, directing them to 'Context7' or official documentation for the latest method names and signatures.
Best use case
Implementing new AI agent integrations that require server-side logic (tools, resources, prompts). Developing backend services that expose functionalities an AI agent can invoke and interact with, ensuring data validation and efficient communication for AI-driven applications.
Build MCP servers with Node/TypeScript SDK — tools, resources, prompts, Zod validation, stdio vs Streamable HTTP. Use Context7 or official MCP docs for latest API.
A well-structured, functional, and robust MCP server capable of exposing tools, resources, and prompts to AI agents, with proper data validation and efficient communication, facilitating seamless and reliable AI-driven interactions.
Practical example
Example input
I need to set up a new backend service that provides tools for an AI agent. Can you help me design and implement an MCP server using Node.js and TypeScript, including Zod validation for inputs? Focus on best practices for production readiness.
Example output
```typescript
// Example MCP Server Implementation with Zod Validation
import { createAgentServer, Tool } from '@context7/mcp';
import { z } from 'zod';
// Define a Zod schema for input validation
const userDataSchema = z.object({
userId: z.string().uuid('Invalid user ID format'),
action: z.enum(['read', 'update', 'delete']),
data: z.any().optional()
});
// Define an MCP tool
const manageUserTool: Tool = {
name: 'manageUser',
description: 'Performs management actions on a user, such as reading, updating, or deleting their profile.',
inputSchema: userDataSchema,
async call(input) {
try {
// Validate input using Zod
const validatedInput = userDataSchema.parse(input);
console.log(`Executing ${validatedInput.action} for user ${validatedInput.userId}`);
// Simulate database or API operation based on action
switch (validatedInput.action) {
case 'read':
return { status: 'success', message: `User data for ${validatedInput.userId} retrieved.`, data: { name: 'John Doe', email: 'john@example.com' } };
case 'update':
// Further logic for update
return { status: 'success', message: `User ${validatedInput.userId} updated with ${JSON.stringify(validatedInput.data)}.` };
case 'delete':
// Further logic for delete
return { status: 'success', message: `User ${validatedInput.userId} deleted.` };
default:
throw new Error(`Unsupported action: ${validatedInput.action}`);
}
} catch (error) {
console.error('Error in manageUserTool:', error);
// Return a structured error for the AI to handle
return { status: 'error', message: `Failed to manage user: ${error.message}` };
}
},
};
// Create and start the MCP server
const server = createAgentServer({ tools: [manageUserTool] });
server.listen(8080, () => {
console.log('MCP Server listening on port 8080');
console.log('Registering manageUserTool with AI agent...');
});
```
This code provides a basic MCP server in Node.js/TypeScript, demonstrating how to define a tool (`manageUserTool`) with Zod for robust input validation. It showcases handling different actions and returning structured responses, including error cases, essential for reliable AI agent integration. Remember to consult Context7 or official MCP docs for the latest SDK API specifics.When to use this skill
- When implementing a new Model Context Protocol (MCP) server for an AI assistant, adding new tools or resources for the AI to utilize, deciding on the optimal communication transport (stdio vs. HTTP streaming), upgrading your MCP SDK, or debugging issues related to MCP server registration and data transport.
When not to use this skill
- When you are primarily interacting with an AI agent as a user (rather than building its backend), developing a server that does not require MCP integration, or working on non-Node.js/TypeScript backend projects where MCP's specific patterns are not applicable.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/mcp-server-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How mcp-server-patterns Compares
| Feature / Agent | mcp-server-patterns | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Build MCP servers with Node/TypeScript SDK — tools, resources, prompts, Zod validation, stdio vs Streamable HTTP. Use Context7 or official MCP docs for latest API.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# MCP Server Patterns
The Model Context Protocol (MCP) lets AI assistants call tools, read resources, and use prompts from your server. Use this skill when building or maintaining MCP servers. The SDK API evolves; check Context7 (query-docs for "MCP") or the official MCP documentation for current method names and signatures.
## When to Use
Use when: implementing a new MCP server, adding tools or resources, choosing stdio vs HTTP, upgrading the SDK, or debugging MCP registration and transport issues.
## How It Works
### Core concepts
- **Tools**: Actions the model can invoke (e.g. search, run a command). Register with `registerTool()` or `tool()` depending on SDK version.
- **Resources**: Read-only data the model can fetch (e.g. file contents, API responses). Register with `registerResource()` or `resource()`. Handlers typically receive a `uri` argument.
- **Prompts**: Reusable, parameterised prompt templates the client can surface (e.g. in Claude Desktop). Register with `registerPrompt()` or equivalent.
- **Transport**: stdio for local clients (e.g. Claude Desktop); Streamable HTTP is preferred for remote (Cursor, cloud). Legacy HTTP/SSE is for backward compatibility.
The Node/TypeScript SDK may expose `tool()` / `resource()` or `registerTool()` / `registerResource()`; the official SDK has changed over time. Always verify against the current [MCP docs](https://modelcontextprotocol.io) or Context7.
### Connecting with stdio
For local clients, create a stdio transport and pass it to your server’s connect method. The exact API varies by SDK version (e.g. constructor vs factory). See the official MCP documentation or query Context7 for "MCP stdio server" for the current pattern.
Keep server logic (tools + resources) independent of transport so you can plug in stdio or HTTP in the entrypoint.
### Remote (Streamable HTTP)
For Cursor, cloud, or other remote clients, use **Streamable HTTP** (single MCP HTTP endpoint per current spec). Support legacy HTTP/SSE only when backward compatibility is required.
## Examples
### Install and server setup
```bash
npm install @modelcontextprotocol/sdk zod
```
```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({ name: "my-server", version: "1.0.0" });
```
Register tools and resources using the API your SDK version provides: some versions use `server.tool(name, description, schema, handler)` (positional args), others use `server.tool({ name, description, inputSchema }, handler)` or `registerTool()`. Same for resources — include a `uri` in the handler when the API provides it. Check the official MCP docs or Context7 for the current `@modelcontextprotocol/sdk` signatures to avoid copy-paste errors.
Use **Zod** (or the SDK’s preferred schema format) for input validation.
## Best Practices
- **Schema first**: Define input schemas for every tool; document parameters and return shape.
- **Errors**: Return structured errors or messages the model can interpret; avoid raw stack traces.
- **Idempotency**: Prefer idempotent tools where possible so retries are safe.
- **Rate and cost**: For tools that call external APIs, consider rate limits and cost; document in the tool description.
- **Versioning**: Pin SDK version in package.json; check release notes when upgrading.
## Official SDKs and Docs
- **JavaScript/TypeScript**: `@modelcontextprotocol/sdk` (npm). Use Context7 with library name "MCP" for current registration and transport patterns.
- **Go**: Official Go SDK on GitHub (`modelcontextprotocol/go-sdk`).
- **C#**: Official C# SDK for .NET.Related Skills
swiftui-patterns
SwiftUI 架构模式,使用 @Observable 进行状态管理,视图组合,导航,性能优化,以及现代 iOS/macOS UI 最佳实践。
perl-patterns
现代 Perl 5.36+ 的惯用法、最佳实践和约定,用于构建稳健、可维护的 Perl 应用程序。
kotlin-ktor-patterns
Ktor 服务器模式,包括路由 DSL、插件、身份验证、Koin DI、kotlinx.serialization、WebSockets 和 testApplication 测试。
kotlin-exposed-patterns
JetBrains Exposed ORM 模式,包括 DSL 查询、DAO 模式、事务、HikariCP 连接池、Flyway 迁移和仓库模式。
rust-patterns
Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.
laravel-patterns
Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.
springboot-patterns
Spring Boot architecture patterns, REST API design, layered services, data access, caching, async processing, and logging. Use for Java Spring Boot backend work.
jpa-patterns
JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.
django-patterns
Django architecture patterns, REST API design with DRF, ORM best practices, caching, signals, middleware, and production-grade Django apps.
python-patterns
Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization. Use when working with Python code to apply Pythonic patterns.
postgres-patterns
PostgreSQL database patterns for query optimization, schema design, indexing, and security. Quick reference for common patterns, index types, data types, and anti-pattern detection. Based on Supabase best practices.
golang-patterns
Go-specific design patterns and best practices including functional options, small interfaces, dependency injection, concurrency patterns, error handling, and package organization. Use when working with Go code to apply idiomatic Go patterns.