本文へ移動
cccskills
無料GitHub で公開

mcp-builder

Build MCP (Model Context Protocol) servers using the official @modelcontextprotocol/sdk. Use this skill when users ask to create an MCP server, MCP tools, MCP resources, or want to expose APIs/functionality to AI agents. This skill covers vanilla MCP implementation with Streamable HTTP transport, session management, tools, resources, and prompts.

インストール方法を見る

含まれるファイル(5)

  • SKILL.md9.5 KB
  • assets/mcp-server.ts2.6 KB
  • assets/package.json729 B
  • assets/server.ts3.0 KB
  • references/patterns.md3.9 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

MCP Builder Skill

This skill guides you in building MCP (Model Context Protocol) servers using the official @modelcontextprotocol/sdk package with TypeScript.

When to Use This Skill

  • User asks to "create an MCP server"
  • User wants to "expose an API to AI agents"
  • User needs "tools for Claude/LLM"
  • User mentions "Model Context Protocol"
  • User wants to build "AI agent integrations"

MCP Core Concepts

What is MCP?

Model Context Protocol (MCP) is an open standard that enables structured, secure interactions between Large Language Models (LLMs) and external systems. MCP acts as a bridge allowing AI agents to:

  • Access external data sources safely
  • Execute tools and functions
  • Maintain consistent communication protocols
  • Integrate with APIs and databases

Key Components

Tools - Interactive functions that perform actions or computations:

  • Execute operations and computations
  • Accept parameters from the LLM
  • Return structured responses
  • Can change system state (side effects allowed)
  • Examples: calculations, database operations, API calls, sending emails

Resources - Read-only data endpoints:

  • Passive data sources (no side effects)
  • Loaded into AI context for reasoning
  • URI-based identification
  • Examples: documentation, config files, status data, user profiles

Prompts - Reusable prompt templates:

  • Pre-defined conversation starters
  • Can accept arguments for customization
  • Return structured messages for the LLM

Transport Options

TransportBest ForProsCons
Streamable HTTPProduction, cloud, multiple clientsScalable, remote accessRequires session management
SSEReal-time apps, live updatesStreaming, auto-reconnectConnection limits
STDIOLocal desktop, developmentSimple, low latencySingle session, local only

Recommendation: Use Streamable HTTP for most production servers.

Project Structure

my-mcp-server/
├── src/
│   ├── server.ts          # Express server with transport setup
│   ├── mcp-server.ts      # MCP server with tools/resources/prompts
│   └── minimal/           # Optional: organized components
│       ├── tool.ts
│       ├── resource.ts
│       └── prompt.ts
├── package.json
├── tsconfig.json
└── .env

Required Dependencies

{
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.12.0",
    "express": "^4.21.0",
    "cors": "^2.8.5",
    "dotenv": "^16.5.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "@types/express": "^4.17.21",
    "@types/cors": "^2.8.17",
    "typescript": "^5.6.3",
    "tsx": "^4.20.3"
  }
}

TypeScript Configuration

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"]
}

Implementation Pattern

1. MCP Server Setup (mcp-server.ts)

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

export function createMCPServer() {
  const server = new McpServer({
    name: 'my-mcp-server',
    version: '1.0.0',
  });

  // Register tools
  server.tool('toolName', 'Tool description', {
    param1: { type: 'string', description: 'Parameter description' }
  }, async (args) => {
    // Implementation
    return {
      content: [{ type: 'text', text: JSON.stringify(result) }]
    };
  });

  // Register resources
  server.resource('resource://uri', 'Resource description', async () => ({
    contents: [{
      uri: 'resource://uri',
      mimeType: 'application/json',
      text: JSON.stringify(data)
    }]
  }));

  // Register prompts
  server.prompt('promptName', 'Prompt description', async (args) => ({
    messages: [{
      role: 'user',
      content: { type: 'text', text: `Prompt content with ${args.param}` }
    }]
  }));

  return server;
}

2. HTTP Server with Session Management (server.ts)

import express from 'express';
import cors from 'cors';
import { randomUUID } from 'node:crypto';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
import { createMCPServer } from './mcp-server.js';

const app = express();
const PORT = process.env.PORT || 3001;

// CORS for browser clients
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'mcp-session-id', 'mcp-protocol-version', 'Authorization'],
  exposedHeaders: ['mcp-session-id'],
  credentials: true,
}));
app.use(express.json());

// Session storage
const transports: Record<string, StreamableHTTPServerTransport> = {};

