jpskill.com
🛠️ 開発・MCP コミュニティ

MCP サーバー開発と運用

mcp-ops

Model Context Protocolサーバーの開発、ツール設計、リソース処理、転送設定を行うためのSkillです。

📜 元の英語説明(参考)

Model Context Protocol server development, tool design, resource handling, and transport configuration. Use for: mcp, model context protocol, mcp server, mcp tool, mcp resource, fastmcp, mcp transport, stdio, sse, streamable http, mcp inspector, tool handler, mcp prompt.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Model Context Protocolサーバーの開発、ツール設計、リソース処理、転送設定を行うためのSkillです。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o mcp-ops.zip https://jpskill.com/download/5917.zip && unzip -o mcp-ops.zip && rm mcp-ops.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/5917.zip -OutFile "$d\mcp-ops.zip"; Expand-Archive "$d\mcp-ops.zip" -DestinationPath $d -Force; ri "$d\mcp-ops.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して mcp-ops.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → mcp-ops フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

[Skill 名] mcp-ops

MCPオペレーション

PythonおよびTypeScriptでModel Context Protocolサーバーを構築、テスト、デプロイするための包括的なパターンです。

MCPアーキテクチャ早見表

┌─────────────────────────────────────────────────────────┐
│                     MCP Host                            │
│  (Claude Desktop, Claude Code, Custom App)              │
│                                                         │
│  ┌───────────┐   ┌───────────┐   ┌───────────┐        │
│  │  Client A  │   │  Client B  │   │  Client C  │       │
│  └─────┬─────┘   └─────┬─────┘   └─────┬─────┘        │
└────────┼───────────────┼───────────────┼────────────────┘
         │               │               │
    ┌────┴────┐     ┌────┴────┐     ┌────┴────┐
    │Transport│     │Transport│     │Transport│
    │ (stdio) │     │  (SSE)  │     │ (HTTP)  │
    └────┬────┘     └────┬────┘     └────┬────┘
         │               │               │
┌────────┴──┐     ┌──────┴────┐   ┌──────┴────┐
│  Server A  │     │  Server B  │   │  Server C  │
│            │     │            │   │            │
│ ┌────────┐ │     │ ┌────────┐ │   │ ┌────────┐ │
│ │ Tools  │ │     │ │Resources│ │   │ │Prompts │ │
│ └────────┘ │     │ └────────┘ │   │ └────────┘ │
│ ┌────────┐ │     │ ┌────────┐ │   │ ┌────────┐ │
│ │Resources│ │     │ │Prompts │ │   │ │ Tools  │ │
│ └────────┘ │     │ └────────┘ │   │ └────────┘ │
└────────────┘     └────────────┘   └────────────┘

Protocol: JSON-RPC 2.0 over chosen transport
Flow:     Client → request → Server → response → Client

サーバータイプ決定木

MCPサーバーに必要なトランスポートは何ですか?
│
├─ ローカルCLIツール / シングルユーザーデスクトップ統合ですか?
│  └─ stdio
│     - 最もシンプルなセットアップ、ネットワーク不要
│     - Claude Desktop、Claude Codeがネイティブサポート
│     - プロセスライフサイクルはホストが管理
│
├─ ウェブダッシュボード / ブラウザベースのクライアントですか?
│  └─ SSE (Server-Sent Events)
│     - HTTPベース、ファイアウォールを通過
│     - サーバー→クライアントイベント用の永続接続
│     - 開発および内部ツールに適しています
│
└─ 本番API / マルチテナント / クラウドデプロイメントですか?
   └─ ストリーミング可能なHTTP
      - リクエストにはHTTP POST、ストリーミングレスポンスにはSSEを使用
      - ステートレスおよびステートフルモードをサポート
      - 完全な認証サポート、ロードバランサーに優しい
      - 本番デプロイメントに推奨

ツール vs リソース vs プロンプト決定木

