mcpField
B
Boilerplate MCP Server

Boilerplate MCP Server

ローカル
github.com/aashari開発ツール7334 週間前に更新

Boilerplate MCP Server について

Boilerplate MCP Server は、TypeScript で MCP サーバーを作成するためのテンプレートです。ツール、リソース、プロンプトを含む IP 検索の例が付属しています。Node.js で新しい MCP 連携を始める開発者向けで、階層構造は他の API にも拡張できます。

主な機能

  1. 01CLI、ツール、リソース、サービスを分けた階層構造
  2. 02STDIO と Streamable HTTP の両トランスポートに対応
  3. 03Zod によるスキーマ検証と registerTool の記述方式
  4. 04ip-api.com を使った IP 検索の例とコマンド
  5. 05ツールのテストに使える MCP Inspector の連携

活用シーン

  1. 01TypeScript の新しい MCP サーバーをテンプレートから始める
  2. 02ツール、リソース、プロンプトの構成方法を学ぶ
  3. 03CLI と MCP Inspector で IP 検索ロジックを確認する

MCP 対応

本プロジェクトは MCP サーバーのテンプレートであり、例として IP 検索ツール、ip:// リソーステンプレート、プロンプトを MCP クライアントに公開します。STDIO または HTTP で実行できます。

設定

ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。

インストール方法は未掲載です

このサーバーのパッケージやリモートエンドポイントはまだ取得できていません。プロジェクトの README の手順に従ってください。

リポジトリ

ツール

ツール一覧はまだ取得されていません

ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。

詳細

Boilerplate MCP Server

TypeScript でカスタム Model Context Protocol(MCP)サーバーを開発するための、本番環境にも対応した基盤です。完全なレイヤードアーキテクチャのパターン、動作する実装例、そして AI アシスタントを外部 API やデータソースに接続するための包括的な開発者向けインフラストラクチャを提供します。

NPM Version License: ISC

最新の更新(2026年2月):MCP SDK 1.26.0 と Zod 4.3.6 に更新し、最新の registerTool パターンとストリーマブル HTTP の改善を継続して取り入れています。詳細は docs/MODERNIZATION.md を参照してください。

特長

  • セキュリティを最優先:DNS リバインディング対策、localhost のみへのバインド、安全なエラー処理
  • 2 種類のトランスポートに対応:STDIO とストリーマブル HTTP トランスポートに対応し、自動フォールバック機能を備えています
  • レイヤードアーキテクチャ:CLI、ツール、リソース、プロンプト、コントローラー、サービス、ユーティリティを明確に分離しています
  • 型安全性:Zod v4.3.6 によるスキーマ検証を備えた、完全な TypeScript 実装です
  • すべての MCP プリミティブに対応:ツール、リソース、プロンプト(例を含む)
  • ResourceLink パターン:大きなレスポンスに対する、トークン効率の高いリソース参照
  • TOON 出力形式:JSON よりもトークン数を 30~60%削減する、トークン指向オブジェクト表記法
  • JMESPath フィルタリング:レスポンスから必要なフィールドのみを抽出して、トークンコストを削減します
  • 生レスポンスのログ記録:大きな API レスポンスを /tmp/mcp/<project>/ に自動で記録し、切り詰めに関する案内も提供します
  • 最新の SDK:registerTool API パターンを採用した MCP SDK v1.26.0 を使用しています(v2 への移行に対応済み)
  • IP アドレスの完全な例:IP ジオロケーション向けのツール、リソース、プロンプト、CLI コマンド
  • 包括的なテスト:カバレッジレポート付きの単体テストと統合テスト(47 件のテストが成功)
  • 本番環境向けツール:ESLint、Prettier、semantic-release、MCP Inspector との統合
  • エラー処理:isError フィールドとコンテキストに応じたログ記録による、構造化されたエラー処理
  • セキュリティドキュメント:認証の実装ガイドを含む完全な SECURITY.md

MCP とは?

Model Context Protocol(MCP)は、AI システムを外部ツールやデータソースに安全に接続するためのオープンスタンダードです。このボイラープレートは、クリーンなレイヤードアーキテクチャで MCP 仕様を実装しており、あらゆる API やデータソース向けのカスタム MCP サーバーを構築できるよう拡張できます。

