Token导航 LogoToken导航

Agent Skill · 研究检索

mcp-server-generator(MCP server 生成器)

mcp-server-generator 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

mcp-server-generator 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证为 MIT,暂无第三方扫描结果,按安装量在研究检索类的 73,675 个 Skill 里排第 5,264。

总安装 26,901周安装 811GitHub Stars 公开资料未说明下载 9,611核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:mcp-server-generator(MCP server 生成器)
来源仓库:https://github.com/krosebrook/source-of-truth-monorepo
仓库路径:skills/mcp-server-generator
安装命令:
npx skills add krosebrook/source-of-truth-monorepo --skill "mcp-server-generator"
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

AgentSkills.tonpx skills
npx skills add krosebrook/source-of-truth-monorepo --skill "mcp-server-generator"

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

发现并安装AI代理的技能工具集,加速MCP服务器模板生成。适用于Codex、Claude、Cursor、Gemini CLI等平台的快速原型开发。自动生成符合MCP规范的服务端脚手架与配置文件。

安装命令:npx skills add krosebrook/source-of-truth-monorepo --skill "mcp-server-generator 注意检查生成的代码是否符合团队编码标准与安全要求

来源仓库内路径:skills/mcp-server-generator

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add krosebrook/source-of-truth-monorepo --skill "mcp-server-generator…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

mcp-server-generator 怎么安装?

在终端执行 npx skills add krosebrook/source-of-truth-monorepo --skill "mcp-server-generator"。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

mcp-server-generator 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

mcp-server-generator 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

mcp-server-generator 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

mcp-server-generator 用的人多吗?

公开数据是累计安装 26,901 次,近一周安装 811 次,下载 9,611 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

mcp-server-generator 安全吗?

没有查到第三方扫描结果,安全性无法从公开资料判断,安装前请自行审查源码、依赖和命令行为。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 许可证明确为 MIT,商用和分发边界好判断。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 没有第三方扫描结果,安全性只能靠自己读源码判断。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 要求有安全扫描结论才肯安装的团队。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
mcp-server-generator

MCP server 生成器 · 本页

26,901—接触敏感数据MIT未收录

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

name
MCP Server Generator
description
Expert guidance for creating, configuring, and deploying Model Context Protocol (MCP) servers. Use when building custom MCP servers, integrating external APIs, or extending Claude with new capabilities.
version
1.0.0
allowed-tools

MCP Server Generator

Comprehensive system for creating high-quality Model Context Protocol (MCP) servers that integrate external APIs, databases, and services with Claude.

Core Concepts

What is MCP?

Model Context Protocol (MCP) is an open standard that enables AI applications to connect to external data sources and tools. MCP servers provide:

  • Resources: File-like data (documents, logs, database schemas)
  • Tools: Executable functions (API calls, calculations, searches)
  • Prompts: Reusable prompt templates
  • Sampling: LLM completion requests

MCP Architecture

┌─────────────┐         ┌─────────────┐         ┌──────────────┐
│   Claude    │ ◄─────► │ MCP Server  │ ◄─────► │ External API │
│  (Client)   │   MCP   │  (Bridge)   │         │  or Service  │
└─────────────┘         └─────────────┘         └──────────────┘

Implementation Patterns

1. TypeScript/Node.js MCP Server

Basic Structure:

#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
  ListResourcesRequestSchema,
  ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

// Initialize server
const server = new Server(
  {
    name: "my-mcp-server",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
      resources: {},
      prompts: {},
    },
  }
);

// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "example_tool",
        description: "An example tool that does something useful",
        inputSchema: {
          type: "object",
          properties: {
            query: {
              type: "string",
              description: "The query parameter",
            },
          },
          required: ["query"],
        },
      },
    ],
  };
});

// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "example_tool") {
    const result = await performAction(args.query);
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  }

  throw new Error(`Unknown tool: ${name}`);
});

// List resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: "example://resource/1",
        name: "Example Resource",
        description: "An example resource",
        mimeType: "application/json",
      },
    ],
  };
});

// Read resource
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  const { uri } = request.params;

  if (uri === "example://resource/1") {
    return {
      contents: [
        {
          uri,
          mimeType: "application/json",
          text: JSON.stringify({ data: "example" }, null, 2),
        },
      ],
    };
  }

  throw new Error(`Resource not found: ${uri}`);
});

// Start server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MCP Server running on stdio");
}

main().catch(console.error);

package.json:

