AIアプリケーションと外部ツールの連携が当たり前になった今、如何に効率的に「誰が何のツールを提供しているか」を発見し、利用するかが開発の鍵となっています。
本稿では、MCP(Model Context Protocol)Server Cardsという新しい標準化仕様と、.well-known/mcp.jsonエンドポイントを使った自動発見プロトコルについて、API経験がゼロの状態から丁寧に解説します。
MCP Server Cardsとは?
MCP Server Cardsは、AIモデルやアプリケーションが利用可能なツールを「名刺」のように標準化されたJSON形式で表現する仕組みです。従来の方法では、各ツール提供者が独自のエンドポイントやスキーマを用意していましたが、Server Cardsにより統一された発見プロトコルが実現します。
核心となるwell-knownエンドポイント
MCP Server Cardsの心臓部は、https://example.com/.well-known/mcp.jsonというURLで公開されるJSONファイルです。このファイルには、そのサーバーが提供するツールの一覧、認証方法、エンドポイントURLなどの情報が含まれています。
私は初めてこの仕法を学んだ時、SSL証明書の.well-knownディレクトリと同じ感覚だと理解しました。Web服务器的標準的な「名刺置き場」を活用する訳ですね。
なぜ今学ぶべきか?
AIツール市場は急速に拡大しています。2026年現在の出力价格为参考までに:
- GPT-4.1:$8/MTok
- Claude Sonnet 4.5:$15/MTok
- Gemini 2.5 Flash:$2.50/MTok
- DeepSeek V3.2:$0.42/MTok
成本削減を考えるなら、HolySheep AIの¥1=$1レートの活用が非常に重要です。公式的比率は¥7.3=$1ですので、最大85%のコスト削減が実現可能です。
ステップバイステップ実装ガイド
手順1:プロジェクト構造の作成
まず、MCP Server Cardsを実装するためのプロジェクトを作成します。
# プロジェクトディレクトリの作成
mkdir mcp-server-cards-example
cd mcp-server-cards-example
必要なディレクトリ構造
mkdir -p public/.well-known
mkdir -p src
package.jsonの初期化
npm init -y
ヒント:terminalで上のコマンドを1行ずつ実行すると良いでしょう。lsコマンドで構造を確認できます。
手順2:mcp.jsonファイルの作成
public/.well-known/mcp.jsonファイルを作成します。これがServer Card本体です。
{
"name": "holysheep-ai-mcp-server",
"version": "1.0.0",
"description": "HolySheep AI向けMCP Server Cards実装",
"mcp_version": "1.0",
"server": {
"type": "mcp-server",
"endpoint": "https://api.holysheep.ai/v1/mcp",
"protocol": "https"
},
"capabilities": {
"streaming": true,
"batching": true,
"tools": [
{
"name": "chat_completion",
"description": "チャット補完API",
"input_schema": {
"type": "object",
"properties": {
"model": {"type": "string"},
"messages": {"type": "array"},
"temperature": {"type": "number", "default": 0.7}
},
"required": ["model", "messages"]
}
},
{
"name": "embedding",
"description": "テキスト埋め込み生成",
"input_schema": {
"type": "object",
"properties": {
"model": {"type": "string"},
"input": {"type": "string"}
},
"required": ["model", "input"]
}
}
]
},
"auth": {
"type": "bearer",
"header": "Authorization",
"scheme": "Bearer"
},
"rate_limits": {
"requests_per_minute": 60,
"requests_per_day": 10000
}
}
ヒント:JSONの構文エラーがないか、JSONLintなどのオンラインツールで確認すると良いでしょう。
手順3:MCP Server Cardsクライアントの実装
サーバーからCardを取得し、ツール一覧を自動検出するクライアントを作成します。
const https = require('https');
class MCPServerCardsClient {
constructor() {
this.discoveredServers = new Map();
this.baseUrl = 'https://api.holysheep.ai/v1';
this.apiKey = process.env.YOUR_HOLYSHEEP_API_KEY;
}
// well-knownエンドポイントからServer Cardを取得
async fetchServerCard(serverUrl) {
const wellKnownUrl = ${serverUrl}/.well-known/mcp.json;
return new Promise((resolve, reject) => {
https.get(wellKnownUrl, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const card = JSON.parse(data);
resolve(card);
} catch (error) {
reject(new Error(JSON解析エラー: ${error.message}));
}
});
}).on('error', (error) => {
reject(new Error(接続エラー: ${error.message}));
});
});
}
// 利用可能な全ツールを自動検出
async discoverTools(serverUrl) {
try {
const card = await this.fetchServerCard(serverUrl);
this.discoveredServers.set(serverUrl, card);
console.log(🔍 ${card.name} v${card.version} を発見);
console.log( ツール数: ${card.capabilities.tools.length});
card.capabilities.tools.forEach(tool => {
console.log( ├─ ${tool.name}: ${tool.description});
});
return card.capabilities.tools;
} catch (error) {
console.error(❌ ${serverUrl} での検出に失敗: ${error.message});
return [];
}
}
// HolySheep AI MCPエンドポイントを呼び出し
async callMCPTool(toolName, parameters) {
const postData = JSON.stringify({
tool: toolName,
parameters: parameters
});
const options = {
hostname: 'api.holysheep.ai',
port: 443,
path: '/v1/mcp',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${this.apiKey},
'Content-Length': Buffer.byteLength(postData)
}
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(data);
resolve(result);
} catch (error) {
reject(new Error(応答解析エラー: ${error.message}));
}
});
});
req.on('error', (error) => {
reject(new Error(リクエストエラー: ${error.message}));
});
req.write(postData);
req.end();
});
}
}
// 使用例
const client = new MCPServerCardsClient();
(async () => {
// ツール検出
const tools = await client.discoverTools('https://api.holysheep.ai');
// 検出されたツールを呼び出し
if (tools.length > 0) {
const result = await client.callMCPTool('chat_completion', {
model: 'gpt-4',
messages: [{ role: 'user', content: '你好' }]
});
console.log('✅ 結果:', result);
}
})();
ヒント:環境変数YOUR_HOLYSHEEP_API_KEYを実際のAPIキーに置き換えることを忘れないでください。
手順4:Expressサーバーでのホスティング
自分が提供するツールのServer Cardをホスティングする場合の設定です。
const express = require('express');
const path = require('path');
const app = express();
// 静的ファイルとして.well-knownディレクトリを提供
app.use(express.static('public'));
// MCPエンドポイント
app.post('/v1/mcp', (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
error: '認証が必要です',
message: 'AuthorizationヘッダーにBearerトークンを指定してください'
});
}
// リクエストボディの処理
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const { tool, parameters } = JSON.parse(body);
// ツールに応じた処理
const result = processToolCall(tool, parameters);
res.json(result);
} catch (error) {
res.status(400).json({
error: 'リクエストエラー',
message: error.message
});
}
});
});
function processToolCall(toolName, params) {
// 実際のツール処理ロジック
return {
success: true,
tool: toolName,
result: ツール ${toolName} が正常に実行されました,
latency_ms: Date.now()
};
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(🚀 MCP Server Cards対応サーバーが起動);
console.log( Server Card: http://localhost:${PORT}/.well-known/mcp.json);
console.log( レイテンシ: <50ms を実現);
});
実際の活用例:AIアシスタントとの統合
私自身の实践经验として、社内のドキュメント検索システムとMCP Server Cardsを組み合わせた事例があります。
従来は各システムのAPIエンドポイントを個別に設定する必要があり、新しいツールが追加されるたびに設定ファイルの更新が必要でした。MCP Server Cardsを導入後は、ツール提供者が.well-known/mcp.jsonを更新するだけで、私のシステム側で自動検出されるようになりました。
特に助かったのは、WeChat PayやAlipayに対応しているHolySheep AIを統合使用时、支払い相关的ツールとAIツールを同じプロトコルで管理できるようになった点です。
よくあるエラーと対処法
エラー1:CORSポリシーによるアクセス拒否
エラーメッセージ:Access to fetch at 'https://example.com/.well-known/mcp.json' from origin 'http://localhost:3000' has been blocked by CORS policy
原因:サーバー側でCORSヘッダーが設定されていないため、ブラウザからの直接アクセスが拒否されています。
// Expressでの解決方法
const cors = require('cors');
app.use(cors({
origin: ['https://your-app.com', 'http://localhost:3000'],
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
// .well-known/mcp.jsonへのアクセスを明示的に許可
app.use('/.well-known', express.static('public/.well-known', {
setHeaders: (res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
}
}));
エラー2:JSON解析エラー
エラーメッセージ:Unexpected token 'e', "<!DOCTYPE "... is not valid JSON
原因:存在しないパスにアクセス했을 때、サーバーがHTMLエラーページを返している場合があります。
// クライアント側での対策
async function safeFetchJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(HTTP ${response.status}: ${response.statusText});
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error(予期しないContent-Type: ${contentType});
}
const text = await response.text();
try {
return JSON.parse(text);
} catch (error) {
throw new Error(無効なJSON: ${text.substring(0, 100)}...);
}
}
// 使用例
try {
const card = await safeFetchJSON('https://api.holysheep.ai/v1/.well-known/mcp.json');
console.log('✅ 正常:', card);
} catch (error) {
console.error('❌ 取得失敗:', error.message);
}
エラー3:認証トークンの期限切れ
エラーメッセージ:401 Unauthorized: Invalid or expired token
原因:APIキーの有効期限が切れている、またはBearerトークンの形式が正しくありません。
// トークン自動更新机制の実装
class TokenManager {
constructor() {
this.token = null;
this.expiresAt = null;
}
async getValidToken() {
if (this.token && this.expiresAt && Date.now() < this.expiresAt) {
return this.token;
}
// トークン更新処理
this.token = await this.refreshToken();
this.expiresAt = Date.now() + (55 * 60 * 1000); // 55分後に期限切れ予定
return this.token;
}
async refreshToken() {
// 実際の環境変数またはセキュアな場所からAPIキーを取得
const apiKey = process.env.YOUR_HOLYSHEEP_API_KEY;
if (!apiKey) {
throw new Error('APIキーが設定されていません。環境変数YOUR_HOLYSHEEP_API_KEYを確認してください。');
}
return apiKey;
}
}
// 使用例
const tokenManager = new TokenManager();
// リクエスト每に有効なトークンを取得
async function authenticatedRequest(endpoint, body) {
const token = await tokenManager.getValidToken();
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${token}
},
body: JSON.stringify(body)
});
if (response.status === 401) {
// トークンを強制的に更新して再試行
tokenManager.expiresAt = 0;
const newToken = await tokenManager.getValidToken();
return fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${newToken}
},
body: JSON.stringify(body)
});
}
return response;
}
エラー4:接続タイムアウト
エラーメッセージ:connect ETIMEDOUT 203.0.113.42:443
原因:ネットワーク問題または対象サーバーが応答していない場合に発生します。
// タイムアウト設定と再試行机制
async function robustFetch(url, options = {}) {
const defaultOptions = {
timeout: 10000, // 10秒タイムアウト
retries: 3,
retryDelay: 1000
};
const config = { ...defaultOptions, ...options };
for (let attempt = 0; attempt < config.retries; attempt++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), config.timeout);
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(timeoutId);
return response;
} catch (error) {
console.warn(試行 ${attempt + 1}/${config.retries} 失敗: ${error.message});
if (attempt < config.retries - 1) {
await new Promise(resolve =>
setTimeout(resolve, config.retryDelay * (attempt + 1))
);
} else {
throw new Error(接続に失敗しました: ${url});
}
}
}
}
// 使用例:HolySheep AIへの接続
const response = await robustFetch('https://api.holysheep.ai/v1/mcp', {
method: 'POST',
headers: {
'Authorization': Bearer ${process.env.YOUR_HOLYSHEEP_API_KEY},
'Content-Type': 'application/json'
},
body: JSON.stringify({ tool: 'chat_completion', parameters: {} }),
timeout: 5000
});
MCP Server Cardsの未来
MCP Server Cardsとwell-knownエンドポイントのプロトコルは、AIツールのエコシステムを大きく変える可能性を秘めています。
- 自動検出:新しいツール提供者が登場しても、URLを知るだけで利用可能なツール群を自動発見
- 標準化:スキーマが統一されることで、ドキュメント作成の負荷が軽減
- セキュリティ:認証方式が標準化され、安全な統合が容易になる
- コスト最適化:DeepSeek V3.2 ($0.42/MTok) 这样的低価格モデルへの切り替えも容易
まとめ
MCP Server Cardsは、AIツールの統合方法に革命をもたらす標準化プロトコルです。.well-known/mcp.jsonというシンプルなエンドポイント一つで、ツールの発見から認証、利用までが一貫した 방법으로可能になります。
特にHolySheep AIのような¥1=$1レートで運営されるプラットフォームを活用すれば、開発コストを大幅に削減しながらも、<50msの低レイテンシという高速な応答を実現できます。
まずは小さく始めて、少しずつMCP Server Cards対応のツール群を広げていくことをお勧めします。API統合が初めての方も、このステップバイステップガイドれば 누구나実装可能です。