前提条件

クイックスタート

# Clone the repository
git clone https://github.com/aashari/boilerplate-mcp-server.git
cd boilerplate-mcp-server

# Install dependencies
npm install

# Build the project
npm run build

# Run in different modes:

# 1. CLI Mode - Execute commands directly
npm run cli -- get-ip-details 8.8.8.8
npm run cli -- get-ip-details                                            # Get your current IP
npm run cli -- get-ip-details 1.1.1.1 -e                                 # With extended data
npm run cli -- get-ip-details 8.8.8.8 --jq "{ip: query, country: country}"  # JMESPath filter
npm run cli -- get-ip-details 8.8.8.8 -o json                            # JSON output

# 2. STDIO Transport - For AI assistant integration (Claude Desktop, Cursor)
npm run mcp:stdio

# 3. HTTP Transport - For web-based integrations
npm run mcp:http

# 4. Development with MCP Inspector
npm run mcp:inspect                         # Auto-opens browser with debugging UI

トランスポートモード

STDIO トランスポート
  • stdin/stdout 経由の JSON-RPC 通信
  • Claude Desktop、Cursor AI、その他のローカル AI アシスタントで使用されます
  • 次のコマンドで実行します:TRANSPORT_MODE=stdio node dist/index.js
ストリーマブル HTTP トランスポート
  • Server-Sent Events(SSE)を使用する HTTP ベースのトランスポート
  • 複数の同時接続と Web 統合をサポートします
  • デフォルトではポート 3000 で実行されます(PORT 環境変数で設定可能)
  • MCP エンドポイント:http://localhost:3000/mcp
  • ヘルスチェック:http://localhost:3000/ → サーバーのバージョンを返します
  • 次のコマンドで実行します:TRANSPORT_MODE=http node dist/index.js

セキュリティ 🔒

このボイラープレートは、本番環境に対応したセキュリティ対策を実装しています。

✅ 組み込みの保護機能
  1. DNS リバインディング対策:Origin ヘッダーの検証により、悪意のあるウェブサイトが localhost サーバーにアクセスするのを防ぎます
  2. localhost のみへのバインド:サーバーは明示的に 127.0.0.1 にバインドされるため、ネットワーク経由ではアクセスできません
  3. 安全なエラー処理:エラーレスポンスには isError: true フラグが含まれ、機密情報は漏えいしません
🔐 セキュリティのベストプラクティス
  • ローカル開発:認証は不要です(localhost のみ+DNS リバインディング保護)
  • ネットワークへのデプロイ:認証が必須です。実装ガイドについては SECURITY.md を参照してください
  • 本番環境:mTLS、OAuth 2.0、またはベアラートークンを使用してください(詳しくは SECURITY.md を参照してください)

📖 セキュリティに関するドキュメント全体: SECURITY.md

🔍 セキュリティ監査レポート: docs/AUDIT-2025-01-13.md

出力形式

TOON 形式(デフォルト)

TOON(Token-Oriented Object Notation)は、LLM 向けに最適化された人間が読みやすい形式で、JSON と比較してトークン使用量を 30~60% 削減します。

status: success
query: 8.8.8.8
country: United States
city: Ashburn
lat: 39.03
lon: -77.5
JSON 形式

--output-format json を指定した場合の標準的な JSON 出力です。

{
  "status": "success",
  "query": "8.8.8.8",
  "country": "United States",
  "city": "Ashburn"
}
JMESPath フィルタリング

必要なフィールドのみを抽出してトークンコストを削減するには、--jq を使用してください。

# Extract specific fields
npm run cli -- get-ip-details 8.8.8.8 --jq "{ip: query, country: country}"

# Output:
# ip: 8.8.8.8
# country: United States

# Nested structure
npm run cli -- get-ip-details 8.8.8.8 --jq "{location: {city: city, coords: {lat: lat, lon: lon}}}"

フィルターの使用例については、JMESPath のドキュメントを参照してください。

アーキテクチャの概要