{
  "name": "my-mcp-server",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "my-mcp-server": "./dist/index.js"
  },
  "scripts": {
    "build": "tsc && chmod +x dist/index.js",
    "dev": "tsc --watch",
    "prepare": "npm run build"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^0.5.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "typescript": "^5.3.0"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "declaration": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

2. Python MCP Server

Basic Structure:

#!/usr/bin/env python3
import asyncio
import logging
from typing import Any

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
    Tool,
    TextContent,
    Resource,
    INTERNAL_ERROR,
)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize server
app = Server("my-mcp-server")

@app.list_tools()
async def list_tools() -> list[Tool]:
    """List available tools."""
    return [
        Tool(
            name="example_tool",
            description="An example tool that does something useful",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The query parameter",
                    },
                },
                "required": ["query"],
            },
        ),
    ]

@app.call_tool()
async def call_tool(name: str, arguments: Any) -> list[TextContent]:
    """Handle tool calls."""
    if name == "example_tool":
        query = arguments.get("query")
        result = await perform_action(query)

        return [
            TextContent(
                type="text",
                text=str(result),
            )
        ]

    raise ValueError(f"Unknown tool: {name}")

@app.list_resources()
async def list_resources() -> list[Resource]:
    """List available resources."""
    return [
        Resource(
            uri="example://resource/1",
            name="Example Resource",
            description="An example resource",
            mimeType="application/json",
        ),
    ]

@app.read_resource()
async def read_resource(uri: str) -> str:
    """Read resource content."""
    if uri == "example://resource/1":
        return '{"data": "example"}'

    raise ValueError(f"Resource not found: {uri}")

async def perform_action(query: str) -> dict:
    """Perform the actual action."""
    # Your implementation here
    return {"query": query, "result": "success"}

async def main():
    """Run the MCP server."""
    async with stdio_server() as (read_stream, write_stream):
        await app.run(
            read_stream,
            write_stream,
            app.create_initialization_options()
        )

if __name__ == "__main__":
    asyncio.run(main())

pyproject.toml:

[project]
name = "my-mcp-server"
version = "1.0.0"
description = "MCP server for..."
requires-python = ">=3.10"
dependencies = [
    "mcp>=0.9.0",
]

[project.scripts]
my-mcp-server = "my_mcp_server:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

3. Common MCP Server Patterns

API Integration Server
// GitHub API MCP Server Example
import { Octokit } from "@octokit/rest";

const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "search_repositories",
        description: "Search GitHub repositories",
        inputSchema: {
          type: "object",
          properties: {
            query: { type: "string", description: "Search query" },
            language: { type: "string", description: "Filter by language" },
            limit: { type: "number", description: "Max results", default: 10 },
          },
          required: ["query"],
        },
      },
      {
        name: "get_repository",
        description: "Get repository details",
        inputSchema: {
          type: "object",
          properties: {
            owner: { type: "string", description: "Repository owner" },
            repo: { type: "string", description: "Repository name" },
          },
          required: ["owner", "repo"],
        },
      },
      {
        name: "create_issue",
        description: "Create a new issue",
        inputSchema: {
          type: "object",
          properties: {
            owner: { type: "string" },
            repo: { type: "string" },
            title: { type: "string" },
            body: { type: "string" },
            labels: { type: "array", items: { type: "string" } },
          },
          required: ["owner", "repo", "title"],
        },
      },
    ],
  };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  switch (name) {
    case "search_repositories": {
      const result = await octokit.search.repos({
        q: `${args.query}${args.language ? ` language:${args.language}` : ""}`,
        per_page: args.limit || 10,
      });
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              result.data.items.map((item) => ({
                name: item.full_name,
                description: item.description,
                stars: item.stargazers_count,
                url: item.html_url,
              })),
              null,
              2
            ),
          },
        ],
      };
    }

    case "get_repository": {
      const result = await octokit.repos.get({
        owner: args.owner,
        repo: args.repo,
      });
      return {
        content: [
          { type: "text", text: JSON.stringify(result.data, null, 2) },
        ],
      };
    }

    case "create_issue": {
      const result = await octokit.issues.create({
        owner: args.owner,
        repo: args.repo,
        title: args.title,
        body: args.body,
        labels: args.labels,
      });
      return {
        content: [
          { type: "text", text: `Issue created: ${result.data.html_url}` },
        ],
      };
    }

    default:
      throw new Error(`Unknown tool: ${name}`);
  }
});
Database Integration Server
# PostgreSQL MCP Server Example
import asyncpg
from mcp.server import Server
from mcp.types import Tool, TextContent