LLMは何をする必要がありますか?
│
├─ アクションまたは計算を実行しますか?
│  └─ TOOL
│     - 副作用があります (API呼び出し、ファイル書き込み、DB変更)
│     - 構造化された入力を受け取り、結果を返します
│     - 例: run_query, create_issue, send_email
│
├─ データまたはコンテキストを読み取りますか?
│  └─ RESOURCE
│     - 読み取り専用のデータ取得
│     - URI (file://, db://, api://) で識別されます
│     - 例: config://app, schema://users, file://readme.md
│
└─ LLMの動作またはワークフローをガイドしますか?
   └─ PROMPT
      - 引数付きのテンプレート化された指示
      - 会話の開始やワークフローを提案
      - 例: code_review(language, file), summarize(topic)

Python SDK クイックスタート

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("my-server")

@mcp.tool()
def search_docs(query: str) -> str:
    """Search documentation by keyword."""
    results = perform_search(query)
    return "\n".join(f"- {r.title}: {r.snippet}" for r in results)

@mcp.tool()
def create_ticket(title: str, body: str, priority: str = "medium") -> str:
    """Create a support ticket."""
    ticket = api.create(title=title, body=body, priority=priority)
    return f"Created ticket #{ticket.id}: {ticket.url}"

@mcp.resource("config://app")
def get_config() -> str:
    """Return current application configuration."""
    return json.dumps(load_config(), indent=2)

@mcp.resource("schema://db/{table}")
def get_table_schema(table: str) -> str:
    """Return the schema for a database table."""
    return json.dumps(get_schema(table), indent=2)

@mcp.prompt()
def code_review(language: str, filepath: str) -> str:
    """Generate a code review prompt for the given file."""
    return f"Review this {language} code in {filepath} for bugs, style issues, and performance."

if __name__ == "__main__":
    mcp.run()  # Defaults to stdio transport

インストールと実行:

uv init my-mcp-server && cd my-mcp-server
uv add mcp[cli]
# Run with: uv run python server.py
# Or:       uv run mcp run server.py

TypeScript SDK クイックスタート

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "my-server",
  version: "1.0.0",
});

// Register a tool
server.tool(
  "search_docs",
  "Search documentation by keyword",
  { query: z.string().describe("Search query") },
  async ({ query }) => {
    const results = await performSearch(query);
    return {
      content: [{ type: "text", text: results.join("\n") }],
    };
  }
);

// Register a resource
server.resource(
  "config",
  "config://app",
  { description: "Current application configuration" },
  async (uri) => ({
    contents: [{
      uri: uri.href,
      mimeType: "application/json",
      text: JSON.stringify(loadConfig(), null, 2),
    }],
  })
);

// Register a prompt
server.prompt(
  "code_review",
  "Generate a code review prompt",
  { language: z.string(), filepath: z.string() },
  async ({ language, filepath }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `Review this ${language} code in ${filepath} for bugs and style issues.`,
      },
    }],
  })
);

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}
main().catch(console.error);

インストールと実行:

npm init -y
npm install @modelcontextprotocol/sdk zod
npx tsx server.ts

トランスポート選択マトリックス

機能 stdio SSE ストリーミング可能なHTTP
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

MCP Operations

Comprehensive patterns for building, testing, and deploying Model Context Protocol servers in Python and TypeScript.

MCP Architecture Quick Reference

┌─────────────────────────────────────────────────────────┐
│                     MCP Host                            │
│  (Claude Desktop, Claude Code, Custom App)              │
│                                                         │
│  ┌───────────┐   ┌───────────┐   ┌───────────┐        │
│  │  Client A  │   │  Client B  │   │  Client C  │       │
│  └─────┬─────┘   └─────┬─────┘   └─────┬─────┘        │
└────────┼───────────────┼───────────────┼────────────────┘
         │               │               │
    ┌────┴────┐     ┌────┴────┐     ┌────┴────┐
    │Transport│     │Transport│     │Transport│
    │ (stdio) │     │  (SSE)  │     │ (HTTP)  │
    └────┬────┘     └────┬────┘     └────┬────┘
         │               │               │
