3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【保存版】ChatGPTでMCPを作成する

Posted at

TL;DR

  • MCP は「AI 用の USB-C」:LLM アプリ(ホスト)が外部のツール/データ(サーバー)へ標準手順でアクセスするためのプロトコル。データ層は JSON-RPC 2.0、通信は stdio または Streamable HTTP を使います(SSE は旧仕様から移行中)。(Model Context Protocol)
  • OpenAI でも一等席サポート:Agents SDK(TS/Python)から Hosted MCP / Streamable HTTP / stdio の3形態を扱えます。ホスト側(Responses API)が直接リモート MCP を叩く Hosted MCP は配線が最小。(OpenAI GitHub)
  • まずは動かす@modelcontextprotocol/sdk のクイックスタートや公式サーバー群(filesystem / git など)を npx/uvx で即試せます。(GitHub)
  • セキュリティ超重要:MCP は OAuth 2.1 ベースの認可仕様と Origin 検証・ローカルバインド 等の実装ガイドが用意されています(特に Streamable HTTP)。(Model Context Protocol)

MCP とは何か(1分で把握)

MCP は、LLM アプリ(ホスト)⇄ MCP サーバー間のやり取りを標準化するオープン・プロトコルです。サーバーは Tools / Resources / Prompts を公開し、クライアント(ホスト側の MCP クライアント)は */listtools/call 等の標準メソッドで発見・実行します。(Model Context Protocol)

MCP の参加者は以下の3つ:

  • MCP Host(例:Claude Desktop、VS Code 拡張、あなたのアプリ)
  • MCP Client(各サーバーと 1:1 で接続・管理するコンポーネント)
  • MCP Server(外部のツール/データを提供)
    この 1:1 モデルにより、ホストは複数サーバーを安全に束ねられます。(Model Context Protocol)

トランスポート(2025年版まとめ)

MCP のデータ層は JSON-RPC 2.0。通信(トランスポート)は 2 方式が標準です:

  • stdio:ローカル子プロセスと stdin/stdout で直結。オーバーヘッドが最小。
  • Streamable HTTP:HTTP POST+必要に応じて SSE でサーバー→クライアントのストリームを張る単一エンドポイント方式。2025-06-18 版HTTP+SSE 旧方式(2024-11-05)を置き換え。(Model Context Protocol)

実務的には、Cloudflare の最新ドキュメントが現場目線の要点を短くまとめていて便利:

  • 3つの言い方が混在:「stdio」「SSE(旧)」「Streamable HTTP(新)」
  • 現在は SSE→Streamable HTTP への移行期。両対応で運用する設計例も提示。(Cloudflare Docs)

OpenAI エコシステムでの使い分け(Agents SDK)

OpenAI Agents SDK からは次の 3 形態を選べます(TS も Python も同等の考え方):

  1. Hosted MCP server tools(ホスト側委任)
    Responses API が直接リモート MCPを叩き、結果をモデルにストリーム返却。アプリ側の配線が最小。(OpenAI GitHub)
  2. Streamable HTTP MCP servers(直結)
    自前のネットワーク制御や認証が必要なとき。再接続やツールリストキャッシュ等のオプションも充実。(OpenAI GitHub)
  3. stdio MCP servers(ローカル実行)
    npx @modelcontextprotocol/server-filesystem のようなローカル子プロセスと結ぶ最短ルート。(OpenAI GitHub)

まず動かす:最小サーバー & 接続

A. TypeScript で最小 MCP サーバー(stdio)

// package: @modelcontextprotocol/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: "demo-server", version: "1.0.0" });

server.tool("add", {
  description: "Add two numbers",
  inputSchema: z.object({ a: z.number(), b: z.number() }),
  execute: async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }] })
});

const transport = new StdioServerTransport();
await server.connect(transport);

公式 TypeScript SDK のクイックスタートをベースにした最小例。(GitHub)

試す(例)node main.mjs を Claude Desktop / Cursor の「ローカル MCP サーバー」設定から紐づけ。@modelcontextprotocol/server-filesystem 等の完成済みサーバーnpx で即利用可。(Model Context Protocol)


B. Python(FastMCP)で最小 MCP サーバー(stdio)

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Demo")

@mcp.tool()
def add(a: int, b: int) -> int:
    "Add two numbers"
    return a + b

if __name__ == "__main__":
    # uvx での実行例: uvx python main.py | stdio ホストから接続
    mcp.run_stdio()

公式 Python SDK(FastMCP)のクイックスタートを簡略化。uvx での実行も推奨されています。(GitHub)


C. OpenAI Agents SDK(TypeScript)から接続する

1) Hosted MCP(Responses API に委任)

import { Agent, hostedMcpTool, run } from "@openai/agents";

const agent = new Agent({
  name: "MCP Assistant",
  instructions: "Use MCP tools to answer.",
  tools: [
    hostedMcpTool({
      serverLabel: "gitmcp",
      serverUrl: "https://gitmcp.io/openai/codex",
      requireApproval: "never",
    }),
  ],
});

const result = await run(agent, "Which language is this repo written in?");
console.log(result.finalOutput);

Hosted MCP の基本形。承認フロー(HITL/onApproval)やコネクタ連携の例も SDK ドキュメントにあります。(OpenAI GitHub)