app = Server("postgres-mcp-server")

# Connection pool
pool = None

async def init_db():
    global pool
    pool = await asyncpg.create_pool(
        host=os.getenv("DB_HOST", "localhost"),
        port=int(os.getenv("DB_PORT", "5432")),
        database=os.getenv("DB_NAME"),
        user=os.getenv("DB_USER"),
        password=os.getenv("DB_PASSWORD"),
    )

@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="query_database",
            description="Execute a read-only SQL query",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "SQL SELECT query to execute",
                    },
                },
                "required": ["query"],
            },
        ),
        Tool(
            name="get_schema",
            description="Get database schema information",
            inputSchema={
                "type": "object",
                "properties": {
                    "table_name": {
                        "type": "string",
                        "description": "Optional table name to filter",
                    },
                },
            },
        ),
    ]

@app.call_tool()
async def call_tool(name: str, arguments: Any) -> list[TextContent]:
    if name == "query_database":
        query = arguments.get("query", "")

        # Security: Only allow SELECT queries
        if not query.strip().upper().startswith("SELECT"):
            raise ValueError("Only SELECT queries are allowed")

        async with pool.acquire() as conn:
            results = await conn.fetch(query)
            return [
                TextContent(
                    type="text",
                    text=json.dumps([dict(row) for row in results], indent=2),
                )
            ]

    elif name == "get_schema":
        table_filter = arguments.get("table_name")

        query = """
            SELECT table_name, column_name, data_type, is_nullable
            FROM information_schema.columns
            WHERE table_schema = 'public'
        """

        if table_filter:
            query += f" AND table_name = '{table_filter}'"

        async with pool.acquire() as conn:
            results = await conn.fetch(query)
            return [
                TextContent(
                    type="text",
                    text=json.dumps([dict(row) for row in results], indent=2),
                )
            ]

    raise ValueError(f"Unknown tool: {name}")
File System Server
// File System MCP Server
import fs from "fs/promises";
import path from "path";

const ALLOWED_DIRECTORIES = [
  process.env.DOCS_PATH || "./docs",
  process.env.DATA_PATH || "./data",
];

function isPathAllowed(filePath: string): boolean {
  const absPath = path.resolve(filePath);
  return ALLOWED_DIRECTORIES.some((dir) =>
    absPath.startsWith(path.resolve(dir))
  );
}

server.setRequestHandler(ListResourcesRequestSchema, async () => {
  const resources = [];

  for (const dir of ALLOWED_DIRECTORIES) {
    const files = await fs.readdir(dir, { recursive: true });
    for (const file of files) {
      const fullPath = path.join(dir, file);
      const stats = await fs.stat(fullPath);

      if (stats.isFile()) {
        resources.push({
          uri: `file://${fullPath}`,
          name: file,
          description: `File at ${fullPath}`,
          mimeType: getMimeType(fullPath),
        });
      }
    }
  }

  return { resources };
});

server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  const { uri } = request.params;
  const filePath = uri.replace("file://", "");

  if (!isPathAllowed(filePath)) {
    throw new Error("Access denied");
  }

  const content = await fs.readFile(filePath, "utf-8");

  return {
    contents: [
      {
        uri,
        mimeType: getMimeType(filePath),
        text: content,
      },
    ],
  };
});

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "search_files",
        description: "Search for files by name or content",
        inputSchema: {
          type: "object",
          properties: {
            query: { type: "string", description: "Search query" },
            type: {
              type: "string",
              enum: ["name", "content"],
              description: "Search by filename or content",
            },
          },
          required: ["query", "type"],
        },
      },
      {
        name: "write_file",
        description: "Write content to a file",
        inputSchema: {
          type: "object",
          properties: {
            path: { type: "string", description: "File path" },
            content: { type: "string", description: "File content" },
          },
          required: ["path", "content"],
        },
      },
    ],
  };
});

4. Configuration & Deployment

Claude Desktop Configuration:

On macOS: ~/Library/Application Support/Claude/claude_desktop_config.json On Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "my-mcp-server": {
      "command": "node",
      "args": ["/path/to/my-mcp-server/dist/index.js"],
      "env": {
        "API_KEY": "your-api-key",
        "LOG_LEVEL": "info"
      }
    },
    "python-mcp-server": {
      "command": "python",
      "args": ["-m", "my_mcp_server"],
      "env": {
        "DATABASE_URL": "postgresql://localhost/mydb"
      }
    },
    "npx-server": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."
      }
    }
  }
}

