SONUB
ZH-HANT 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)

用 親手做一個小型 ,再用 指令碼測試它。一條條跟著看和之間來往的訊息。然後把它連線到 ,看看設定儲存在哪裡。

訊息與傳輸方式

和用 2.0 訊息對話——像 (“你能做什麼?”)和 (“用這些值做這件事”)這樣的小段 。訊息透過兩種標準之一來往:stdio 或 。

訊息來往的順序
  1. initialize 打招呼並商定版本
  2. tools/list 你能做什麼?
  3. tools/call 用這些值做這件事

stdio

在同一臺電腦上啟動伺服器,透過標準對話。適合在你自己電腦上執行的伺服器。

Streamable HTTP

伺服器執行在一個網址上,很多使用者透過網際連線。適合很多人共用的服務。

親手做的伺服器和客戶端

1. 做伺服器——mcp-server.py

伺服器(mcp-server.py)只用 ,所以你能看到本身。它從標準輸入每行讀一條 JSON-RPC 訊息,並向標準輸出每行寫一條回覆:

  • :客戶端帶著協議版本打招呼。伺服器用同一個回答,說明自己有工具,並報出自己的名字。
  • tools/list:伺服器返回它唯一的工具 strange-add,附帶描述和輸入模式(a 和 b 是數字)。
  • tools/call:伺服器執行 strange-add,並把結果作為文字返回。
  • 沒有 id 的訊息是通知(比如 /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 只協議訊息——混進一個多餘的 () 就會破壞對話,所以要寫到 stderr。print(..., =True) 會把每條回覆立刻發出去。

這個手寫的伺服器使用以 initialize 開始的方式(協議版本 2025-06-18), 等客戶端仍然接受這種方式。(2026-07-28)不再用 initialize ,而是在每個請求裡帶上版本。做真正的服務時,請使用官方 (Python MCPServer、),它們會替你遵循規範。

2. 用客戶端測試——mcp-client.sh

客戶端(mcp-client.sh)是一個不需要任何 就能扮演主機角色的 指令碼。它啟動伺服器,傳送整個會話(initialize、initialized 通知、tools/list、tools/call、ping),逐條檢查回覆,並列印 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

這些命令在你自己的電腦或伺服器的裡執行,而不是在這個頁面上。執行前請逐行讀一遍。

出處

在 AI 課程裡一起學

AI 課程的 MCP 章節——目標 · 任務 · 進度

術語詞典

選一個你不認識的詞吧,可以看到簡單的解釋和相關術語。

還沒有匹配的術語。

選擇一個術語即可檢視解釋。

閱讀視窗