// MCP endpoint handler
const handleMCPRequest = async (req, res) => {
  const sessionId = req.headers['mcp-session-id'] as string | undefined;
  let transport: StreamableHTTPServerTransport;

  if (sessionId && transports[sessionId]) {
    transport = transports[sessionId];
  } else if (!sessionId && isInitializeRequest(req.body)) {
    transport = new StreamableHTTPServerTransport({
      sessionIdGenerator: () => randomUUID(),
      onsessioninitialized: (newSessionId) => {
        transports[newSessionId] = transport;
      },
    });

    transport.onclose = () => {
      if (transport.sessionId) delete transports[transport.sessionId];
    };

    const server = createMCPServer();
    await server.connect(transport);
  } else {
    res.status(400).json({
      jsonrpc: '2.0',
      error: { code: -32000, message: 'No valid session ID or not an init request' },
      id: null,
    });
    return;
  }

  await transport.handleRequest(req, res, req.body);
};

app.post('/', handleMCPRequest);
app.post('/mcp', handleMCPRequest);

app.get('/health', (req, res) => {
  res.json({ status: 'ok', server: 'my-mcp-server', version: '1.0.0' });
});

app.listen(PORT, () => console.log(`MCP Server running on port ${PORT}`));

Tool Implementation Examples

Simple Tool

server.tool('echo', 'Echo a message back', {
  message: { type: 'string', description: 'Message to echo' }
}, async ({ message }) => ({
  content: [{ type: 'text', text: `Echo: ${message}` }]
}));

Tool with Multiple Parameters

server.tool('calculate', 'Perform arithmetic operations', {
  a: { type: 'number', description: 'First number' },
  b: { type: 'number', description: 'Second number' },
  operation: { type: 'string', description: 'Operation: add, subtract, multiply, divide' }
}, async ({ a, b, operation }) => {
  let result: number;
  switch (operation) {
    case 'add': result = a + b; break;
    case 'subtract': result = a - b; break;
    case 'multiply': result = a * b; break;
    case 'divide': 
      if (b === 0) throw new Error('Division by zero');
      result = a / b; 
      break;
    default: throw new Error('Invalid operation');
  }
  return { content: [{ type: 'text', text: JSON.stringify({ result }) }] };
});

External API Tool

server.tool('getWeather', 'Get current weather for a city', {
  city: { type: 'string', description: 'City name' }
}, async ({ city }) => {
  const response = await fetch(`https://api.weather.com/v1/current?city=${encodeURIComponent(city)}&key=${process.env.WEATHER_API_KEY}`);
  const data = await response.json();
  return {
    content: [{ type: 'text', text: JSON.stringify({
      city,
      temperature: data.main.temp,
      conditions: data.weather[0].description
    }) }]
  };
});

Resource Implementation Examples

// Static resource
server.resource('config://settings', 'Application settings', async () => ({
  contents: [{
    uri: 'config://settings',
    mimeType: 'application/json',
    text: JSON.stringify({ theme: 'dark', language: 'en' })
  }]
}));

// Dynamic resource
server.resource('server://info', 'Server information', async () => ({
  contents: [{
    uri: 'server://info',
    mimeType: 'application/json',
    text: JSON.stringify({
      name: 'my-server',
      version: '1.0.0',
      uptime: process.uptime(),
      timestamp: new Date().toISOString()
    })
  }]
}));

Editing Guidelines

Core Principles

  1. Edit existing files, don't recreate - Template files are provided; modify them
  2. Preserve existing structure - Don't change fundamental architecture
  3. Minimal necessary changes - Make smallest changes to achieve requirements
  4. Maintain backward compatibility - Don't break existing functionality

DO

  • Add new tools/resources/prompts to existing service files
  • Extend existing functionality
  • Follow existing code patterns
  • Use TypeScript for type safety

DON'T

  • Completely rewrite template files
  • Remove essential boilerplate code
  • Create unnecessary new files
  • Add terminal/command instructions (user will run commands themselves)

Running the Server

The user will handle running commands. Your job is to provide the code files only.

Standard commands the user might run:

  • npm install - Install dependencies
  • npm run dev or npx tsx src/server.ts - Development mode
  • npm run build - Build for production
  • npm start - Run production build

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Analyze tau2-bench task export files to identify exactly where and why tasks failed. Map failures to specific conversation rounds, show root causes, check whether relevant documentation was available, and cite sources. Use this skill whenever you need to debug a tau2-bench evaluation, understand why an agent made wrong decisions, identify missing knowledge, or review task performance—especially when context length, eligibility criteria, or policy compliance might be at fault.

日本語の概要は準備中です。原文の説明を表示しています。

Leanmcp/gateway-skills2,1112026年10月8日 更新

