SONUB
JA English 한국어 日本語 中文 हिन्दी বাংলা اردو Español Português Français Deutsch Русский العربية Bahasa Indonesia Tiếng Việt ไทย Türkçe

通知を有効にする方法

このブラウザーまたはアドレスでは通知を利用できません。対応ブラウザーで安全な接続のSONUBサイトを開いてください。

通知がブロックされている場合は、ブラウザーの設定で許可してください。

  1. アドレスバー横のサイト設定、またはブラウザーのサイト設定を開き、このサイトの通知を許可に変更してください。
  2. 端末の設定でブラウザーの通知を許可し、おやすみモードや集中モードを確認してください。
  3. SONUBに戻ってページを再読み込みしてください。通知が有効になるとベルは表示されなくなります。

iPhoneやiPadではSONUBをホーム画面に追加し、そこから開いて通知を許可してください。

管理者 ログイン 表示テーマ 標準テーマ ダークテーマ ピンクテーマ チャット 1:1 チャット グループチャット 掲示板 お知らせ ニュース掲示板 ご意見掲示板 自己紹介 主要メニュー ログアウト

MCP(Model Context Protocol)

で小さな を作り、スクリプトで試します。メッセージを1つずつ追い、 につないだ設定の保存場所を見ます。

メッセージとトランスポート

とは 2.0 のメッセージで話します。(「何ができるの?」)や (「この値でこれをして」)のような小さな です。メッセージは2つの標準のトランスポート、stdio と のどちらかで行き来します。

メッセージが行き来する順番
  1. initialize あいさつしてバージョンを合わせます
  2. tools/list 何ができるの?
  3. tools/call この値でこれをして

stdio

が同じコンピューターでサーバーのを直接起動し、標準入力と標準出力で話します。自分のコンピューターで使うサーバーに向いています。

Streamable HTTP

サーバーがウェブアドレスで動き、たくさんのユーザーがインターネットでつながります。たくさんの人がいっしょに使うサービスに向いています。

手で作ったサーバーとクライアント

1. サーバーを作る — mcp-server.py

サーバー(mcp-server.py)は のだけを使うので、そのものが見えます。標準入力から JSON-RPC のメッセージを1行に1つずつ読み、標準出力に返事を1行に1つずつ書きます。

  • : クライアントがプロトコルのバージョンを伝えてあいさつします。サーバーは同じで答え、ツールを持っていることを伝え、自分の名前を名乗ります。
  • tools/list: サーバーはただ1つのツール strange-add を、説明と入力(a と b は数)と一緒に返します。
  • tools/call: サーバーは strange-add を実行し、結果をテキストで返します。
  • id のないメッセージは通知(notifications/initialized など)なので、サーバーは返事をしません。それ以外のリクエスト(ping など)には空の結果を返します。
mcp-server.py
"""
mcp-server.py: the smallest MCP server.
One tool, plain Python (standard library only), no SDK.

Who is who
  MCP server  This program. It offers tools (functions the AI
              may use).
  Host        The app the user talks to (Claude Code, Codex).
              It runs one MCP client for each connected server.
  MCP client  The part of the host that talks to this server
              with JSON-RPC messages (here over stdio: one JSON
              message per line).
  Model       The LLM (Claude Opus, GPT, ...). It never talks to
              the server directly. It only talks to the host.

Flow
  1. Discover tools
     The client asks for the tools (tools/list). The server replies
     with each tool's name, description and input schema.
  2. Offer tools
     The host sends the user's message to the model, together
     with the tool list.
  3. Model decides
     The model answers directly, or asks for a tool call
     (tool name + arguments). It never runs the tool itself.
  4. Call the tool
     The client sends the request to the server (tools/call).
  5. Run the tool
     The server runs the function and returns the result.
  6. Model continues
     The host gives the result back to the model. The model may
     call more tools (3-6 again) or write the final answer.

  Model             Host (MCP client)            MCP server
    |                    |  1. tools/list  ------>  |
    |                    |  <------  tool list      |
    | <-- 2. message + tool list                    |
    | 3. tool call -->   |                          |
    |                    |  4. tools/call  ------>  |
    |                    |  <------  5. result      |
    | <-- 6. result      |                          |

Rule for stdio servers: stdout carries protocol messages only.
Never print() anything else there. Write logs to stderr.
"""

import json
import random
import sys

SERVER_INFO = {"name": "strange-add-mcp", "version": "1.0.0"}

# The tool. The model reads the description to decide when to use it.
STRANGE_ADD = {
    "name": "strange-add",
    "description": "Add two numbers with a strange number.",
    "inputSchema": {
        "type": "object",
        "properties": {
            "a": {"type": "number"},
            "b": {"type": "number"},
        },
        "required": ["a", "b"],
    },
}


def strange_add(a, b):
    """Add a + b and a random number from 1 to 100 (always > a + b).

    The model cannot guess the answer, so a right answer proves
    that the tool was really called.
    """
    return a + b + random.randint(1, 100)


def handle(method, params):
    """Return the result for one request. Others (like ping) get {}."""
    if method == "initialize":
        # Use the client's protocol version and say "I have tools".
        return {
            "protocolVersion": params["protocolVersion"],
            "capabilities": {"tools": {}},
            "serverInfo": SERVER_INFO,
        }
    if method == "tools/list":
        return {"tools": [STRANGE_ADD]}
    if method == "tools/call":
        args = params["arguments"]
        total = strange_add(args["a"], args["b"])
        return {"content": [{"type": "text", "text": str(total)}]}
    return {}