プロジェクト構成(クリックして展開)
src/
├── cli/                    # Command-line interfaces
│   ├── index.ts            # CLI entry point with Commander setup
│   └── ipaddress.cli.ts    # IP address CLI commands
├── controllers/            # Business logic orchestration  
│   ├── ipaddress.controller.ts    # IP lookup business logic
│   └── ipaddress.formatter.ts     # Response formatting
├── services/               # External API interactions
│   ├── vendor.ip-api.com.service.ts  # ip-api.com service
│   └── vendor.ip-api.com.types.ts    # Service type definitions
├── tools/                  # MCP tool definitions (AI interface)
│   ├── ipaddress.tool.ts   # IP lookup tool (inline content)
│   ├── ipaddress-link.tool.ts  # IP lookup with ResourceLink pattern
│   └── ipaddress.types.ts  # Tool argument schemas
├── resources/              # MCP resource definitions
│   └── ipaddress.resource.ts # IP lookup resource (URI: ip://address)
├── prompts/                # MCP prompt definitions
│   └── analysis.prompt.ts  # IP analysis prompt templates
├── types/                  # Global type definitions
│   └── common.types.ts     # Shared interfaces (ControllerResponse, etc.)
├── utils/                  # Shared utilities
│   ├── logger.util.ts      # Contextual logging system
│   ├── error.util.ts       # MCP-specific error formatting
│   ├── error-handler.util.ts # Error handling utilities
│   ├── config.util.ts      # Environment configuration
│   ├── constants.util.ts   # Version and package constants
│   ├── formatter.util.ts   # Markdown formatting and response truncation
│   ├── toon.util.ts        # TOON format encoding
│   ├── jq.util.ts          # JMESPath filtering
│   ├── response.util.ts    # Raw API response logging
│   └── transport.util.ts   # HTTP transport utilities
└── index.ts                # Server entry point (dual transport)

レイヤー構成

このボイラープレートは、保守性を高め、関心事を明確に分離する、6 つの異なるレイヤーで構成されるクリーンなレイヤーアーキテクチャに従っています。

1. CLI レイヤー(src/cli/)
  • 目的:ツールを直接使用・テストするためのコマンドラインインターフェース
  • 実装:コンテキストに応じたエラー処理を備えた、Commander ベースの引数解析
  • 例:get-ip-details [ipAddress] --include-extended-data --no-use-https
  • パターン:コマンドを登録 → 引数を解析 → コントローラーを呼び出す → エラーを処理
2. ツールレイヤー(src/tools/)
  • 目的:AI アシスタントが呼び出せる MCP ツールの定義
  • 実装:構造化されたレスポンスを伴う Zod スキーマ検証
  • 例:省略可能な IP アドレスと設定オプションを備えた ip_get_details ツール
  • パターン:スキーマを定義 → 引数を検証 → コントローラーを呼び出す → MCP レスポンスを整形
3. リソースレイヤー(src/resources/)
  • 目的:URI を介してアクセスできるコンテキストデータを提供する MCP リソース
  • 実装:パラメーター化された URI に対応する ResourceTemplate と registerResource API を使用
  • 例:IP の位置情報を提供する ip://{ipAddress} リソーステンプレート
  • パターン:URI テンプレートを登録 → 変数を抽出 → 整形したコンテンツを返す
4. コントローラーレイヤー(src/controllers/)
  • 目的:包括的なエラー処理を伴うビジネスロジックのオーケストレーション
  • 実装:オプションの検証、フォールバックロジック、レスポンスの整形
  • 例:HTTPS フォールバック、テスト環境の検出、API トークンの検証を伴う IP ルックアップ
  • パターン:入力を検証 → デフォルト値を適用 → サービスを呼び出す → レスポンスを整形
5. サービスレイヤー(src/services/)
  • 目的:ビジネスロジックを最小限に抑えた、外部 API との直接的なやり取り
  • 実装:構造化されたエラー処理を備えた HTTP トランスポートユーティリティ
  • 例:認証とフィールド選択に対応した ip-api.com API 呼び出し
  • パターン:リクエストを構築 → API を呼び出す → レスポンスを検証 → 生データを返す