How to develop, modify, and extend the Claude Code codebase following its established programming style, patterns, and conventions. Use this skill whenever working on the claude-code source — adding tools, commands, utils, components, types, hooks, services, or fixing bugs. Also use when the user asks about claude-code architecture, coding standards, file organization, or wants to understand how the codebase works. This skill ensures all contributions match the existing codebase style exactly.

日本語の概要は準備中です。原文の説明を表示しています。

Leanmcp/gateway-skills2,1112026年10月8日 更新

Generate a complete, beginner-friendly explanation of an entire code repository as a set of markdown files. Maps the repo structure with `treecap` (installing it if missing), studies the actual source, then writes a `CODE_EXPLANATION/` folder containing an `OVERVIEW.md` plus numbered deep-dive files (01_architecture.md, 02_models.md, ...) that explain how the code is built, what it does, and how the pieces fit together — illustrated with real code excerpts. Use this skill whenever the user wants to understand, document, onboard onto, or get a walkthrough of a codebase: phrases like "explain this repo", "explain the code", "code explanation", "walk me through this codebase", "help me understand how this is built", "document the architecture", or "what does this project do" — even if they don't say the word "skill". Prefer this over ad-hoc summaries whenever the goal is a durable, written explanation of a whole repo.

日本語の概要は準備中です。原文の説明を表示しています。

Leanmcp/gateway-skills2,1112026年10月8日 更新

Run inference on Fireworks AI — direct, through the Leanmcp AI Gateway proxy (aigateway.leanmcp.com) for observability, or via LiteLLM / the OpenAI SDK / raw HTTP. Covers the endpoint-and-key matrix for each route, serverless vs dedicated deployments and their cold starts, browsing and filtering the model catalogue, reasoning models that return content:null with the answer in reasoning_content, function calling, concurrency and load testing, and runner scripts where many models share one protocol with a --use-proxy toggle. Use this skill whenever the user mentions Fireworks, FIREWORKS_API_KEY, api.fireworks.ai, fireworks_ai/ model ids, accounts/fireworks/models/..., a Fireworks deployment id, the Leanmcp gateway or LEANMCP_API_KEY, app.leanmcp.com observability, or gpt-oss / kimi / glm / qwen / deepseek served on Fireworks; wants to route LLM calls through a proxy for logging or cost tracking; is debugging empty responses, 404s, scope errors, cold starts, or "the gateway isn't working"; wants to pick a Fireworks model with tool calling; or wants to sweep several models over one benchmark. Reach for it even on vague asks like "why is this model returning nothing" or "set up inference for these models" when Fireworks is in play.

日本語の概要は準備中です。原文の説明を表示しています。

Leanmcp/gateway-skills2,1112026年10月8日 更新

Build, run, debug and ship 3D city games in Godot 4 — procedurally generated cities (block grids, districts, weighted building typologies, MultiMesh batching, facade shaders, terrain, day/night, landmarks), first-person controllers, headless verification, Blender-generated .glb assets, rigged character and animation packs, real OpenStreetMap-derived cities, WebAssembly export, and cloud GPU streaming on GCP. Use this skill whenever the work involves Godot or a .gd/.tscn/.gdshader/project.godot file; whenever someone wants to start, set up, clone onto a new machine, or stand up a 3D game or city generator; whenever they mention procedural city, city generator, block grid, building typology, MultiMesh, facade shader, terrain heightmap, navmesh, Godot export templates, export presets, headless Godot, .glb pipeline, Blender asset generation, character rigs or borrowed animations; and whenever they want to deploy or share a game — web export, SharedArrayBuffer/COOP/COEP, Selkies, pixel streaming, GPU VM, or "let people play this without installing anything." Reach for it even on vague asks like "get this running", "why is my city slow", "my model faces backwards", "make it work on a cloud machine", or "set this up somewhere else too" when a Godot 3D project is in play.

日本語の概要は準備中です。原文の説明を表示しています。

Leanmcp/gateway-skills2,1112026年10月8日 更新

Scaffold a native iOS app (SwiftUI, no dependencies) from nothing, run it in the Simulator, and archive + upload it to TestFlight entirely from the command line. Bundles working scripts for icon generation, simulator run, and signed upload via the App Store Connect API. Use this whenever the user wants to build, run, ship, or debug an iOS/iPhone/iPad app, mentions Xcode, SwiftUI, .xcodeproj, xcodebuild, simctl, provisioning, code signing, App Store Connect, TestFlight, archiving, or "get this on my phone" — and also when an existing iOS build is failing on icons, signing, teams, destinations, or duplicate build numbers.

日本語の概要は準備中です。原文の説明を表示しています。

Leanmcp/gateway-skills2,1112026年10月8日 更新

Leanmcp のスキルをすべて見る

このスキルの問題を報告する