概要
この章では、MCP(Model Context Protocol、モデルコンテキストプロトコル)サーバーの開発方法について解説します。 前章で学んだアーキテクチャの知識を活かし、実際にMCPサーバーを構築してClaude Desktopに接続するまでの流れを説明します。
MCPサーバーとは
MCPサーバーは、AIアプリケーションに機能を提供するプログラムです。 標準化されたプロトコルを通じて、Tools(ツール)、Resources(リソース)、Prompts(プロンプト)の3つのコアプリミティブを公開できます。
MCPサーバーが提供できる主な機能は以下のとおりです。
- 外部API連携 天気情報、データベース、Webサービスへのアクセス
- ファイルシステム操作 ファイルの読み書き、ディレクトリ管理
- 計算処理 データ分析、変換、集計
- カスタムワークフロー 業務固有の処理やタスク自動化
ローカルMCPサーバーは、stdioトランスポートを使用してClaude DesktopなどのMCPクライアントと通信します。 クライアントがサーバープロセスを起動し、標準入出力を通じてJSON-RPCメッセージを交換する仕組みです。
flowchart LR
subgraph Client["MCPクライアント"]
CD[Claude Desktop]
end
subgraph Server["MCPサーバー"]
Process[サーバープロセス]
Tools[Tools]
Resources[Resources]
Prompts[Prompts]
end
CD -->|"stdin(JSON-RPC)"| Process
Process -->|"stdout(JSON-RPC)"| CD
Process --> Tools
Process --> Resources
Process --> Promptsこの図は、Claude DesktopがMCPサーバーを子プロセスとして起動し、標準入出力でメッセージをやり取りする構成を示しています。
開発環境の準備
MCPサーバーを開発するには、使用する言語に応じた環境を準備する必要があります。
前提条件
ローカル開発には以下が必要です。
| 要件 | 説明 |
|---|---|
| Claude Desktop | MCPクライアントとして使用、macOS/Windows対応 |
| Node.js | TypeScript/JavaScript開発に必要(LTSバージョン推奨) |
| Python 3.10以上 | Python開発に必要(uvパッケージマネージャー推奨) |
| Python MCP SDK 1.2.0以上 | Python SDK使用時に必要(mcp[cli]パッケージ) |
Claude Desktopは公式サイトからダウンロードできます。
SDKの選択
MCPは10言語の公式SDKを提供しています。 各SDKは同等の機能を提供しつつ、言語固有のベストプラクティスに従って設計されています。
| 言語 | リポジトリ | Tier |
|---|---|---|
| TypeScript | modelcontextprotocol/typescript-sdk | Tier 1 |
| Python | modelcontextprotocol/python-sdk | Tier 1 |
| C# | modelcontextprotocol/csharp-sdk | Tier 1 |
| Go | modelcontextprotocol/go-sdk | Tier 1 |
| Java | modelcontextprotocol/java-sdk | Tier 2 |
| Rust | modelcontextprotocol/rust-sdk | Tier 2 |
| Swift | modelcontextprotocol/swift-sdk | Tier 3 |
| Ruby | modelcontextprotocol/ruby-sdk | Tier 3 |
| PHP | modelcontextprotocol/php-sdk | Tier 3 |
| Kotlin | modelcontextprotocol/kotlin-sdk | TBD |
SDKはTierによって分類されており、Tier 1は機能の完全性、プロトコルサポート、メンテナンスのコミットメントが最も高い水準にあります。 Tier 2は主要機能をサポートしつつ一部制限があり、Tier 3はコミュニティによるメンテナンスが中心です。
すべてのSDKは以下の機能をサポートしています。
- MCPサーバーの作成(Tools、Resources、Prompts)
- MCPクライアントの構築
- ローカル/リモートトランスポート
- 型安全なプロトコル準拠
この章では、利用頻度の高いPython、TypeScript、Goでの実装方法を解説します。
MCPサーバーの実装
実際にMCPサーバーを実装します。 天気情報を取得するシンプルなサーバーを例として、PythonとTypeScriptの両方で実装方法を示します。
PythonでFastMCPを使った実装
Python SDKには、FastMCPという高レベルAPIが含まれています。 デコレータベースの直感的な構文で、少ないコード量でMCPサーバーを構築できます。
プロジェクト作成
まず、プロジェクトディレクトリを作成し、依存関係をインストールします。
# プロジェクトディレクトリを作成
uv init weather
cd weather
# 仮想環境を作成して有効化
uv venv
source .venv/bin/activate
# 依存関係をインストール
uv add "mcp[cli]" httpx
# サーバーファイルを作成
touch weather.pyuvはPythonの高速パッケージマネージャーです。
mcp[cli]パッケージにはFastMCPとCLIツールが含まれ、httpxは非同期HTTPクライアントです。
Python MCP SDK 1.2.0以上が必要です。
ツールの実装
weather.pyファイルを作成し、天気予報を取得するツールを実装します。
from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP
# MCPサーバーを初期化
mcp = FastMCP("weather")
# 定数
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
async def make_nws_request(url: str) -> dict[str, Any] | None:
"""National Weather Service APIにリクエストを送信"""
headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
async with httpx.AsyncClient() as client:
try:
response = await client.get(url, headers=headers, timeout=30.0)
response.raise_for_status()
return response.json()
except Exception:
return None
def format_alert(feature: dict) -> str:
"""警報データを読みやすい文字列に変換"""
props = feature["properties"]
return f"""
イベント: {props.get("event", "不明")}
地域: {props.get("areaDesc", "不明")}
重大度: {props.get("severity", "不明")}
説明: {props.get("description", "説明なし")}
対応手順: {props.get("instruction", "特定の手順なし")}
"""
@mcp.tool()
async def get_alerts(state: str) -> str:
"""
米国の州の気象警報を取得します。
Args:
state: 2文字の州コード(例: CA, NY)
"""
url = f"{NWS_API_BASE}/alerts/active/area/{state}"
data = await make_nws_request(url)
if not data or "features" not in data:
return "警報データを取得できないか、警報が見つかりません。"
if not data["features"]:
return "この州には有効な警報はありません。"
alerts = [format_alert(feature) for feature in data["features"]]
return "\n---\n".join(alerts)
@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
"""
指定した緯度・経度の天気予報を取得します。
Args:
latitude: 緯度(例: 38.8894)
longitude: 経度(例: -77.0352)
"""
# まず地点情報を取得
points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
points_data = await make_nws_request(points_url)
if not points_data:
return "この地点の予報データを取得できませんでした。"
# 予報URLを取得して予報データを取得
forecast_url = points_data["properties"]["forecast"]
forecast_data = await make_nws_request(forecast_url)
if not forecast_data:
return "詳細な予報を取得できませんでした。"
# 予報を整形して返す
periods = forecast_data["properties"]["periods"]
forecasts = []
for period in periods[:5]: # 最初の5期間のみ
forecast = f"""
{period["name"]}:
気温: {period["temperature"]}°{period["temperatureUnit"]}
風: {period["windSpeed"]} {period["windDirection"]}
予報: {period["detailedForecast"]}
"""
forecasts.append(forecast)
return "\n---\n".join(forecasts)
def main():
mcp.run(transport="stdio")
if __name__ == "__main__":
main()このコードでは、@mcp.tool()デコレータを使って2つのツールを定義しています。
get_alertsは州コードから気象警報を取得し、get_forecastは緯度・経度から天気予報を取得します。
format_alertヘルパー関数で警報データを読みやすい形式に変換します。
関数のdocstringがツールの説明として自動的に使用されます。
サーバーの起動
サーバーを起動するには、以下のコマンドを実行します。
uv run weather.pyこのコマンドはMCPホストからのメッセージを待ち受けます。 開発・デバッグ時はMCP Inspectorを活用します(後述)。
TypeScriptでの実装
TypeScript SDKは、より詳細な制御が必要な場合に適しています。 型システムを活用した堅牢なサーバーを構築できます。
プロジェクト作成
プロジェクトを初期化し、必要なパッケージをインストールします。
# プロジェクトディレクトリを作成
mkdir weather
cd weather
# npmプロジェクトを初期化
npm init -y
# 依存関係をインストール
npm install @modelcontextprotocol/sdk zod@3
npm install -D @types/node typescript
# ソースディレクトリとファイルを作成
mkdir src
touch src/index.ts@modelcontextprotocol/sdkはMCP TypeScript SDKで、zodはスキーマ検証ライブラリです。
package.jsonに以下の設定を追加します。
{
"type": "module",
"bin": {
"weather": "./build/index.js"
},
"scripts": {
"build": "tsc && chmod 755 build/index.js"
},
"files": ["build"]
}type: "module"はESモジュール形式を有効にします。
binフィールドでCLIコマンドとして実行可能にします。
プロジェクトルートにtsconfig.jsonを作成します。
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}ツールの実装
src/index.tsファイルを作成し、サーバーを実装します。
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const NWS_API_BASE = "https://api.weather.gov";
const USER_AGENT = "weather-app/1.0";
// NWS APIへのリクエスト
async function makeNWSRequest<T>(url: string): Promise<T | null> {
const headers = {
"User-Agent": USER_AGENT,
Accept: "application/geo+json",
};
try {
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return (await response.json()) as T;
} catch (error) {
console.error("Error making NWS request:", error);
return null;
}
}
// 型定義
interface AlertFeature {
properties: {
event?: string;
areaDesc?: string;
severity?: string;
status?: string;
headline?: string;
};
}
interface AlertsResponse {
features: AlertFeature[];
}
interface PointsResponse {
properties: {
forecast?: string;
};
}
interface ForecastPeriod {
name?: string;
temperature?: number;
temperatureUnit?: string;
windSpeed?: string;
windDirection?: string;
shortForecast?: string;
}
interface ForecastResponse {
properties: {
periods: ForecastPeriod[];
};
}
// 警報データのフォーマット
function formatAlert(feature: AlertFeature): string {
const props = feature.properties;
return [
`イベント: ${props.event || "不明"}`,
`地域: ${props.areaDesc || "不明"}`,
`重大度: ${props.severity || "不明"}`,
`ステータス: ${props.status || "不明"}`,
`見出し: ${props.headline || "見出しなし"}`,
"---",
].join("\n");
}
// MCPサーバーを作成
const server = new McpServer({
name: "weather",
version: "1.0.0",
});
// get_alertsツールを登録
server.registerTool(
"get_alerts",
{
description: "米国の州の気象警報を取得します",
inputSchema: {
state: z
.string()
.length(2)
.describe("2文字の州コード(例: CA, NY)"),
},
},
async ({ state }) => {
const stateCode = state.toUpperCase();
const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
if (!alertsData) {
return {
content: [{ type: "text", text: "警報データの取得に失敗しました" }],
};
}
const features = alertsData.features || [];
if (features.length === 0) {
return {
content: [{ type: "text", text: `${stateCode}州に有効な警報はありません` }],
};
}
const formattedAlerts = features.map(formatAlert);
return {
content: [{ type: "text", text: formattedAlerts.join("\n") }],
};
}
);
// get_forecastツールを登録
server.registerTool(
"get_forecast",
{
description: "指定した緯度・経度の天気予報を取得します",
inputSchema: {
latitude: z.number().min(-90).max(90).describe("緯度(例: 38.8894)"),
longitude: z.number().min(-180).max(180).describe("経度(例: -77.0352)"),
},
},
async ({ latitude, longitude }) => {
const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
if (!pointsData) {
return {
content: [
{
type: "text",
text: `座標 ${latitude}, ${longitude} の地点データの取得に失敗しました(米国内の座標のみ対応)`,
},
],
};
}
const forecastUrl = pointsData.properties?.forecast;
if (!forecastUrl) {
return {
content: [{ type: "text", text: "予報URLの取得に失敗しました" }],
};
}
const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
if (!forecastData) {
return {
content: [{ type: "text", text: "予報データの取得に失敗しました" }],
};
}
const periods = forecastData.properties?.periods || [];
if (periods.length === 0) {
return {
content: [{ type: "text", text: "予報期間のデータがありません" }],
};
}
const formattedForecast = periods.map((period: ForecastPeriod) =>
[
`${period.name || "不明"}:`,
`気温: ${period.temperature || "不明"}°${period.temperatureUnit || "F"}`,
`風: ${period.windSpeed || "不明"} ${period.windDirection || ""}`,
`${period.shortForecast || "予報なし"}`,
"---",
].join("\n")
);
return {
content: [
{
type: "text",
text: `${latitude}, ${longitude} の予報:\n\n${formattedForecast.join("\n")}`,
},
],
};
}
);
// サーバーを起動
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Weather MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});TypeScript版では、McpServerクラスを使用してサーバーを作成し、server.registerTool()メソッドでツールを登録しています。
zodライブラリを使ってパラメータのスキーマを定義し、型安全性を確保しています。
formatAlert関数で警報データを整形します。
サーバーの起動
TypeScriptをコンパイルして実行します。
npm run buildこのコマンドはTypeScriptをコンパイルし、build/index.jsを生成します。
Claude Desktopからはこのビルド済みファイルを実行します。
GoでのMCPサーバー実装
Go SDKは、静的型付けとシンプルな並行処理を活かした堅牢なMCPサーバーを構築できます。 Tier 1 SDKとして分類されており、本番環境での使用に適した安定性を持ちます。
プロジェクト作成
プロジェクトを初期化し、MCP Go SDKをインストールします。
# プロジェクトディレクトリを作成
mkdir weather-server-go
cd weather-server-go
# Goモジュールを初期化
go mod init weather
# MCP Go SDKをインストール
go get github.com/modelcontextprotocol/go-sdk/mcp
# サーバーファイルを作成
touch main.goGo 1.24以上が必要です。
github.com/modelcontextprotocol/go-sdk/mcpがMCP公式Go SDKです。
データ構造とヘルパー関数の定義
main.goにパッケージとデータ構造を定義します。
package main
import (
"cmp"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
const (
NWSAPIBase = "https://api.weather.gov"
UserAgent = "weather-app/1.0"
)
type ForecastInput struct {
Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"`
Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"`
}
type AlertsInput struct {
State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"`
}
// NWS APIへのリクエストを送信するジェネリック関数
func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Accept", "application/geo+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
}
var result T
json.NewDecoder(resp.Body).Decode(&result)
return &result, nil
}GoのジェネリクスをAPIリクエストに活用し、型安全なレスポンス解析を実現しています。
cmp.Or()関数でnilセーフなデフォルト値を設定できます。
ツールの実装
ツール実行ハンドラを実装します。
func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) (
*mcp.CallToolResult, any, error,
) {
pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude)
pointsData, err := makeNWSRequest[struct {
Properties struct{ Forecast string `json:"forecast"` } `json:"properties"`
}](ctx, pointsURL)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: "天気情報を取得できませんでした"}},
}, nil, nil
}
forecastData, err := makeNWSRequest[struct {
Properties struct {
Periods []struct {
Name string `json:"name"`
Temperature int `json:"temperature"`
TemperatureUnit string `json:"temperatureUnit"`
DetailedForecast string `json:"detailedForecast"`
} `json:"periods"`
} `json:"properties"`
}](ctx, pointsData.Properties.Forecast)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: "予報データを取得できませんでした"}},
}, nil, nil
}
var forecasts []string
for i := range min(5, len(forecastData.Properties.Periods)) {
p := forecastData.Properties.Periods[i]
forecasts = append(forecasts, fmt.Sprintf("%s: %d°%s\n%s",
p.Name, p.Temperature, p.TemperatureUnit, p.DetailedForecast))
}
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: strings.Join(forecasts, "\n\n")}},
}, nil, nil
}
func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) (
*mcp.CallToolResult, any, error,
) {
alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, strings.ToUpper(input.State))
alertsData, err := makeNWSRequest[struct {
Features []struct {
Properties struct {
Event string `json:"event"`
AreaDesc string `json:"areaDesc"`
Severity string `json:"severity"`
} `json:"properties"`
} `json:"features"`
}](ctx, alertsURL)
if err != nil || len(alertsData.Features) == 0 {
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: "有効な警報はありません"}},
}, nil, nil
}
var alerts []string
for _, f := range alertsData.Features {
p := f.Properties
alerts = append(alerts, fmt.Sprintf("イベント: %s\n地域: %s\n重大度: %s",
cmp.Or(p.Event, "不明"), cmp.Or(p.AreaDesc, "不明"), cmp.Or(p.Severity, "不明")))
}
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: strings.Join(alerts, "\n\n---\n\n")}},
}, nil, nil
}サーバーの起動
mainf関数でサーバーを初期化し、stdioトランスポートで起動します。
func main() {
server := mcp.NewServer(&mcp.Implementation{
Name: "weather",
Version: "1.0.0",
}, nil)
mcp.AddTool(server, &mcp.Tool{
Name: "get_forecast",
Description: "指定した緯度・経度の天気予報を取得します",
}, getForecast)
mcp.AddTool(server, &mcp.Tool{
Name: "get_alerts",
Description: "指定した州の気象警報を取得します",
}, getAlerts)
if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
log.Fatal(err)
}
}ビルドして実行します。
go build -o weather .
./weatherClaude Desktopへの登録
ビルドしたバイナリをclaude_desktop_config.jsonに登録します。
{
"mcpServers": {
"weather": {
"command": "/絶対パス/weather-server-go/weather"
}
}
}Go版はコンパイル済みバイナリなので、Node.jsやPythonのランタイムが不要です。
設定ファイルにはcommandのみ指定し、argsは不要です。
Claude Desktopへの接続
開発したMCPサーバーをClaude Desktopに接続します。 設定ファイルを編集して、サーバーの起動コマンドを登録する必要があります。
設定ファイルの場所
Claude Desktopの設定ファイルは、OSによって異なる場所にあります。
| OS | 設定ファイルパス |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
設定ファイルが存在しない場合は、Claude Desktopの設定画面から「Developer」→「Edit Config」をクリックすると自動作成されます。
設定の記述例
設定ファイルにmcpServersオブジェクトを追加します。
以下はPythonサーバーを登録する例です。
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
"run",
"weather.py"
]
}
}
}commandにはuvの絶対パスを指定する必要がある場合があります。
which uv(macOS/Linux)またはwhere uv(Windows)で確認できます。
TypeScriptサーバーの場合は以下のように設定します。
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"]
}
}
}設定項目の説明は以下のとおりです。
- mcpServers サーバー設定のルートオブジェクト
- weather サーバーの識別名(任意の名前を設定可能)
- command サーバーを起動するコマンド
- args コマンドに渡す引数の配列
環境変数が必要な場合は、envフィールドを追加できます。
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["/path/to/server/dist/index.js"],
"env": {
"API_KEY": "your-api-key"
}
}
}
}この設定では、envフィールドにAPIキーを指定しています。
サーバープロセス起動時に環境変数として渡されるため、コード内でprocess.env.API_KEYのようにアクセスできます。
接続確認とトラブルシューティング
設定ファイルを保存したら、Claude Desktopを完全に終了して再起動します。 正常に接続されると、チャット入力欄の右下にMCPサーバーインジケータが表示されます。
接続に問題がある場合は、ログファイルを確認してください。
| OS | ログファイルの場所 |
|---|---|
| macOS | ~/Library/Logs/Claude/ |
| Windows | %APPDATA%\Claude\logs\ |
主なログファイルは以下のとおりです。
- mcp.log MCP接続に関する一般的なログ
- mcp-server-{サーバー名}.log 各サーバーのエラー出力
よくある問題と解決方法を以下に示します。
| 問題 | 原因 | 解決方法 |
|---|---|---|
| サーバーが表示されない | 設定ファイルの構文エラー | JSONの形式を確認 |
| 接続に失敗する | パスが間違っている | 絶対パスを使用 |
| ツールが動作しない | サーバーのエラー | ログファイルを確認 |
Windows環境でのENOENTエラー
Windowsでサーバーのログに${APPDATA}を含むパスのエラーが表示される場合は、claude_desktop_config.jsonのenvフィールドにAPPDATAの展開済みの値を明示的に設定する必要があります。
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["/path/to/server/dist/index.js"],
"env": {
"APPDATA": "C:\\Users\\username\\AppData\\Roaming\\"
}
}
}
}また、npxコマンドを使用する場合は、npmがグローバルにインストールされている必要があります。
%APPDATA%\npmフォルダが存在しない場合は、以下のコマンドでnpmをグローバルインストールしてください。
npm install -g npmMCP Inspectorによるデバッグ
MCP Inspectorは、MCPサーバーのテストとデバッグのための公式ツールです。 サーバーの動作を対話的に確認し、問題を特定できます。
Inspectorの起動
MCP Inspectorはnpxで直接実行できます。 インストールは不要です。
# Pythonサーバーをインスペクト
npx @modelcontextprotocol/inspector uv --directory /path/to/server run server.py
# TypeScriptサーバーをインスペクト
npx @modelcontextprotocol/inspector node /path/to/server/dist/index.jsnpmやPyPIで公開されているサーバーも直接インスペクトできます。
# npmパッケージをインスペクト
npx @modelcontextprotocol/inspector npx @modelcontextprotocol/server-filesystem /path/to/directory
# PyPIパッケージをインスペクト
npx @modelcontextprotocol/inspector uvx mcp-server-git --repository /path/to/repoこれらのコマンドにより、ローカルにインストールしていないパッケージでも直接テストできます。
機能の概要
MCP Inspectorは以下の機能を提供します。
flowchart TB
subgraph Inspector["MCP Inspector"]
Connection["Server Connection Pane<br/>トランスポート選択・環境設定"]
Resources["Resources Tab<br/>リソース一覧・内容確認"]
Prompts["Prompts Tab<br/>プロンプトテスト"]
Tools["Tools Tab<br/>ツール実行・結果確認"]
Notifications["Notifications Pane<br/>ログ・通知表示"]
end
Server[MCPサーバー] <--> Connection
Connection --> Resources
Connection --> Prompts
Connection --> Tools
Connection --> Notifications各機能の詳細は以下のとおりです。
- Server Connection Pane トランスポートの選択、コマンドライン引数と環境変数のカスタマイズ
- Resources Tab 利用可能なリソースの一覧表示、メタデータ確認、内容のインスペクション
- Prompts Tab プロンプトテンプレートの表示、カスタム引数でのテスト、生成メッセージのプレビュー
- Tools Tab ツール一覧とスキーマの表示、カスタム入力でのテスト実行、結果の確認
- Notifications Pane サーバーからのログ出力、リアルタイム通知の表示
開発ワークフロー
MCP Inspectorを活用した効率的な開発ワークフローを以下に示します。
-
開発開始 Inspectorでサーバーを起動し、基本的な接続を確認します。 Capability Negotiationが正常に完了することを確認します。
-
反復テスト コードを変更したらサーバーを再ビルドし、Inspectorで再接続します。 変更した機能をテストし、メッセージログを監視します。
-
エッジケースのテスト 以下のケースをテストして堅牢性を確認します。
- 無効な入力
- 必須パラメータの欠落
- 同時操作
- エラーハンドリングとレスポンス
セキュリティとベストプラクティス
MCPサーバーを開発する時は、セキュリティとベストプラクティスに注意が必要です。
ログ出力の注意点
stdioトランスポートを使用するローカルMCPサーバーでは、標準出力(stdout)がプロトコル通信に使用されます。 そのため、ログやデバッグ情報は必ず標準エラー出力(stderr)に出力してください。
# Python - 悪い例
print("デバッグ情報") # stdoutに出力され、プロトコルが破損する
# Python - 良い例(sys.stderrを指定)
import sys
print("デバッグ情報", file=sys.stderr)
# Python - 良い例(標準のloggingモジュールを使用)
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("デバッグ情報")// TypeScript - 悪い例
console.log("デバッグ情報"); // stdoutに出力される
// TypeScript - 良い例
console.error("デバッグ情報"); // stderrに出力されるstdoutへの出力はJSON-RPCメッセージとして解釈されるため、プロトコルエラーの原因となります。
認証と認可
ローカルMCPサーバーは、ユーザーのマシン上で実行されるため、通常はOAuth認証は不要です。 代わりに、以下の方法で認証情報を管理します。
| 方法 | 用途 | 例 |
|---|---|---|
| 環境変数 | APIキー、シークレット | API_KEY=xxx |
| 設定ファイル | 複雑な設定 | .env、config.json |
| システムキーチェーン | 機密情報の安全な保存 | macOS Keychain、Windows Credential Manager |
環境変数はclaude_desktop_config.jsonのenvフィールドで設定できます。
リモートMCPサーバーの場合は、OAuth 2.1に準拠した認証フローが必要です。 詳細は次章で解説します。
トークン管理
外部APIを呼び出すMCPサーバーでは、以下のベストプラクティスに従ってください。
- 短い有効期限 アクセストークンは数分から数時間で期限切れにする
- トークンの検証 リクエスト受信時に必ずトークンを検証する
- 安全な保存 トークンは暗号化して保存し、適切なアクセス制御を設定する
- ログへの出力禁止 認証情報、トークン、シークレットをログに出力しない
# 悪い例 - シークレットをログに出力
logging.info(f"API呼び出し: key={api_key}")
# 良い例 - シークレットを隠蔽
logging.info(f"API呼び出し: key=***")このコードでは、APIキーを***でマスクしてログに出力しています。
これにより、ログファイルが第三者に閲覧されても認証情報が漏洩するリスクを防げます。
まとめ
この章では、MCPサーバーの開発方法について解説しました。
- MCPサーバーの役割 AIアプリケーションにTools、Resources、Promptsを提供するプログラム
- SDK選択 10言語の公式SDKがあり、Python(FastMCP)、TypeScript、Goが代表的
- Python実装 FastMCPのデコレータベースAPIで簡潔に実装可能(SDK 1.2.0以上が必要)
- TypeScript実装
McpServerクラスと
registerTool()、zodによる型安全な実装 - Go実装 ジェネリクスを活用した静的型付けの実装、コンパイル済みバイナリでランタイム不要
- Claude Desktop接続
claude_desktop_config.jsonにサーバー設定を追加 - MCP Inspector 対話的なデバッグとテストのための公式ツール
- セキュリティ ログ出力先の注意、認証情報の安全な管理
Desktop Extensions(MCPB)
Desktop Extensionsは、MCPサーバーのインストールを簡単にする新しいパッケージング形式です。 従来の手動設定から、ワンクリックインストールへと変化させる技術です。
課題の解決
従来のMCPサーバーインストールには以下の課題がありました。
| 課題 | 影響 |
|---|---|
| 開発者ツール必須 | Node.js、Pythonなどのランタイムが必要 |
| 手動設定 | JSONファイルの編集が必要 |
| 依存関係管理 | パッケージの競合やバージョンの不一致 |
| 発見メカニズムの欠如 | 有用なMCPサーバーを見つけるのが困難 |
| 更新の複雑さ | 手動での再インストールが必要 |
Desktop Extensionsの特徴
Desktop Extensions(.mcpbファイル)は、これらの問題を解決します。
インストール方法
従来の方法
# Node.jsのインストールが必要
npm install -g @example/mcp-server
# JSONファイルの手動編集
# Claude Desktopの再起動
# 正常動作の祈りDesktop Extensions
.mcpbファイルをダウンロード- Claude Desktopでダブルクリック
- 「Install」をクリック
これだけで完了です。
アーキテクチャ
Desktop Extensionは、すべての必要なファイルを含むZIPアーカイブです。
extension.mcpb(ZIPアーカイブ)
├── manifest.json # 拡張機能のメタデータと設定
├── server/ # MCPサーバーの実装
│ └── [サーバーファイル]
├── dependencies/ # 必要なパッケージ/ライブラリ
└── icon.png # オプション:拡張機能のアイコンマニフェストファイル
最小限のmanifest.jsonの例を以下に示します。
{
"mcpb_version": "0.1",
"name": "my-extension",
"version": "1.0.0",
"description": "シンプルなMCP拡張機能",
"author": {
"name": "Extension Author"
},
"server": {
"type": "node",
"entry_point": "server/index.js",
"mcp_config": {
"command": "node",
"args": [
"${__dirname}/server/index.js"
]
}
}
}ユーザー設定
ユーザーからの設定値を収集する場合の例を以下に示します。
{
"user_config": {
"api_key": {
"type": "string",
"title": "APIキー",
"description": "認証用のAPIキー",
"sensitive": true,
"required": true
}
},
"server": {
"mcp_config": {
"env": {
"API_KEY": "${user_config.api_key}"
}
}
}
}Claude Desktopは以下を自動で行います。
- ユーザーフレンドリーな設定UIを表示
- 有効化前に入力を検証
- 機密値をOSのキーチェーンに安全保存
- サーバー起動時に設定値を環境変数として渡す
開発手順
Desktop Extensionの開発手順を以下に示します。
1. 初期化
npx @anthropic-ai/mcpb initこのコマンドは、サーバーについてのインタラクティブな質問を行い、完全なmanifest.jsonを生成します。
--yesパラメータで最小限のマニフェストを素早く生成することも可能です。
2. パッケージ化
npx @anthropic-ai/mcpb packこのコマンドは以下を実行します。
- マニフェストの検証
.mcpbアーカイブの生成
3. テスト
.mcpbファイルをClaude DesktopのSettings画面にドラッグして、以下を確認します。
- 拡張機能の人間が読める情報
- 必要な権限と設定
- シンプルな「Install」ボタン
オープンエコシステム
Desktop Extensionの仕様とツールチェーンはオープンソースです。
公開されるもの
- 完全なMCPB仕様
- パッケージング・検証ツール
- 参照実装コード
- TypeScript型・スキーマ
これにより以下が実現されます。
- MCPサーバー開発者向け 一度パッケージすれば、MCPBをサポートするあらゆる場所で実行
- アプリ開発者向け ゼロから構築することなく拡張機能サポートを追加
- ユーザー向け すべてのMCP対応アプリケーションで一貫した体験
セキュリティ考慮事項
Desktop Extensionsには複数のセキュリティ機能が組み込まれています。
ユーザー向け
- 機密データはOSキーチェーンに保存
- 自動更新機能
- インストールされた拡張機能の監査機能
企業向け
- Group Policy(Windows)とMDM(macOS)サポート
- 承認された拡張機能の事前インストール
- 特定の拡張機能や発行者のブロック
- 拡張機能ディレクトリの完全無効化
- プライベート拡張機能ディレクトリの展開
使用例
実際の使用例として、AnthropicではGameBoyエミュレーター用のDesktop Extensionを作成しました。 この拡張機能はPyBoyGameBoyエミュレータを開き、Claudeがゲームを制御できるようにします。
この例は、Desktop ExtensionsがローカルマシンのツールやアプリケーションとClaudeを接続する無限の可能性を示しています。
次章では、リモートMCPサーバーとDesktop Extensionsについて解説します。