6. ユーティリティレイヤー(src/utils/)
  • 目的:すべてのレイヤーで共有する機能
  • 主なコンポーネント:
    • logger.util.ts:コンテキスト付きログ(ファイル名・メソッド名のコンテキスト)
    • error.util.ts:MCP 固有のエラー整形
    • error-handler.util.ts:エラー処理とコンテキストの構築
    • transport.util.ts:リトライロジックを備えた HTTP/API ユーティリティ
    • config.util.ts:環境設定の管理
    • constants.util.ts:バージョンとパッケージの定数
    • formatter.util.ts:Markdown の整形とレスポンスの切り詰め
    • toon.util.ts:TOON 形式のエンコード(トークン効率の高い出力)
    • jq.util.ts:レスポンス変換のための JMESPath フィルタリング
    • response.util.ts:生の API レスポンスを /tmp/mcp/<project>/ に記録

開発者ガイド

開発スクリプト
# Build and Clean
npm run build               # Build TypeScript to dist/
npm run clean               # Remove dist/ and coverage/
npm run prepare             # Build + ensure executable permissions (for npm publish)

# CLI Testing
npm run cli -- get-ip-details 8.8.8.8                    # Test specific IP
npm run cli -- get-ip-details --include-extended-data    # Test with extended data
npm run cli -- get-ip-details --no-use-https             # Test with HTTP

# MCP Server Modes
npm run mcp:stdio           # STDIO transport for AI assistants
npm run mcp:http            # HTTP transport on port 3000
npm run mcp:inspect         # HTTP + auto-open MCP Inspector

# Testing
npm test                    # Run all tests (Jest)
npm run test:coverage       # Generate coverage report
npm run test:cli            # Run CLI-specific tests

# Code Quality
npm run lint                # ESLint with TypeScript rules
npm run format              # Prettier formatting
環境変数
コア設定
  • TRANSPORT_MODE: トランスポートモード(stdio | http、デフォルト:stdio)
  • PORT: HTTP サーバーのポート(デフォルト:3000)
  • DEBUG: デバッグログを有効にします(true | false、デフォルト:false)
  • NODE_ENV: Node の環境(development | production、デフォルト:development)
IP API の設定
  • IPAPI_API_TOKEN: ip-api.com の拡張データ用 API トークン(任意。無料プランを利用可能)
.env ファイルの例
# Core configuration
TRANSPORT_MODE=http
PORT=3000
DEBUG=true
NODE_ENV=development

# External API Keys
IPAPI_API_TOKEN=your_token_here
デバッグツール
  • MCP Inspector: MCP ツールをテストするためのビジュアルツール

    • npm run mcp:inspect でサーバーを起動します
    • ターミナルに表示された URL を開きます
    • ツールを対話的にテストします
  • デバッグログ: DEBUG=true 環境変数で有効にします

  • 生レスポンスのログ記録: 大きな API レスポンス(40,000 文字超)は自動的にログに記録されます

    • レスポンスは /tmp/mcp/<project-name>/ ディレクトリに保存されます
    • ファイル名の形式:<timestamp>-<random>.txt
    • リクエストの詳細、レスポンスデータ、パフォーマンス指標が含まれます
    • 省略されたレスポンスには、完全な生ファイルへのアクセス方法が記載されます
設定(クリックして展開)

~/.mcp/configs.json を作成します:

{
  "boilerplate": {
    "environments": {
      "DEBUG": "true",
      "TRANSPORT_MODE": "http",
      "PORT": "3000"
    }
  }
}

カスタムツールの作成

ツール実装の手順ガイド(クリックして展開)
1. サービスレイヤーを定義する

src/services/ に、ベンダー固有の命名パターンに従って新しいサービスを作成します:

// src/services/vendor.example-api.service.ts
import { Logger } from '../utils/logger.util.js';
import { fetchApi } from '../utils/transport.util.js';
import { ExampleApiResponse, ExampleApiRequestOptions } from './vendor.example-api.types.js';
import { createApiError, McpError } from '../utils/error.util.js';

const serviceLogger = Logger.forContext('services/vendor.example-api.service.ts');

async function get(
	param?: string,
	options: ExampleApiRequestOptions = {}
): Promise<ExampleApiResponse> {
	const methodLogger = serviceLogger.forMethod('get');
	methodLogger.debug(`Calling Example API with param: ${param}`);

	try {
		const url = `https://api.example.com/${param || 'default'}`;
		const rawData = await fetchApi<ExampleApiResponse>(url, {
			headers: options.apiKey ? { 'Authorization': `Bearer ${options.apiKey}` } : {}
		});

		methodLogger.debug('Received successful response from Example API');
		return rawData;
	} catch (error) {
		methodLogger.error('Service error fetching data', error);
		
		if (error instanceof McpError) {
			throw error;
		}
		
		throw createApiError(
			'Unexpected service error while fetching data',
			undefined,
			error
		);
	}
}