def main():
    # One JSON-RPC message per line comes in, one reply per line goes out.
    for line in sys.stdin:
        request = json.loads(line)
        # No id means a notification: send no reply.
        if "id" not in request:
            continue
        result = handle(request["method"], request.get("params", {}))
        reply = {"jsonrpc": "2.0", "id": request["id"], "result": result}
        # flush=True sends the reply at once.
        print(json.dumps(reply), flush=True)


if __name__ == "__main__":
    main()

strange-add は a + b に 1〜100 の乱数を足します。はこの値を自分では計算できないので、2 + 3 の答えが 5 でなければ、ツールが本当に動いた証拠になります。stdout にはプロトコルのメッセージだけを流します — よけいな () が1つあるだけで会話がこわれるので、 stderr に書きましょう。print(..., =True) は返事を1つずつすぐに送り出します。

この手作りのサーバーは initialize で始まる方式(プロトコルのバージョン 2025-06-18)で話します。 などのクライアントは、この方式を今も受け付けます。最新の(2026-07-28)では、initialize のの代わりに、すべてのリクエストにバージョンをのせます。実際のサービスには、仕様に合わせてくれる公式の (Python の MCPServer、)を使いましょう。

2. クライアントで試す — mcp-client.sh

クライアント(mcp-client.sh)は、を使わずにホストの役をするスクリプトです。サーバーを起動し、セッション全体(initialize、initialized の通知、tools/list、tools/call、ping)を送って、返事を1つずつ確かめ、PASS か FAIL を表示します。終了コード 0 は、すべて通ったという意味です。エージェントにつなぐ前に、このようにサーバーを試しましょう。本物ののクライアントでは、モデルが次のくり返しに加わります。

  • ユーザーの質問とツールの一覧をモデルに送ります。
  • モデルがツールを使いたいと言ったら、クライアントが tools/call でサーバーのそのツールを呼びます。
  • 結果をモデルに返すと、モデルが最終的な答えを書きます。
mcp-client.sh
#!/bin/sh
# mcp-client.sh: the simplest MCP client, a shell script.
# It starts mcp-server.py, talks to it over stdio (one JSON-RPC
# message per line) and checks every reply.
# Exit code 0 means every check passed.

SERVER="python3 $(dirname "$0")/mcp-server.py"

# 1. Send the whole session at once and keep the replies.
#    id 1     initialize                 agree on a version
#    (no id)  notifications/initialized  "ready" (no reply)
#    id 2     tools/list                 which tools are there?
#    id 3     tools/call                 run strange-add(2, 3)
#    id 4     ping                       is the server alive?
replies=$(
  $SERVER <<'EOF'
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "shell-mcp-client", "version": "1.0.0"}}}
{"jsonrpc": "2.0", "method": "notifications/initialized"}
{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "strange-add", "arguments": {"a": 2, "b": 3}}}
{"jsonrpc": "2.0", "id": 4, "method": "ping"}
EOF
)

echo "--- Server replies ---"
echo "$replies"
echo "--- Checks ---"

failed=0

# 2. check <label> <reply id> <text the reply must contain>
check() {
  reply=$(echo "$replies" | grep -F "\"id\": $2,")
  if echo "$reply" | grep -qF "$3"; then
    echo "PASS   $1"
  else
    echo "FAIL   $1 (expected: $3)"
    failed=1
  fi
}

check "initialize: protocol version"  1 '"protocolVersion": "2025-06-18"'
check "initialize: server info"       1 '"serverInfo": {'
check "initialize: has tools"         1 '"capabilities": {"tools": {}}'
check "tools/list: strange-add"       2 '"name": "strange-add"'
check "ping: empty result"            4 '"result": {}'

# 3. strange-add adds a random 0 to 100,
#    so the answer only has to be >= 2 + 3.
total=$(echo "$replies" | grep -F '"id": 3,' |
  sed 's/.*"text": "\([0-9]*\)".*/\1/')
if [ "$total" -ge 5 ] 2>/dev/null; then
  echo "PASS   tools/call: strange-add(2, 3) >= 5 (got $total)"
else
  echo "FAIL   tools/call: strange-add(2, 3) >= 5 (got $total)"
  failed=1
fi

exit $failed

3. Claude Code につなぐ・外す

ターミナルで入力するコマンド
# put the two files above into one folder
mkdir -p ~/tmp/mcp && cd ~/tmp/mcp
#   mcp-server.py   mcp-client.sh

# 1) test the server without any AI
sh mcp-client.sh               # -> 6 x PASS, exit code 0

# 2) connect it to Claude Code (no --scope: the "local" scope)
claude mcp add strange-add -- python3 ~/tmp/mcp/mcp-server.py
claude mcp list                # strange-add: ... - Connected
claude mcp get strange-add     # Scope: Local config

# 3) where it was saved: NOT in this folder (no new file here)
#    ~/.claude.json -> projects -> "<this folder>" -> mcpServers
jq '.projects["'"$PWD"'"].mcpServers' ~/.claude.json

# 4) use it: start Claude Code in THIS folder
claude                         # "Use strange-add to add 2 and 3"
                               # -> not 5 (e.g. 61): the tool ran

claude mcp remove strange-add -s local

これらはこのページではなく、自分のパソコンやサーバーので実行します。実行する前に1行ずつ読みましょう。

出典

AIコースでもいっしょに学ぶ

AIコースの MCP チャプター — 目標・課題・進み具合

用語辞典

知らない言葉を選んでみましょう。やさしい説明と関連用語が見られます。

その用語はまだありません。

用語を選ぶと説明が表示されます。

読書ウィンドウ