┌────────┴──┐     ┌──────┴────┐   ┌──────┴────┐
│  Server A  │     │  Server B  │   │  Server C  │
│            │     │            │   │            │
│ ┌────────┐ │     │ ┌────────┐ │   │ ┌────────┐ │
│ │ Tools  │ │     │ │Resources│ │   │ │Prompts │ │
│ └────────┘ │     │ └────────┘ │   │ └────────┘ │
│ ┌────────┐ │     │ ┌────────┐ │   │ ┌────────┐ │
│ │Resources│ │     │ │Prompts │ │   │ │ Tools  │ │
│ └────────┘ │     │ └────────┘ │   │ └────────┘ │
└────────────┘     └────────────┘   └────────────┘

Protocol: JSON-RPC 2.0 over chosen transport
Flow:     Client → request → Server → response → Client

Server Type Decision Tree

What transport does your MCP server need?
│
├─ Local CLI tool / single-user desktop integration?
│  └─ stdio
│     - Simplest setup, no networking
│     - Claude Desktop, Claude Code native support
│     - Process lifecycle managed by host
│
├─ Web dashboard / browser-based client?
│  └─ SSE (Server-Sent Events)
│     - HTTP-based, works through firewalls
│     - Persistent connection for server→client events
│     - Good for development and internal tools
│
└─ Production API / multi-tenant / cloud deployment?
   └─ Streamable HTTP
      - HTTP POST for requests, SSE for streaming responses
      - Supports stateless and stateful modes
      - Full auth support, load balancer friendly
      - Recommended for production deployments

Tool vs Resource vs Prompt Decision Tree

What does the LLM need to do?
│
├─ Perform an action or computation?
│  └─ TOOL
│     - Has side effects (API calls, file writes, DB mutations)
│     - Accepts structured input, returns results
│     - Examples: run_query, create_issue, send_email
│
├─ Read data or context?
│  └─ RESOURCE
│     - Read-only data retrieval
│     - Identified by URI (file://, db://, api://)
│     - Examples: config://app, schema://users, file://readme.md
│
└─ Guide the LLM's behavior or workflow?
   └─ PROMPT
      - Templated instructions with arguments
      - Suggests conversation starters or workflows
      - Examples: code_review(language, file), summarize(topic)

Python SDK Quick Start

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("my-server")

@mcp.tool()
def search_docs(query: str) -> str:
    """Search documentation by keyword."""
    results = perform_search(query)
    return "\n".join(f"- {r.title}: {r.snippet}" for r in results)

@mcp.tool()
def create_ticket(title: str, body: str, priority: str = "medium") -> str:
    """Create a support ticket."""
    ticket = api.create(title=title, body=body, priority=priority)
    return f"Created ticket #{ticket.id}: {ticket.url}"

@mcp.resource("config://app")
def get_config() -> str:
    """Return current application configuration."""
    return json.dumps(load_config(), indent=2)

@mcp.resource("schema://db/{table}")
def get_table_schema(table: str) -> str:
    """Return the schema for a database table."""
    return json.dumps(get_schema(table), indent=2)

@mcp.prompt()
def code_review(language: str, filepath: str) -> str:
    """Generate a code review prompt for the given file."""
    return f"Review this {language} code in {filepath} for bugs, style issues, and performance."

if __name__ == "__main__":
    mcp.run()  # Defaults to stdio transport

Install and run:

uv init my-mcp-server && cd my-mcp-server
uv add mcp[cli]
# Run with: uv run python server.py
# Or:       uv run mcp run server.py

TypeScript SDK Quick Start

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "my-server",
  version: "1.0.0",
});

// Register a tool
server.tool(
  "search_docs",
  "Search documentation by keyword",
  { query: z.string().describe("Search query") },
  async ({ query }) => {
    const results = await performSearch(query);
    return {
      content: [{ type: "text", text: results.join("\n") }],
    };
  }
);

// Register a resource
server.resource(
  "config",
  "config://app",
  { description: "Current application configuration" },
  async (uri) => ({
    contents: [{
      uri: uri.href,
      mimeType: "application/json",
      text: JSON.stringify(loadConfig(), null, 2),
    }],
  })
);

// Register a prompt
server.prompt(
  "code_review",
  "Generate a code review prompt",
  { language: z.string(), filepath: z.string() },
  async ({ language, filepath }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `Review this ${language} code in ${filepath} for bugs and style issues.`,
      },
    }],
  })
);

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}
main().catch(console.error);

