MCP Builder
AnthropicOfficialPublished by Anthropic
- Skill
- Tool integration
- Software development
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
mcp-builder provides a structured, four-phase workflow for developing robust MCP servers. It covers the entire lifecycle from initial research and planning to implementation, testing, and the creation of standardized evaluations. The guide emphasizes best practices for tool design, schema definition using Zod or Pydantic, and proper error handling to ensure LLMs can effectively interact with external APIs.
What it does
- Outlines a four-phase development process for MCP servers.
- Provides guidance on selecting between TypeScript (v2) and Python SDKs.
- Details best practices for tool naming, discoverability, and context management.
- Explains how to implement structured tool inputs and outputs.
- Includes instructions for testing servers with the MCP Inspector.
- Defines a standardized XML format for creating LLM-based evaluations.
When to use it
- When you need to build a new MCP server to connect an external API to an LLM.
- When you are unsure whether to use the TypeScript or Python SDK for your project.
- When you need to migrate an existing MCP server from v1 to v2.
- When you need to create a test suite to verify your MCP server's performance.
Advantages
- Promotes consistent, high-quality tool design across different languages.
- Provides clear migration paths for existing SDK versions.
- Encourages the creation of verifiable, complex evaluation scenarios.
- Focuses on actionable error messages to improve agent reliability.
Usage examples
- “How do I start building a new MCP server in TypeScript?”
- The agent will guide you through setting up a project using the v2 TypeScript SDK, including project structure and tool registration patterns.
- “What are the best practices for naming tools in an MCP server?”
- The agent will explain the importance of descriptive, action-oriented names and consistent prefixes like github_create_issue.
- “How can I verify that my MCP server is working correctly?”
- The agent will provide instructions on using the MCP Inspector and creating a 10-question evaluation suite in the required XML format.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/anthropics/mcp-builder/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip mcp-builder.zip -d .agents/skills
Documentation by Anthropic
MCP Server Development Guide
Overview
Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks.
Process
🚀 High-Level Workflow
Creating a high-quality MCP server involves four main phases:
Phase 1: Deep Research and Planning
1.1 Understand Modern MCP Design
API Coverage vs. Workflow Tools: Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage.
Tool Naming and Discoverability:
Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., github_create_issue, github_list_repos) and action-oriented naming.
Context Management: Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently.
Actionable Error Messages: Error messages should guide agents toward solutions with specific suggestions and next steps.
1.2 Study MCP Protocol Documentation
Navigate the MCP specification:
Start with the sitemap to find relevant pages: https://modelcontextprotocol.io/sitemap.xml
Then fetch specific pages with .md suffix for markdown format (e.g., https://modelcontextprotocol.io/specification/draft.md).
Key pages to review:
Specification overview and architecture
Transport mechanisms (streamable HTTP, stdio)
Tool, resource, and prompt definitions
1.3 Study Framework Documentation
Recommended stack:
Language: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools)
Transport: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers.
Load framework documentation:
MCP Best Practices: 📋 View Best Practices - Core guidelines
For TypeScript (recommended):
The TypeScript SDK has two major versions. Pick one before writing code:
v2 (
@modelcontextprotocol/server): the current stable release. Use it for new servers.v1 (
@modelcontextprotocol/sdk): receives bug and security fixes only. Use it only when the project'spackage.jsonalready depends on@modelcontextprotocol/sdk, or migrate that project withnpx @modelcontextprotocol/codemod@latest v1-to-v2 .
If the project already uses v1, tell the user once, in a sentence or two, that v2 (@modelcontextprotocol/server) is the current stable release, that v1 receives only bug and security fixes, and that npx @modelcontextprotocol/codemod@latest v1-to-v2 . migrates the project. Then continue with v1 unless the user asks to migrate.
Don't mix the two in one project: v1 code samples (imports from @modelcontextprotocol/sdk/...) don't apply to v2.
TypeScript SDK (v2): Use WebFetch to load
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md; the full docs index ishttps://ts.sdk.modelcontextprotocol.io/v2/llms.txt⚡ TypeScript Guide (v2) - TypeScript patterns and examples
For v1 projects only:
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/v1.x/README.mdand the TypeScript Guide (v1)
For Python:
Python SDK: Use WebFetch to load
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md🐍 Python Guide - Python patterns and examples
1.4 Plan Your Implementation
Understand the API: Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.
Tool Selection: Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.
Phase 2: Implementation
2.1 Set Up Project Structure
See language-specific guides for project setup:
⚡ TypeScript Guide (v2) - Project structure, package.json, tsconfig.json (v1 for existing v1 projects)
🐍 Python Guide - Module organization, dependencies
2.2 Implement Core Infrastructure
Create shared utilities:
API client with authentication
Error handling helpers
Response formatting (JSON/Markdown)
Pagination support
2.3 Implement Tools
For each tool:
Input Schema:
Use Zod (TypeScript) or Pydantic (Python)
Include constraints and clear descriptions
Add examples in field descriptions
Output Schema:
Define
outputSchemawhere possible for structured dataUse
structuredContentin tool responses (TypeScript SDK feature)Helps clients understand and process tool outputs
Tool Description:
Concise summary of functionality
Parameter descriptions
Return type schema
Implementation:
Async/await for I/O operations
Proper error handling with actionable messages
Support pagination where applicable
Return both text content and structured data when using modern SDKs
Annotations:
readOnlyHint: true/falsedestructiveHint: true/falseidempotentHint: true/falseopenWorldHint: true/false
Phase 3: Review and Test
3.1 Code Quality
Review for:
No duplicated code (DRY principle)
Consistent error handling
Full type coverage
Clear tool descriptions
3.2 Build and Test
TypeScript:
Run
npm run buildto verify compilationv2 projects: run the self-check script from the v2 guide against the built server
Test with MCP Inspector:
npx @modelcontextprotocol/inspector
Python:
Verify syntax:
python -m py_compile your_server.pyTest with MCP Inspector
See language-specific guides for detailed testing approaches and quality checklists.
Phase 4: Create Evaluations
After implementing your MCP server, create comprehensive evaluations to test its effectiveness.
Load ✅ Evaluation Guide for complete evaluation guidelines.
4.1 Understand Evaluation Purpose
Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
4.2 Create 10 Evaluation Questions
To create effective evaluations, follow the process outlined in the evaluation guide:
Tool Inspection: List available tools and understand their capabilities
Content Exploration: Use READ-ONLY operations to explore available data
Question Generation: Create 10 complex, realistic questions
Answer Verification: Solve each question yourself to verify answers
4.3 Evaluation Requirements
Ensure each question is:
Independent: Not dependent on other questions
Read-only: Only non-destructive operations required
Complex: Requiring multiple tool calls and deep exploration
Realistic: Based on real use cases humans would care about
Verifiable: Single, clear answer that can be verified by string comparison
Stable: Answer won't change over time
4.4 Output Format
Create an XML file with this structure:
<evaluation>
<qa_pair>
<question>Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?</question>
<answer>3</answer>
</qa_pair>
<!-- More qa_pairs... -->
</evaluation>Reference Files
📚 Documentation Library
Load these resources as needed during development:
Core MCP Documentation (Load First)
MCP Protocol: Start with sitemap at
https://modelcontextprotocol.io/sitemap.xml, then fetch specific pages with.mdsuffix📋 MCP Best Practices - Universal MCP guidelines including:
Server and tool naming conventions
Response format guidelines (JSON vs Markdown)
Pagination best practices
Transport selection (streamable HTTP vs stdio)
Security and error handling standards
SDK Documentation (Load During Phase 1/2)
Python SDK: Fetch from
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.mdTypeScript SDK (v2): Fetch from
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md; full docs index athttps://ts.sdk.modelcontextprotocol.io/v2/llms.txtTypeScript SDK (v1, existing v1 projects only): Fetch from
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/v1.x/README.md
Language-Specific Implementation Guides (Load During Phase 2)
🐍 Python Implementation Guide - Complete Python/FastMCP guide with:
Server initialization patterns
Pydantic model examples
Tool registration with
@mcp.toolComplete working examples
Quality checklist
⚡ TypeScript Implementation Guide (SDK v2) - Complete TypeScript guide for
@modelcontextprotocol/serverwith:Project setup and the server factory
Tool design: Zod 4 schemas, output formats, pagination, errors
A complete example serving stdio and Streamable HTTP, plus bearer auth
Resources, prompts, and notifications
A self-check script to verify the built server
Links to SDK examples for advanced features
A v1 → v2 translation table, migration steps, and a quality checklist
⚡ TypeScript Implementation Guide (SDK v1) - The equivalent guide for existing
@modelcontextprotocol/sdkprojects
Evaluation Guide (Load During Phase 4)
✅ Evaluation Guide - Complete evaluation creation guide with:
Question creation guidelines
Answer verification strategies
XML format specifications
Example questions and answers
Running an evaluation with the provided scripts
Files
- ATTRIBUTION.mdAdded by AutoGineer865 B
- LICENSE.txt11.1 KiB
- SKILL.md10.9 KiB
- reference/evaluation.md21.2 KiB
- reference/mcp_best_practices.md7.2 KiB
- reference/node_mcp_server.md28.1 KiB
- reference/node_mcp_server_v2.md34.3 KiB
- reference/python_mcp_server.md24.5 KiB
- scripts/connections.pyScript4.8 KiB
- scripts/evaluation.pyScript12.3 KiB
- scripts/example_evaluation.xml1.2 KiB
- scripts/requirements.txt29 B
reference/node_mcp_server.md
Node/TypeScript MCP Server Implementation Guide
This guide covers v1 of the TypeScript SDK (
@modelcontextprotocol/sdk). Use it only for projects that already depend on v1. For new servers, use the v2 guide.
Overview
This document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples.
Quick Reference
Key Imports
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import express from "express";
import { z } from "zod";Server Initialization
const server = new McpServer({
name: "service-mcp-server",
version: "1.0.0"
});Tool Registration Pattern
server.registerTool(
"tool_name",
{
title: "Tool Display Name",
description: "What the tool does",
inputSchema: { param: z.string() },
outputSchema: { result: z.string() }
},
async ({ param }) => {
const output = { result: `Processed: ${param}` };
return {
content: [{ type: "text", text: JSON.stringify(output) }],
structuredContent: output // Modern pattern for structured data
};
}
);MCP TypeScript SDK
The official MCP TypeScript SDK provides:
McpServerclass for server initializationregisterToolmethod for tool registrationZod schema integration for runtime input validation
Type-safe tool handler implementations
IMPORTANT - Use Modern APIs Only:
DO use:
server.registerTool(),server.registerResource(),server.registerPrompt()DO NOT use: Old deprecated APIs such as
server.tool(),server.setRequestHandler(ListToolsRequestSchema, ...), or manual handler registrationThe
register*methods provide better type safety, automatic schema handling, and are the recommended approach
See the MCP SDK documentation in the references for complete details.
Server Naming Convention
Node/TypeScript MCP servers must follow this naming pattern:
Format:
{service}-mcp-server(lowercase with hyphens)Examples:
github-mcp-server,jira-mcp-server,stripe-mcp-server
The name should be:
General (not tied to specific features)
Descriptive of the service/API being integrated
Easy to infer from the task description
Without version numbers or dates
Project Structure
Create the following structure for Node/TypeScript MCP servers:
{service}-mcp-server/
├── package.json
├── tsconfig.json
├── README.md
├── src/
│ ├── index.ts # Main entry point with McpServer initialization
│ ├── types.ts # TypeScript type definitions and interfaces
│ ├── tools/ # Tool implementations (one file per domain)
│ ├── services/ # API clients and shared utilities
│ ├── schemas/ # Zod validation schemas
│ └── constants.ts # Shared constants (API_URL, CHARACTER_LIMIT, etc.)
└── dist/ # Built JavaScript files (entry point: dist/index.js)Tool Implementation
Tool Naming
Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names.
Avoid Naming Conflicts: Include the service context to prevent overlaps:
Use "slack_send_message" instead of just "send_message"
Use "github_create_issue" instead of just "create_issue"
Use "asana_list_tasks" instead of just "list_tasks"
Tool Structure
Tools are registered using the registerTool method with the following requirements:
Use Zod schemas for runtime input validation and type safety
The
descriptionfield must be explicitly provided - JSDoc comments are NOT automatically extractedExplicitly provide
title,description,inputSchema, andannotationsThe
inputSchemamust be a Zod schema object (not a JSON schema)Type all parameters and return values explicitly
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({
name: "example-mcp",
version: "1.0.0"
});
// Zod schema for input validation
const UserSearchInputSchema = z.object({
query: z.string()
.min(2, "Query must be at least 2 characters")
.max(200, "Query must not exceed 200 characters")
.describe("Search string to match against names/emails"),
limit: z.number()
.int()
.min(1)
.max(100)
.default(20)
.describe("Maximum results to return"),
offset: z.number()
.int()
.min(0)
.default(0)
.describe("Number of results to skip for pagination"),
response_format: z.nativeEnum(ResponseFormat)
.default(ResponseFormat.MARKDOWN)
.describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
}).strict();
// Type definition from Zod schema
type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
server.registerTool(
"example_search_users",
{
title: "Search Example Users",
description: `Search for users in the Example system by name, email, or team.
This tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones.
Args:
- query (string): Search string to match against names/emails
- limit (number): Maximum results to return, between 1-100 (default: 20)
- offset (number): Number of results to skip for pagination (default: 0)
- response_format ('markdown' | 'json'): Output format (default: 'markdown')
Returns:
For JSON format: Structured data with schema:
{
"total": number, // Total number of matches found
"count": number, // Number of results in this response
"offset": number, // Current pagination offset
"users": [
{
"id": string, // User ID (e.g., "U123456789")
"name": string, // Full name (e.g., "John Doe")
"email": string, // Email address
"team": string, // Team name (optional)
"active": boolean // Whether user is active
}
],
"has_more": boolean, // Whether more results are available
"next_offset": number // Offset for next page (if has_more is true)
}
Examples:
- Use when: "Find all marketing team members" -> params with query="team:marketing"
- Use when: "Search for John's account" -> params with query="john"
- Don't use when: You need to create a user (use example_create_user instead)
Error Handling:
- Returns "Error: Rate limit exceeded" if too many requests (429 status)
- Returns "No users found matching '<query>'" if search returns empty`,
inputSchema: UserSearchInputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async (params: UserSearchInput) => {
try {
// Input validation is handled by Zod schema
// Make API request using validated parameters
const data = await makeApiRequest<any>(
"users/search",
"GET",
undefined,
{
q: params.query,
limit: params.limit,
offset: params.offset
}
);
const users = data.users || [];
const total = data.total || 0;
if (!users.length) {
return {
content: [{
type: "text",
text: `No users found matching '${params.query}'`
}]
};
}
// Prepare structured output
const output = {
total,
count: users.length,
offset: params.offset,
users: users.map((user: any) => ({
id: user.id,
name: user.name,
email: user.email,
...(user.team ? { team: user.team } : {}),
active: user.active ?? true
})),
has_more: total > params.offset + users.length,
...(total > params.offset + users.length ? {
next_offset: params.offset + users.length
} : {})
};
// Format text representation based on requested format
let textContent: string;
if (params.response_format === ResponseFormat.MARKDOWN) {
const lines = [`# User Search Results: '${params.query}'`, "",
`Found ${total} users (showing ${users.length})`, ""];
for (const user of users) {
lines.push(`## ${user.name} (${user.id})`);
lines.push(`- **Email**: ${user.email}`);
if (user.team) lines.push(`- **Team**: ${user.team}`);
lines.push("");
}
textContent = lines.join("\n");
} else {
textContent = JSON.stringify(output, null, 2);
}
return {
content: [{ type: "text", text: textContent }],
structuredContent: output // Modern pattern for structured data
};
} catch (error) {
return {
content: [{
type: "text",
text: handleApiError(error)
}]
};
}
}
);Zod Schemas for Input Validation
Zod provides runtime type validation:
import { z } from "zod";
// Basic schema with validation
const CreateUserSchema = z.object({
name: z.string()
.min(1, "Name is required")
.max(100, "Name must not exceed 100 characters"),
email: z.string()
.email("Invalid email format"),
age: z.number()
.int("Age must be a whole number")
.min(0, "Age cannot be negative")
.max(150, "Age cannot be greater than 150")
}).strict(); // Use .strict() to forbid extra fields
// Enums
enum ResponseFormat {
MARKDOWN = "markdown",
JSON = "json"
}
const SearchSchema = z.object({
response_format: z.nativeEnum(ResponseFormat)
.default(ResponseFormat.MARKDOWN)
.describe("Output format")
});
// Optional fields with defaults
const PaginationSchema = z.object({
limit: z.number()
.int()
.min(1)
.max(100)
.default(20)
.describe("Maximum results to return"),
offset: z.number()
.int()
.min(0)
.default(0)
.describe("Number of results to skip")
});Response Format Options
Support multiple output formats for flexibility:
enum ResponseFormat {
MARKDOWN = "markdown",
JSON = "json"
}
const inputSchema = z.object({
query: z.string(),
response_format: z.nativeEnum(ResponseFormat)
.default(ResponseFormat.MARKDOWN)
.describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
});Markdown format:
Use headers, lists, and formatting for clarity
Convert timestamps to human-readable format
Show display names with IDs in parentheses
Omit verbose metadata
Group related information logically
JSON format:
Return complete, structured data suitable for programmatic processing
Include all available fields and metadata
Use consistent field names and types
Pagination Implementation
For tools that list resources:
const ListSchema = z.object({
limit: z.number().int().min(1).max(100).default(20),
offset: z.number().int().min(0).default(0)
});
async function listItems(params: z.infer<typeof ListSchema>) {
const data = await apiRequest(params.limit, params.offset);
const response = {
total: data.total,
count: data.items.length,
offset: params.offset,
items: data.items,
has_more: data.total > params.offset + data.items.length,
next_offset: data.total > params.offset + data.items.length
? params.offset + data.items.length
: undefined
};
return JSON.stringify(response, null, 2);
}Character Limits and Truncation
Add a CHARACTER_LIMIT constant to prevent overwhelming responses:
// At module level in constants.ts
export const CHARACTER_LIMIT = 25000; // Maximum response size in characters
async function searchTool(params: SearchInput) {
let result = generateResponse(data);
// Check character limit and truncate if needed
if (result.length > CHARACTER_LIMIT) {
const truncatedData = data.slice(0, Math.max(1, data.length / 2));
response.data = truncatedData;
response.truncated = true;
response.truncation_message =
`Response truncated from ${data.length} to ${truncatedData.length} items. ` +
`Use 'offset' parameter or add filters to see more results.`;
result = JSON.stringify(response, null, 2);
}
return result;
}Error Handling
Provide clear, actionable error messages:
import axios, { AxiosError } from "axios";
function handleApiError(error: unknown): string {
if (error instanceof AxiosError) {
if (error.response) {
switch (error.response.status) {
case 404:
return "Error: Resource not found. Please check the ID is correct.";
case 403:
return "Error: Permission denied. You don't have access to this resource.";
case 429:
return "Error: Rate limit exceeded. Please wait before making more requests.";
default:
return `Error: API request failed with status ${error.response.status}`;
}
} else if (error.code === "ECONNABORTED") {
return "Error: Request timed out. Please try again.";
}
}
return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
}Shared Utilities
Extract common functionality into reusable functions:
// Shared API request function
async function makeApiRequest<T>(
endpoint: string,
method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
data?: any,
params?: any
): Promise<T> {
try {
const response = await axios({
method,
url: `${API_BASE_URL}/${endpoint}`,
data,
params,
timeout: 30000,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
});
return response.data;
} catch (error) {
throw error;
}
}Async/Await Best Practices
Always use async/await for network requests and I/O operations:
// Good: Async network request
async function fetchData(resourceId: string): Promise<ResourceData> {
const response = await axios.get(`${API_URL}/resource/${resourceId}`);
return response.data;
}
// Bad: Promise chains
function fetchData(resourceId: string): Promise<ResourceData> {
return axios.get(`${API_URL}/resource/${resourceId}`)
.then(response => response.data); // Harder to read and maintain
}TypeScript Best Practices
Use Strict TypeScript: Enable strict mode in tsconfig.json
Define Interfaces: Create clear interface definitions for all data structures
Avoid
any: Use proper types orunknowninstead ofanyZod for Runtime Validation: Use Zod schemas to validate external data
Type Guards: Create type guard functions for complex type checking
Error Handling: Always use try-catch with proper error type checking
Null Safety: Use optional chaining (
?.) and nullish coalescing (??)
// Good: Type-safe with Zod and interfaces
interface UserResponse {
id: string;
name: string;
email: string;
team?: string;
active: boolean;
}
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
team: z.string().optional(),
active: z.boolean()
});
type User = z.infer<typeof UserSchema>;
async function getUser(id: string): Promise<User> {
const data = await apiCall(`/users/${id}`);
return UserSchema.parse(data); // Runtime validation
}
// Bad: Using any
async function getUser(id: string): Promise<any> {
return await apiCall(`/users/${id}`); // No type safety
}Package Configuration
package.json
{
"name": "{service}-mcp-server",
"version": "1.0.0",
"description": "MCP server for {Service} API integration",
"type": "module",
"main": "dist/index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"build": "tsc",
"clean": "rm -rf dist"
},
"engines": {
"node": ">=18"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.6.1",
"axios": "^1.7.9",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/node": "^22.10.0",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
}
}tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}Complete Example
#!/usr/bin/env node
/**
* MCP Server for Example Service.
*
* This server provides tools to interact with Example API, including user search,
* project management, and data export capabilities.
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import axios, { AxiosError } from "axios";
// Constants
const API_BASE_URL = "https://api.example.com/v1";
const CHARACTER_LIMIT = 25000;
// Enums
enum ResponseFormat {
MARKDOWN = "markdown",
JSON = "json"
}
// Zod schemas
const UserSearchInputSchema = z.object({
query: z.string()
.min(2, "Query must be at least 2 characters")
.max(200, "Query must not exceed 200 characters")
.describe("Search string to match against names/emails"),
limit: z.number()
.int()
.min(1)
.max(100)
.default(20)
.describe("Maximum results to return"),
offset: z.number()
.int()
.min(0)
.default(0)
.describe("Number of results to skip for pagination"),
response_format: z.nativeEnum(ResponseFormat)
.default(ResponseFormat.MARKDOWN)
.describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
}).strict();
type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
// Shared utility functions
async function makeApiRequest<T>(
endpoint: string,
method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
data?: any,
params?: any
): Promise<T> {
try {
const response = await axios({
method,
url: `${API_BASE_URL}/${endpoint}`,
data,
params,
timeout: 30000,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
});
return response.data;
} catch (error) {
throw error;
}
}
function handleApiError(error: unknown): string {
if (error instanceof AxiosError) {
if (error.response) {
switch (error.response.status) {
case 404:
return "Error: Resource not found. Please check the ID is correct.";
case 403:
return "Error: Permission denied. You don't have access to this resource.";
case 429:
return "Error: Rate limit exceeded. Please wait before making more requests.";
default:
return `Error: API request failed with status ${error.response.status}`;
}
} else if (error.code === "ECONNABORTED") {
return "Error: Request timed out. Please try again.";
}
}
return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
}
// Create MCP server instance
const server = new McpServer({
name: "example-mcp",
version: "1.0.0"
});
// Register tools
server.registerTool(
"example_search_users",
{
title: "Search Example Users",
description: `[Full description as shown above]`,
inputSchema: UserSearchInputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async (params: UserSearchInput) => {
// Implementation as shown above
}
);
// Main function
// For stdio (local):
async function runStdio() {
if (!process.env.EXAMPLE_API_KEY) {
console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
process.exit(1);
}
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("MCP server running via stdio");
}
// For streamable HTTP (remote):
async function runHTTP() {
if (!process.env.EXAMPLE_API_KEY) {
console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
process.exit(1);
}
const app = express();
app.use(express.json());
app.post('/mcp', async (req, res) => {
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true
});
res.on('close', () => transport.close());
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
const port = parseInt(process.env.PORT || '3000');
app.listen(port, () => {
console.error(`MCP server running on http://localhost:${port}/mcp`);
});
}
// Choose transport based on environment
const transport = process.env.TRANSPORT || 'stdio';
if (transport === 'http') {
runHTTP().catch(error => {
console.error("Server error:", error);
process.exit(1);
});
} else {
runStdio().catch(error => {
console.error("Server error:", error);
process.exit(1);
});
}Advanced MCP Features
Resource Registration
Expose data as resources for efficient, URI-based access:
import { ResourceTemplate } from "@modelcontextprotocol/sdk/types.js";
// Register a resource with URI template
server.registerResource(
{
uri: "file://documents/{name}",
name: "Document Resource",
description: "Access documents by name",
mimeType: "text/plain"
},
async (uri: string) => {
// Extract parameter from URI
const match = uri.match(/^file:\/\/documents\/(.+)$/);
if (!match) {
throw new Error("Invalid URI format");
}
const documentName = match[1];
const content = await loadDocument(documentName);
return {
contents: [{
uri,
mimeType: "text/plain",
text: content
}]
};
}
);
// List available resources dynamically
server.registerResourceList(async () => {
const documents = await getAvailableDocuments();
return {
resources: documents.map(doc => ({
uri: `file://documents/${doc.name}`,
name: doc.name,
mimeType: "text/plain",
description: doc.description
}))
};
});When to use Resources vs Tools:
Resources: For data access with simple URI-based parameters
Tools: For complex operations requiring validation and business logic
Resources: When data is relatively static or template-based
Tools: When operations have side effects or complex workflows
Transport Options
The TypeScript SDK supports two main transport mechanisms:
Streamable HTTP (Recommended for Remote Servers)
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import express from "express";
const app = express();
app.use(express.json());
app.post('/mcp', async (req, res) => {
// Create new transport for each request (stateless, prevents request ID collisions)
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true
});
res.on('close', () => transport.close());
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
app.listen(3000);stdio (For Local Integrations)
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const transport = new StdioServerTransport();
await server.connect(transport);Transport selection:
Streamable HTTP: Web services, remote access, multiple clients
stdio: Command-line tools, local development, subprocess integration
Notification Support
Notify clients when server state changes:
// Notify when tools list changes
server.notification({
method: "notifications/tools/list_changed"
});
// Notify when resources change
server.notification({
method: "notifications/resources/list_changed"
});Use notifications sparingly - only when server capabilities genuinely change.
Code Best Practices
Code Composability and Reusability
Your implementation MUST prioritize composability and code reuse:
Extract Common Functionality:
Create reusable helper functions for operations used across multiple tools
Build shared API clients for HTTP requests instead of duplicating code
Centralize error handling logic in utility functions
Extract business logic into dedicated functions that can be composed
Extract shared markdown or JSON field selection & formatting functionality
Avoid Duplication:
NEVER copy-paste similar code between tools
If you find yourself writing similar logic twice, extract it into a function
Common operations like pagination, filtering, field selection, and formatting should be shared
Authentication/authorization logic should be centralized
Building and Running
Always build your TypeScript code before running:
# Build the project
npm run build
# Run the server
npm start
# Development with auto-reload
npm run devAlways ensure npm run build completes successfully before considering the implementation complete.
Quality Checklist
Before finalizing your Node/TypeScript MCP server implementation, ensure:
Strategic Design
[ ] Tools enable complete workflows, not just API endpoint wrappers
[ ] Tool names reflect natural task subdivisions
[ ] Response formats optimize for agent context efficiency
[ ] Human-readable identifiers used where appropriate
[ ] Error messages guide agents toward correct usage
Implementation Quality
[ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented
[ ] All tools registered using
registerToolwith complete configuration[ ] All tools include
title,description,inputSchema, andannotations[ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
[ ] All tools use Zod schemas for runtime input validation with
.strict()enforcement[ ] All Zod schemas have proper constraints and descriptive error messages
[ ] All tools have comprehensive descriptions with explicit input/output types
[ ] Descriptions include return value examples and complete schema documentation
[ ] Error messages are clear, actionable, and educational
TypeScript Quality
[ ] TypeScript interfaces are defined for all data structures
[ ] Strict TypeScript is enabled in tsconfig.json
[ ] No use of
anytype - useunknownor proper types instead[ ] All async functions have explicit Promise<T> return types
[ ] Error handling uses proper type guards (e.g.,
axios.isAxiosError,z.ZodError)
Advanced Features (where applicable)
[ ] Resources registered for appropriate data endpoints
[ ] Appropriate transport configured (stdio or streamable HTTP)
[ ] Notifications implemented for dynamic server capabilities
[ ] Type-safe with SDK interfaces
Project Configuration
[ ] Package.json includes all necessary dependencies
[ ] Build script produces working JavaScript in dist/ directory
[ ] Main entry point is properly configured as dist/index.js
[ ] Server name follows format:
{service}-mcp-server[ ] tsconfig.json properly configured with strict mode
Code Quality
[ ] Pagination is properly implemented where applicable
[ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages
[ ] Filtering options are provided for potentially large result sets
[ ] All network operations handle timeouts and connection errors gracefully
[ ] Common functionality is extracted into reusable functions
[ ] Return types are consistent across similar operations
Testing and Build
[ ]
npm run buildcompletes successfully without errors[ ] dist/index.js created and executable
[ ] Server runs:
node dist/index.js --help[ ] All imports resolve correctly
[ ] Sample tool calls work as expected
Requirements and compatibility
Written for: Claude Code, Claude apps
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Names Claude Code tools, Needs an MCP server, Needs network access, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Anthropic
- Publisher
- Anthropic (Official)
- Source
- anthropics/skills · skills/mcp-builder · commit 2c5958e
- Licence
- Apache License 2.0 (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Anthropic or Anthropic.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mcp-builder.zip