export default { get };
2. コントローラーを作成する

src/controllers/ に、エラーコンテキストを含むビジネスロジックを処理するコントローラーを追加します:

// src/controllers/example.controller.ts
import { Logger } from '../utils/logger.util.js';
import exampleService from '../services/vendor.example-api.service.js';
import { formatExample } from './example.formatter.js';
import { handleControllerError, buildErrorContext } from '../utils/error-handler.util.js';
import { ControllerResponse } from '../types/common.types.js';
import { config } from '../utils/config.util.js';

const logger = Logger.forContext('controllers/example.controller.ts');

export interface GetDataOptions {
	param?: string;
	includeMetadata?: boolean;
}

async function getData(
	options: GetDataOptions = {}
): Promise<ControllerResponse> {
	const methodLogger = logger.forMethod('getData');
	methodLogger.debug(`Getting data for param: ${options.param || 'default'}`, options);

	try {
		// Apply business logic and defaults
		const apiKey = config.get('EXAMPLE_API_TOKEN');
		
		// Call service layer
		const data = await exampleService.get(options.param, {
			apiKey,
			includeMetadata: options.includeMetadata ?? false
		});
		
		// Format response
		const formattedContent = formatExample(data);
		return { content: formattedContent };
		
	} catch (error) {
		throw handleControllerError(
			error,
			buildErrorContext(
				'ExampleData',
				'getData',
				'controllers/example.controller.ts@getData',
				options.param || 'default',
				{ options }
			)
		);
	}
}

export default { getData };
3. MCP ツールを実装する

登録パターンに従って、src/tools/ にツール定義を作成します:

// src/tools/example.tool.ts
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { Logger } from '../utils/logger.util.js';
import { formatErrorForMcpTool } from '../utils/error.util.js';
import exampleController from '../controllers/example.controller.js';

const logger = Logger.forContext('tools/example.tool.ts');

// Define Zod schema for tool arguments
const GetDataSchema = z.object({
	param: z.string().optional().describe('Optional parameter for the API call'),
	includeMetadata: z.boolean().optional().default(false)
		.describe('Whether to include additional metadata in the response')
});

async function handleGetData(args: Record<string, unknown>) {
	const methodLogger = logger.forMethod('handleGetData');
	
	try {
		methodLogger.debug('Tool example_get_data called', args);

		// Validate arguments with Zod
		const validatedArgs = GetDataSchema.parse(args);

		// Call controller
		const result = await exampleController.getData({
			param: validatedArgs.param,
			includeMetadata: validatedArgs.includeMetadata
		});

		// Return MCP-formatted response
		return {
			content: [
				{
					type: 'text' as const,
					text: result.content
				}
			]
		};
	} catch (error) {
		methodLogger.error('Tool example_get_data failed', error);
		return formatErrorForMcpTool(error);
	}
}

// Registration function using the modern registerTool API (SDK v1.23.0)
function registerTools(server: McpServer) {
	const registerLogger = logger.forMethod('registerTools');
	registerLogger.debug('Registering example tools...');

	// SDK best practices: 'title' for UI display name, 'description' for detailed info
	server.registerTool(
		'example_get_data',
		{
			title: 'Get Example Data',  // Display name for UI (e.g., 'Get Example Data')
			description: `Gets data from the Example API with optional parameter.
Use this tool to fetch example data. Returns formatted data as Markdown.`,
			inputSchema: GetDataSchema,
		},
		handleGetData
	);

	registerLogger.debug('Example tools registered successfully');
}

export default { registerTools };
4. CLI サポートを追加する

Commander パターンに従って、src/cli/ に CLI コマンドを作成します:

// src/cli/example.cli.ts
import { Command } from 'commander';
import { Logger } from '../utils/logger.util.js';
import exampleController from '../controllers/example.controller.js';
import { handleCliError } from '../utils/error.util.js';

const logger = Logger.forContext('cli/example.cli.ts');