Install and run:

npm init -y
npm install @modelcontextprotocol/sdk zod
npx tsx server.ts

Transport Selection Matrix

Feature stdio SSE Streamable HTTP
Use case Local CLI tools, desktop Web dashboards, dev Production APIs
Protocol stdin/stdout pipes HTTP + EventSource HTTP POST + SSE
Auth support Env vars only Bearer tokens Full OAuth2/PKCE
Deployment Local process Single server Load balanced
Reconnection Process restart Auto-reconnect Stateless resilient
Multi-client 1:1 only Multiple clients Horizontally scalable
Firewall N/A (local) HTTP-friendly HTTP-friendly
State Process lifetime Connection lifetime Session or stateless
Best for Claude Desktop/Code Internal tools Cloud/enterprise

Authentication Patterns Quick Reference

# Pattern 1: API keys from environment
import os
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("api-server")

@mcp.tool()
def call_api(endpoint: str) -> str:
    """Call external API with configured credentials."""
    api_key = os.environ["MY_API_KEY"]  # Set in client config
    resp = httpx.get(f"https://api.example.com/{endpoint}",
                     headers={"Authorization": f"Bearer {api_key}"})
    return resp.text
# Pattern 2: OAuth2 token refresh (in-memory cache)
import time

_token_cache: dict = {}

async def get_valid_token() -> str:
    if _token_cache.get("expires_at", 0) > time.time() + 60:
        return _token_cache["access_token"]
    resp = await httpx.AsyncClient().post("https://auth.example.com/token", data={
        "grant_type": "refresh_token",
        "refresh_token": os.environ["REFRESH_TOKEN"],
        "client_id": os.environ["CLIENT_ID"],
    })
    data = resp.json()
    _token_cache.update({
        "access_token": data["access_token"],
        "expires_at": time.time() + data["expires_in"],
    })
    return data["access_token"]
// Claude Desktop config with env vars
{
  "mcpServers": {
    "my-server": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/server", "python", "server.py"],
      "env": {
        "MY_API_KEY": "sk-...",
        "DATABASE_URL": "postgresql://..."
      }
    }
  }
}

Common Gotchas

Gotcha Why Fix
Tool not appearing in client inputSchema has invalid JSON Schema Validate schema with jsonschema library; use Pydantic/Zod to generate
Tool returns raw object Results must be content list with typed items Always return {"content": [{"type": "text", "text": "..."}]}
Timeout on long operations Default client timeout is often 30-60s Add progress notifications; break into smaller operations
Concurrent requests fail Tool handler uses shared mutable state Use asyncio locks, or make handlers stateless
Large response crashes client MCP messages have practical size limits Paginate results; return summaries with detail-fetch tools
Error swallowed silently Exception in handler returns generic error Set isError: true in response; include error message in content
SSE connection drops No keep-alive or reconnection logic Implement heartbeat; client auto-reconnects on SSE
Client ignores new tools Capabilities not updated after tool change Call server.request_context.session.send_resource_list_changed()
Tool name collision Two servers register same tool name Namespace tools: myserver_search not just search
Resource URI too generic data://info is ambiguous Use specific schemes: db://myapp/users, config://myapp/settings
async def missing on handler FastMCP tools can be sync or async, but I/O should be async Use async def for any handler doing network/file I/O
Server works locally, fails in Claude Desktop Different working directory or PATH Use absolute paths; log os.getcwd() on startup

Reference Files

File Lines Content
references/server-architecture.md ~700 Server lifecycle, FastMCP/TS SDK setup, capabilities, middleware, error handling
references/tool-handlers.md ~650 Schema design, validation, return types, composition, side effects, examples
references/resources-prompts.md ~550 Resource URIs, static/dynamic resources, templates, prompts, subscriptions
references/transport-auth.md ~550 stdio/SSE/HTTP transports, session management, OAuth2, rate limiting, TLS
references/testing-debugging.md ~550 MCP Inspector, unit/integration testing, protocol debugging, CI, performance

See Also