2) Streamable HTTP 直結

import { Agent, run, MCPServerStreamableHttp } from "@openai/agents";

const mcpServer = new MCPServerStreamableHttp({
  url: "https://example.com/mcp", // 単一エンドポイント
});

await mcpServer.connect();
const agent = new Agent({ name: "GitMCP Assistant", mcpServers: [mcpServer] });
const result = await run(agent, "Read project metadata");
console.log(result.finalOutput);
await mcpServer.close();

Streamable HTTP は単一エンドポイントで POST/GET を扱い、必要に応じて SSE ストリームで多段応答を返せます。(OpenAI GitHub)

3) stdio 直結

import { Agent, run, MCPServerStdio } from "@openai/agents";

const server = new MCPServerStdio({
  name: "FS",
  fullCommand: "npx -y @modelcontextprotocol/server-filesystem ./samples",
});
await server.connect();

const agent = new Agent({
  name: "FS Assistant",
  instructions: "Use files to answer.",
  mcpServers: [server],
});

const result = await run(agent, "List files");
console.log(result.finalOutput);

npx で公式 filesystem サーバーをすぐ叩けます。(OpenAI GitHub)


運用の落とし穴とベストプラクティス

1) 認可(Authorization)

  • 標準は OAuth 2.1。MCP サーバーは Protected Resource Metadata (RFC 9728) を実装し、認可サーバー位置を示す必要があります。実装者は OAuth 2.1/PKCE・動的クライアント登録等の既存標準に準拠しましょう。(Model Context Protocol)
  • 2025年の仕様更新で、リソース・インジケータやトークン取り扱いの明確化が進みました。(Auth0)

2) Streamable HTTP の安全策(超重要)

  • Origin ヘッダ検証、ローカル運用時は 127.0.0.1 バインド適切な認証 の実装を必須に。DNS リバインディング対策として明記されています。(Model Context Protocol)

3) ツール実行のガバナンス

  • Hosted/ローカル問わず、人手承認(HITL)やツール・フィルタリング(許可/禁止リスト、動的フィルタ)を活用して危険ツールの露出を抑制。Agents SDK に実装例あり。(OpenAI GitHub)

4) 既知のリスクに備える

  • サーバー数/採用が急拡大する中で、アイデンティティ管理や静的資格情報の漏洩は最大の脅威。短命トークン・最小特権・鍵のローテーションなど“いつもの基本”を徹底しましょう(ベストプラクティスや注意喚起は公式ガイドにも)。(Model Context Protocol)

デプロイの現実解:Cloudflare で両対応

SSE(旧)と Streamable HTTP(新)を併用し、クライアント側の移行を滑らかにする実装例が公開されています。Workers/OAuth 連携込みのサンプルも。段階移行の設計がイメージしやすいのでおすすめ。(Cloudflare Docs)


公式サーバー&エコシステムを活用

  • Example Servers 一覧:filesystem / git / memory など、そのまま使えるサーバーが多数。npx(TS)や uvx/pip(Python)で即導入可能。(Model Context Protocol)
  • クイックスタート:公式の手順で TS/Python どちらも数分でサーバー起動まで到達できます。(Model Context Protocol)

どれを選ぶ?(意思決定チャート)

  • 最短で外部サーバーを使いたいHosted MCP(Responses API にお任せ)(OpenAI GitHub)
  • 自社インフラでリモート配信したいStreamable HTTP(将来標準。SSE クラ兼用期間は両対応を)(Model Context Protocol)
  • ローカルで試したい / 社内限定stdio(一番シンプル)(OpenAI GitHub)

参考リンク(一次情報優先)

  • OpenAI(Agents SDK)MCP ガイド:TypeScript / Python(本記事のサンプルはここがベース)(OpenAI GitHub)
  • 公式仕様:「Transports(2025-06-18)」「Architecture」「Security Best Practices / Authorization」(Model Context Protocol)
  • 公式エコシステム:Examples(参考サーバー群)(Model Context Protocol)
  • OpenAI Platform(MCP ランディング)(OpenAI Platform)

おわりに

MCP は**「LLM × 外部世界」を安全・速やかに繋ぐための実務的な標準です。まずは stdio で最小サーバーを動かして感触を掴み、Hosted MCP で配線を最小化しつつ、将来的には Streamable HTTP へ寄せていく、という段階的導入が扱いやすいはず。セキュリティ設計だけは最初から本気**でいきましょう。(OpenAI GitHub)


付録:よくある質問(抜粋)

Q. SSE はもう使えない?
A. 旧仕様(HTTP+SSE)は後方互換のため併存可能ですが、Streamable HTTP が正式置き換えです。移行期間はクライアント事情により両対応が現実解。(Model Context Protocol)

Q. OpenAI の世界で “Hosted MCP” の利点は?
A. サーバー発見〜実行までを Responses API に委任でき、アプリ側の往復配線が減ります。HITL(人手承認)やツール・フィルタも併用可能。(OpenAI GitHub)

Q. 最低限やるべきセキュリティは?
A. Origin 検証/ローカルは 127.0.0.1/OAuth 2.1/短命トークン/最小特権。公式「Security Best Practices」「Authorization」をまず熟読。(Model Context Protocol)


3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?