function register(program: Command) {
	const methodLogger = logger.forMethod('register');
	methodLogger.debug('Registering example CLI commands...');

	program
		.command('get-data')
		.description('Gets data from the Example API')
		.argument('[param]', 'Optional parameter for the API call')
		.option('-m, --include-metadata', 'Include additional metadata in response')
		.action(async (param, options) => {
			const actionLogger = logger.forMethod('action:get-data');
			
			try {
				actionLogger.debug('CLI get-data called', { param, options });

				const result = await exampleController.getData({
					param,
					includeMetadata: options.includeMetadata || false
				});

				console.log(result.content);
			} catch (error) {
				handleCliError(error);
			}
		});

	methodLogger.debug('Example CLI commands registered successfully');
}

export default { register };
5. コンポーネントを登録する

エントリーポイントを更新し、新しいコンポーネントを登録します:

// 1. Register CLI in src/cli/index.ts
import exampleCli from './example.cli.js';

export async function runCli(args: string[]) {
	// ... existing setup code ...
	
	// Register CLI commands
	exampleCli.register(program);  // Add this line
	
	// ... rest of function
}

// 2. Register Tools in src/index.ts
import exampleTools from './tools/example.tool.js';

// In the startServer function, after existing registrations:
exampleTools.registerTools(serverInstance);
6. MCP リソースを追加する(任意)

最新の registerResource API を使用して、src/resources/ にリソースを作成します:

// src/resources/example.resource.ts
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Logger } from '../utils/logger.util.js';
import exampleController from '../controllers/example.controller.js';
import { formatErrorForMcpResource } from '../utils/error.util.js';

const logger = Logger.forContext('resources/example.resource.ts');

function registerResources(server: McpServer) {
	const registerLogger = logger.forMethod('registerResources');
	registerLogger.debug('Registering example resources...');

	// Use registerResource with ResourceTemplate for parameterized URIs (SDK v1.23.0)
	server.registerResource(
		'example-data',
		new ResourceTemplate('example://{param}', { list: undefined }),
		{
			title: 'Example Data',  // Display name for UI
			description: 'Retrieve example data by parameter'
		},
		async (uri, variables) => {
			const methodLogger = logger.forMethod('exampleResource');
			try {
				// Extract parameter from template variables
				const param = variables.param as string | undefined;

				methodLogger.debug('Example resource called', { uri: uri.href, param });

				const result = await exampleController.getData({ param });

				return {
					contents: [
						{
							uri: uri.href,
							text: result.content,
							mimeType: 'text/markdown'
						}
					]
				};
			} catch (error) {
				methodLogger.error('Resource error', error);
				return formatErrorForMcpResource(error, uri.href);
			}
		}
	);

	registerLogger.debug('Example resources registered successfully');
}

export default { registerResources };

IP アドレスの実装例

このボイラープレートには、すべてのレイヤーを紹介する IP アドレスのジオロケーション例が含まれています:

利用可能なツールとコマンド

CLI コマンド:

npm run cli -- get-ip-details                                            # Get current public IP (TOON format)
npm run cli -- get-ip-details 8.8.8.8                                    # Get details for specific IP
npm run cli -- get-ip-details 1.1.1.1 -e                                 # Short form with extended data
npm run cli -- get-ip-details 1.1.1.1 --include-extended-data           # Long form with extended data
npm run cli -- get-ip-details 8.8.8.8 --no-use-https                    # Force HTTP (for free tier)
npm run cli -- get-ip-details 8.8.8.8 -o json                            # JSON output (short form)
npm run cli -- get-ip-details 8.8.8.8 --output-format json              # JSON output (long form)
npm run cli -- get-ip-details 8.8.8.8 --jq "{ip: query, country: country}"  # JMESPath filtered output

MCP ツール:

  • ip_get_details - AI アシスタント向けの IP ジオロケーション検索
  • ip_get_details_link - 同じ検索結果に加え、リソースリンクを出力します(リソース対応クライアント向け)

両方のツールで共通のパラメーターを使用します:

  • ipAddress(任意):検索する IP アドレス(現在のデバイスのパブリック IP を使用する場合は省略)
  • includeExtendedData(任意、デフォルト:false):ASN、ホスト、組織のデータを含めます(API トークンが必要)
  • useHttps(任意、デフォルト:true):API 呼び出しに HTTPS を使用します
  • jq(任意):レスポンスをフィルタリング/変換する JMESPath 式
  • outputFormat(任意、デフォルト:"toon"):出力形式。「toon」または「json」

