MCP TypeScript Server Template

MCP TypeScript Server Template

A template repository for building Model Context Protocol (MCP) servers with TypeScript, featuring full TypeScript support, testing setup, CI/CD pipelines, and modular architecture for easy extension.

Category
访问服务器

README

MCP MCP Server

An MCP (Model Context Protocol) server implementation with TypeScript.

GitHub

Features

  • 🚀 Full TypeScript support with strict mode
  • 🧪 Testing setup with Vitest and coverage reporting
  • 📦 Automated releases with semantic-release
  • 🔄 CI/CD pipelines with GitHub Actions
  • 🏗️ Modular architecture for easy extension
  • 📝 Comprehensive documentation and examples
  • 🛠️ Development tools: Biome for linting/formatting, Husky for Git hooks
  • 🎯 Pre-configured for MCP server development
  • 🔐 Built-in validation using Zod schemas
  • ⚡ ES modules with native Node.js support
  • 📊 Code coverage reporting with c8

MCP Servers Built with This Template

Here are some MCP servers built using this template:

Wayback Machine MCP

GitHub npm version npm downloads

Archive and retrieve web pages using the Internet Archive's Wayback Machine. No API keys required.

OpenAlex MCP

GitHub npm version npm downloads

Access scholarly articles and research data from the OpenAlex database.


Building an MCP server? Use this template and add your server to this list!

Quick Start

Using GitHub Template

  1. Click "Use this template" button on GitHub
  2. Clone your new repository
  3. Install dependencies: yarn install
  4. Start development: yarn dev

Manual Setup

# Clone the template
git clone https://github.com/Mearman/mcp-template.git my-mcp-server
cd my-mcp-server

# Install dependencies
yarn install

# Start development
yarn dev

Project Structure

src/
├── index.ts          # MCP server entry point
├── tools/            # Tool implementations
│   ├── example.ts    # Example tool
│   └── *.test.ts     # Tool tests
├── utils/            # Shared utilities
│   ├── validation.ts # Input validation helpers
│   └── *.test.ts     # Utility tests
└── types.ts          # TypeScript type definitions

# Configuration files
├── .github/workflows/  # CI/CD pipelines
├── .husky/            # Git hooks
├── biome.json         # Linter/formatter config
├── tsconfig.json      # TypeScript config
├── vitest.config.ts   # Test runner config
└── .releaserc.json    # Semantic release config

Development

Available Commands

# Install dependencies
yarn install

# Development with hot reload
yarn dev

# Build TypeScript to JavaScript
yarn build

# Run production build
yarn start

# Run tests
yarn test

# Run tests in watch mode
yarn test:watch

# Run tests with coverage report
yarn test:ci

# Lint code
yarn lint

# Auto-fix linting issues
yarn lint:fix

# Format code
yarn format

Development Workflow

  1. Start development: yarn dev - Runs the server with hot reload
  2. Write tests: Add .test.ts files alongside your code
  3. Run tests: yarn test:watch - Keep tests running while you code
  4. Lint/format: Automatic on commit via Husky hooks

Creating Your MCP Server

1. Define Your Tools

Create tool implementations in src/tools/:

// src/tools/my-tool.ts
import { z } from 'zod';

const MyToolSchema = z.object({
  input: z.string().describe('Tool input'),
});

export async function myTool(args: unknown) {
  const { input } = MyToolSchema.parse(args);
  
  // Tool implementation
  return {
    success: true,
    result: `Processed: ${input}`,
  };
}

2. Register Tools in Server

Update src/index.ts to register your tools:

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: 'my_tool',
      description: 'Description of what my tool does',
      inputSchema: zodToJsonSchema(MyToolSchema),
    },
  ],
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  switch (request.params.name) {
    case 'my_tool':
      return await myTool(request.params.arguments);
    default:
      throw new Error(`Unknown tool: ${request.params.name}`);
  }
});

3. Configure for Claude Desktop

Add to claude_desktop_config.json:

{
  "mcpServers": {
    "my-mcp-server": {
      "command": "node",
      "args": ["/path/to/my-mcp-server/dist/index.js"],
      "env": {}
    }
  }
}

Testing

Write tests for your tools in src/tools/*.test.ts:

import { describe, it, expect } from 'vitest';
import { myTool } from './my-tool';

describe('myTool', () => {
  it('should process input correctly', async () => {
    const result = await myTool({ input: 'test' });
    expect(result.success).toBe(true);
    expect(result.result).toBe('Processed: test');
  });
});

Publishing

NPM Package

  1. Update package.json with your package details:

    • name: Your package name (e.g., mcp-your-server)
    • description: Clear description of what your server does
    • keywords: Add relevant keywords for discoverability
    • author: Your name or organization
    • repository: Your GitHub repository URL
  2. Build the project:

    yarn build
    
  3. Test the build locally:

    yarn start
    
  4. Publish to npm:

    npm publish
    

Automated Releases

This template includes semantic-release for automated versioning and publishing:

  1. Follow conventional commits
  2. Push to main branch
  3. CI/CD will automatically:
    • Determine version bump
    • Update CHANGELOG.md
    • Create GitHub release
    • Publish to npm (if NPM_TOKEN secret is configured)

Note: NPM publishing is optional. If you don't want to publish to npm, simply don't add the NPM_TOKEN secret to your repository. The release process will still create GitHub releases.

Best Practices

  1. Input Validation: Always validate tool inputs using Zod schemas
  2. Error Handling: Provide clear error messages for debugging
  3. Testing: Write comprehensive tests for all tools
  4. Documentation: Document each tool's purpose and usage
  5. Type Safety: Leverage TypeScript's type system fully
  6. Modular Design: Keep tools focused on single responsibilities
  7. Async/Await: Use modern async patterns for all I/O operations
  8. Environment Variables: Use .env files for configuration (never commit secrets)

Adding CLI Support

To add CLI functionality to your MCP server (like the Wayback Machine example):

  1. Install Commander.js:

    yarn add commander chalk ora
    
  2. Create src/cli.ts:

    import { Command } from 'commander';
    import chalk from 'chalk';
    
    export function createCLI() {
      const program = new Command();
      
      program
        .name('your-tool')
        .description('Your MCP server as a CLI')
        .version('1.0.0');
        
      // Add commands here
      
      return program;
    }
    
  3. Update src/index.ts to detect CLI mode:

    async function main() {
      const isCliMode = process.stdin.isTTY || process.argv.length > 2;
      
      if (isCliMode && process.argv.length > 2) {
        const { createCLI } = await import('./cli.js');
        const program = createCLI();
        await program.parseAsync(process.argv);
      } else {
        // MCP server mode
        const transport = new StdioServerTransport();
        await server.connect(transport);
      }
    }
    
  4. Add bin entry to package.json:

    "bin": {
      "your-tool": "dist/index.js"
    }
    

License

CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Maintaining Your MCP Server

Template Updates

This template includes scripts to help you merge updates from the template into your derived MCP server:

  1. Merge Updates: Use scripts/merge-template-updates.sh to selectively merge template improvements while preserving your customizations.

  2. Analyze Differences: Use scripts/analyze-template-diff.sh to understand what has changed between your server and the template.

See scripts/README.md for detailed documentation on using these maintenance scripts.

Installing Scripts in Existing Projects

If you created your MCP server before these scripts were added:

# From mcp-template directory
./scripts/install-scripts.sh ../path-to-your-mcp-server

Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

Troubleshooting

Common Issues

  1. Build errors: Ensure all dependencies are installed with yarn install
  2. Type errors: Run npx tsc --noEmit to check TypeScript types
  3. Test failures: Check test files are named *.test.ts
  4. Claude Desktop connection: Verify the path in your config is absolute

Debug Mode

To see detailed logs when running as an MCP server:

DEBUG=* node dist/index.js

Resources

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选