Environment Variables Best Practices:

// Load from .env file
import dotenv from "dotenv";
dotenv.config();

// Validate required env vars
const requiredEnvVars = ["API_KEY", "DATABASE_URL"];
for (const varName of requiredEnvVars) {
  if (!process.env[varName]) {
    throw new Error(`Missing required environment variable: ${varName}`);
  }
}

// Use with defaults
const config = {
  apiKey: process.env.API_KEY,
  apiUrl: process.env.API_URL || "https://api.example.com",
  timeout: parseInt(process.env.TIMEOUT || "30000"),
  maxRetries: parseInt(process.env.MAX_RETRIES || "3"),
};

5. Error Handling & Logging

Comprehensive Error Handling:

import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  try {
    // Validate arguments
    if (!args.query) {
      throw new McpError(
        ErrorCode.InvalidParams,
        "Missing required parameter: query"
      );
    }

    // Perform action
    const result = await performAction(args.query);

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  } catch (error) {
    // Log error
    console.error(`Error in tool ${name}:`, error);

    // Return user-friendly error
    if (error instanceof McpError) {
      throw error;
    }

    throw new McpError(
      ErrorCode.InternalError,
      `Failed to execute tool: ${error.message}`
    );
  }
});

Structured Logging:

import logging
import json
from datetime import datetime

# Configure JSON logging
class JSONFormatter(logging.Formatter):
    def format(self, record):
        log_data = {
            "timestamp": datetime.utcnow().isoformat(),
            "level": record.levelname,
            "message": record.getMessage(),
            "module": record.module,
            "function": record.funcName,
        }
        if record.exc_info:
            log_data["exception"] = self.formatException(record.exc_info)
        return json.dumps(log_data)

handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# Use in code
logger.info("Tool called", extra={"tool_name": name, "args": arguments})
logger.error("API request failed", extra={"status_code": 500, "url": api_url})

6. Testing Strategies

Unit Testing:

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

describe("MCP Server", () => {
  let client: Client;
  let transport: StdioClientTransport;

  beforeAll(async () => {
    transport = new StdioClientTransport({
      command: "node",
      args: ["./dist/index.js"],
    });

    client = new Client(
      {
        name: "test-client",
        version: "1.0.0",
      },
      {
        capabilities: {},
      }
    );

    await client.connect(transport);
  });

  afterAll(async () => {
    await client.close();
  });

  it("should list tools", async () => {
    const response = await client.listTools();
    expect(response.tools).toHaveLength(3);
    expect(response.tools[0].name).toBe("example_tool");
  });

  it("should call tool successfully", async () => {
    const response = await client.callTool({
      name: "example_tool",
      arguments: { query: "test" },
    });
    expect(response.content).toBeDefined();
  });

  it("should handle errors gracefully", async () => {
    await expect(
      client.callTool({
        name: "non_existent_tool",
        arguments: {},
      })
    ).rejects.toThrow();
  });
});

Integration Testing:

# Test server manually
node dist/index.js &
SERVER_PID=$!

# Send test requests
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | node dist/index.js

# Cleanup
kill $SERVER_PID

7. Performance Optimization

Caching:

import NodeCache from "node-cache";

const cache = new NodeCache({ stdTTL: 600 }); // 10 minutes

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "expensive_operation") {
    const cacheKey = `${name}:${JSON.stringify(args)}`;

    // Check cache
    const cached = cache.get(cacheKey);
    if (cached) {
      return {
        content: [{ type: "text", text: JSON.stringify(cached) }],
      };
    }

    // Perform operation
    const result = await expensiveOperation(args);

    // Store in cache
    cache.set(cacheKey, result);

    return {
      content: [{ type: "text", text: JSON.stringify(result) }],
    };
  }
});

Rate Limiting:

import rateLimit from "express-rate-limit";

const limiter = new Map();

function checkRateLimit(key: string): boolean {
  const now = Date.now();
  const record = limiter.get(key) || { count: 0, resetAt: now + 60000 };

  if (now > record.resetAt) {
    record.count = 0;
    record.resetAt = now + 60000;
  }

  record.count++;
  limiter.set(key, record);

  return record.count <= 100; // 100 requests per minute
}

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (!checkRateLimit("global")) {
    throw new McpError(ErrorCode.InternalError, "Rate limit exceeded");
  }

  // Handle request...
});