出力動作:

  • ip_get_details:text コンテンツブロックを 1 つ返します
  • ip_get_details_link:同じ最初の text ブロックに加え、resource_link ブロック(ip://<resolved-ip>)を返します

MCP リソース:

  • ip://{ipAddress} - IP 詳細のリソーステンプレート(例:ip://8.8.8.8、ip://1.1.1.1)
    • IP のジオロケーションデータを Markdown 形式で返します
    • トークン効率を高めるため、デフォルトで TOON 形式を使用します
紹介する機能
  • TOON 出力:トークン効率の高い形式(JSON よりトークン数を 30~60%削減)
  • JMESPath フィルタリング:必要なフィールドだけを抽出してコストを削減
  • フォールバックロジック:無料プランのユーザー向けに HTTPS から HTTP へフォールバック
  • 環境検出:テスト環境と本番環境で異なる動作
  • API トークンのサポート:拡張データ(ASN、モバイル検出など)用の任意のトークン
  • エラー処理:プライベート IP アドレスや予約済み IP アドレスに対する構造化エラー
設定オプション
# Optional - for extended data features
IPAPI_API_TOKEN=your_token_from_ip-api.com

# Development
DEBUG=true                    # Enable detailed logging
TRANSPORT_MODE=http          # Use HTTP transport
PORT=3001                    # Custom port

MCP サーバーの公開

  1. パッケージの詳細をカスタマイズする:

    {
      "name": "your-mcp-server-name",
      "version": "1.0.0", 
      "description": "Your custom MCP server",
      "author": "Your Name",
      "keywords": ["mcp", "your-domain", "ai-integration"]
    }
    
  2. ドキュメントを更新する: IP アドレスの例をユースケースに合わせたものに置き換えます。

  3. 十分にテストする:

    npm run build && npm test
    npm run cli -- your-command
    npm run mcp:stdio    # Test with MCP Inspector
    
  4. リリースする: Conventional Commits に準拠したコミットを main にプッシュすると、GitHub Actions(OIDC による信頼された公開)を通じて semantic-release が自動的に公開します。

テスト戦略

このボイラープレートには、包括的なテスト基盤が含まれています。

テスト構成
tests/               # Not present - tests are in src/
src/
├── **/*.test.ts     # Co-located with source files
├── utils/           # Utility function tests
├── controllers/     # Business logic tests  
├── services/        # API integration tests
└── cli/             # CLI command tests
テストのベストプラクティス
  • ユニットテスト:ユーティリティと純粋関数(*.util.test.ts)をテストします。
  • コントローラーテスト:サービス呼び出しをモックして、ビジネスロジックをテストします。
  • サービステスト:実際の、またはモックした HTTP 呼び出しで API 統合をテストします。
  • CLI テスト:コマンドの解析と実行をテストします。
  • テスト環境の検出:コントローラーでテストモードを自動的に処理します。
テストの実行
npm test                    # Run all tests
npm run test:coverage       # Generate coverage report  
npm run test:cli           # CLI-specific tests only
カバレッジの目標
  • 目標:テストカバレッジ >80%
  • ビジネスロジック(コントローラー)とユーティリティに重点を置きます。
  • 外部サービスを適切にモックします。

ライセンス

ISC ライセンス

MCP SDK v2 への準備

⚠️ 注:MCP SDK v2 は開発中です(2026 年第 1 四半期に安定版がリリースされる予定です)。このボイラープレートは、最小限の変更で移行できるよう準備されています。

v2 の主な変更点:

  • パッケージの分割:@modelcontextprotocol/server と @modelcontextprotocol/client
  • Express、Hono、Node.js HTTP 向けのオプションのミドルウェアパッケージ
  • コア API のパターンは同じです(このボイラープレートでは、すでに最新の API を使用しています)。

移行手順とスケジュールの詳細は、MODERNIZATION.md を参照してください。

リソースとドキュメント

MCP プロトコルのリソース
実装の参考資料
MCP サーバーのエコシステム

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。