8. Security Best Practices

Input Validation:

import { z } from "zod";

const toolInputSchemas = {
  search_query: z.object({
    query: z.string().min(1).max(500),
    limit: z.number().int().min(1).max(100).optional(),
    filters: z.record(z.string()).optional(),
  }),
};

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  // Validate input
  const schema = toolInputSchemas[name];
  if (!schema) {
    throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);
  }

  try {
    const validatedArgs = schema.parse(args);
    // Use validatedArgs...
  } catch (error) {
    throw new McpError(
      ErrorCode.InvalidParams,
      `Invalid arguments: ${error.message}`
    );
  }
});

Access Control:

function checkPermissions(userId: string, action: string): boolean {
  const permissions = {
    admin: ["read", "write", "delete"],
    user: ["read"],
    guest: [],
  };

  const userRole = getUserRole(userId);
  return permissions[userRole]?.includes(action) || false;
}

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const userId = request.params._meta?.userId;
  const action = getActionFromTool(request.params.name);

  if (!checkPermissions(userId, action)) {
    throw new McpError(ErrorCode.InvalidParams, "Permission denied");
  }

  // Proceed with request...
});

9. Publishing & Distribution

NPM Package:

{
  "name": "@company/mcp-server-example",
  "version": "1.0.0",
  "description": "MCP server for...",
  "main": "dist/index.js",
  "bin": {
    "mcp-server-example": "dist/index.js"
  },
  "files": ["dist", "README.md", "LICENSE"],
  "keywords": ["mcp", "claude", "mcp-server"],
  "repository": {
    "type": "git",
    "url": "https://github.com/company/mcp-server-example"
  },
  "publishConfig": {
    "access": "public"
  }
}

Docker Distribution:

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
USER node
CMD ["node", "dist/index.js"]

10. Documentation Template

README.md:

# My MCP Server

> [Brief description of what this server does]

## Features

- Feature 1
- Feature 2
- Feature 3

## Installation

\`\`\`bash
npm install -g my-mcp-server
\`\`\`

## Configuration

Add to your Claude Desktop config:

\`\`\`json
{
  "mcpServers": {
    "my-server": {
      "command": "my-mcp-server",
      "env": {
        "API_KEY": "your-api-key"
      }
    }
  }
}
\`\`\`

## Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| API_KEY | Yes | Your API key |
| API_URL | No | API endpoint (default: https://api.example.com) |

## Available Tools

### tool_name

Description of what this tool does.

**Parameters:**
- `param1` (string, required): Description
- `param2` (number, optional): Description

**Example:**
\`\`\`
Use the tool_name tool with parameter "value"
\`\`\`

## Available Resources

### resource://example/1

Description of this resource.

## Development

\`\`\`bash
git clone https://github.com/company/my-mcp-server
cd my-mcp-server
npm install
npm run build
npm run dev
\`\`\`

## License

MIT

Quick Start Checklist

  • [ ] Choose implementation language (TypeScript/Python)
  • [ ] Set up project structure with proper tooling
  • [ ] Implement tools with clear input schemas
  • [ ] Add comprehensive error handling
  • [ ] Implement caching for expensive operations
  • [ ] Add input validation and sanitization
  • [ ] Set up structured logging
  • [ ] Write unit and integration tests
  • [ ] Create detailed documentation
  • [ ] Configure environment variables properly
  • [ ] Add rate limiting if needed
  • [ ] Implement access control if needed
  • [ ] Test with Claude Desktop
  • [ ] Publish to npm/PyPI or Docker

Common Use Cases

  1. API Integration: GitHub, Jira, Slack, Linear, Notion
  2. Database Access: PostgreSQL, MongoDB, Redis, Elasticsearch
  3. File Systems: Local files, S3, Google Drive, Dropbox
  4. Developer Tools: Git operations, CI/CD, deployment
  5. Business Tools: CRM, ERP, analytics platforms
  6. AI/ML: Vector databases, model APIs, embeddings
  7. Communication: Email, SMS, webhooks, notifications
  8. Monitoring: Logs, metrics, alerts, dashboards

When to Use This Skill:

Invoke when building new MCP servers, troubleshooting existing servers, or integrating external services with Claude.

平台分布

Claude Code

76.31%
按下载量换算7,334

安全审计

暂无安全审计结果可展示。

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills