跳到正文
DEV Community· Siftwright·· 47 分鐘前AI 評分61

如何只用 Python 標準庫連接 Siftwright 遠端 MCP 伺服器並免 API key 呼叫兩項工具

Talk to a remote MCP server with only the Python standard library (and call two tools without a key)

AI 導讀

Siftwright 遠端 MCP 伺服器可用約 60 行 Python 標準庫程式連接,並示範無需 API key 呼叫 domain_whois 和 pqc_scan。

正文

Most "connect your agent to MCP" guides start with installing an SDK and a client. But the protocol underneath a remote MCP server is just JSON-RPC over HTTPS POST. If you want to know what a server actually does before you wire it into Claude, Cursor or VS Code, you can talk to it with the Python standard library in about 60 lines.

This post does exactly that against a real server, https://siftwright.com/mcp. Two of its nine tools, domain_whois and pqc_scan, answer without an API key (one domain per call, with a free daily limit per network). That means every command below works as you read it. I ran all of them on 26 November 2026, and the outputs shown are from those runs.

The three calls that matter

A client needs three JSON-RPC methods:

  1. initialize: agree on a protocol version and learn the server's name.
  2. tools/list: get each tool's name, description and JSON Schema for its input.
  3. tools/call: run a tool with arguments.

Each one is a POST with Content-Type: application/json and an Accept header that allows both JSON and text/event-stream (the Streamable HTTP transport lets a server reply either way; this one replies with plain JSON).

You can check it with curl first:

curl -s https://siftwright.com/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq -r '.result.tools[].name'
youtube_transcript
website_screenshot
google_news
pqc_scan
contact_details
tech_stack
app_store_reviews
ats_jobs
domain_whois

The whole client (stdlib only)

"""Call a remote MCP server's tools with nothing but the Python standard library."""
import json
import os
import sys
import urllib.request

MCP_URL = "https://siftwright.com/mcp"
API_KEY = os.environ.get("SIFTWRIGHT_API_KEY")  # optional: keyless calls use the free trial


def rpc(method, params=None, _id=[0]):
    _id[0] += 1
    body = {"jsonrpc": "2.0", "id": _id[0], "method": method}
    if params is not None:
        body["params"] = params
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2025-06-18",
        # Cloudflare-fronted sites often refuse the default "Python-urllib" agent.
        "User-Agent": "stdlib-mcp-demo/1.0",
    }
    if API_KEY:
        headers["Authorization"] = f"Bearer {API_KEY}"
    req = urllib.request.Request(MCP_URL, json.dumps(body).encode(), headers)
    with urllib.request.urlopen(req, timeout=120) as resp:
        msg = json.load(resp)
    if "error" in msg:
        raise RuntimeError(msg["error"])
    return msg["result"]


def call_tool(name, arguments):
    result = rpc("tools/call", {"name": name, "arguments": arguments})
    # Tool results come back as content blocks; these tools put JSON in a text block.
    text = "".join(b.get("text", "") for b in result["content"] if b["type"] == "text")
    if result.get("isError"):
        raise RuntimeError(text)
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        return text


if __name__ == "__main__":
    info = rpc("initialize", {
        "protocolVersion": "2025-06-18",
        "capabilities": {},
        "clientInfo": {"name": "stdlib-demo", "version": "1.0"},
    })
    print("server:", info["serverInfo"]["title"], info["protocolVersion"])

    tools = rpc("tools/list")["tools"]
    print("tools:", ", ".join(t["name"] for t in tools))

    domain = sys.argv[1] if len(sys.argv) > 1 else "wikipedia.org"
    print(json.dumps(call_tool("domain_whois", {"domains": [domain]}), indent=2)[:1500])
    print(json.dumps(call_tool("pqc_scan", {"hosts": [domain]}), indent=2)[:1500])

Run it:

python3 mcp_try.py wikipedia.org

Trimmed output from my run:

server: Siftwright web data 2025-06-18
tools: youtube_transcript, website_screenshot, google_news, pqc_scan, contact_details, tech_stack, app_store_reviews, ats_jobs, domain_whois
{
  "mode": "free_trial",
  "results": [
    {
      "domain": "wikipedia.org",
      "source": "rdap",
      "registrar": "MarkMonitor Inc.",
      "createdAt": "2001-01-13T00:12:14.754Z",
      "expiresAt": "2027-01-13T00:12:14Z",
      "ageDays": 9448,
      "daysUntilExpiry": 47,
      "nameservers": ["ns0.wikimedia.org", "ns1.wikimedia.org", "ns2.wikimedia.org"],
      "dnssec": false,
      "dns": {
        "mx": [{"priority": 10, "host": "mx-in1001.wikimedia.org"}, ...],
        "spf": "v=spf1 include:_cidrs.wikimedia.org ~all",
        "dmarc": "v=DMARC1; p=reject; rua=mailto:dmarc-rua@wikimedia.org;",
        ...
{
  "mode": "free_trial",
  "results": [
    {
      "host": "wikipedia.org",
      "tls13": true,
      "pqKeyExchange": false,
      "groups": {"X25519MLKEM768": false, ..., "classical": "x25519"},
      "grade": {"letter": "D", "label": "Not quantum-safe yet", ...},
      ...

For comparison, pqc_scan on cloudflare.com in the same session returned pqKeyExchange: true, X25519MLKEM768: true, prefersPostQuantum: true and grade A+.

Four things I learned writing this

1. The default Python user agent got a 403. My first run failed with HTTP Error 403: Forbidden before reaching the MCP server at all. Many Cloudflare-fronted sites refuse requests whose User-Agent is Python-urllib/3.x. Setting any honest agent string (stdlib-mcp-demo/1.0) fixed it. If a remote MCP server works with curl but not from your script, check this first.

2. Tool results are content blocks, not raw JSON. tools/call returns {"content": [{"type": "text", "text": "..."}], "isError": ...}. These tools put a JSON document inside the text block, so the client joins the text blocks and tries json.loads. A model sees the same text, which is why small, structured output matters for context size.

3. Errors a model should read come back as isError: true, not as HTTP errors. Calling a key-only tool without a key returns HTTP 200 with:

This tool needs a Siftwright API key. Add the header "Authorization: Bearer sw_live_..." to your MCP client config. ...

That is the right design for agents: the model gets a readable reason instead of a transport failure. Your own client should check isError rather than rely on status codes.

4. Read the extra fields, not just results. When I passed two domains without a key, the server checked only the first and said so in a note field:

Free keyless trial: one host per call with a daily limit per network. Only the first of your 2 entries was checked. ...

A script that only reads results would silently miss the second domain.

Plugging the same server into an agent

Once the raw calls behave, adding the server to a client is one line or one small JSON block. I tested the protocol above directly. The client configs below follow each client's documented format for remote HTTP servers.

Claude Code:

claude mcp add --transport http siftwright https://siftwright.com/mcp

Cursor (~/.cursor/mcp.json):

{
  "mcpServers": {
    "siftwright": { "url": "https://siftwright.com/mcp" }
  }
}

VS Code (.vscode/mcp.json):

{
  "servers": {
    "siftwright": { "type": "http", "url": "https://siftwright.com/mcp" }
  }
}

Without a key, the agent can run domain_whois and pqc_scan on one domain at a time. The other seven tools (YouTube transcripts, screenshots/PDFs, Google News, contact details, tech stack, App Store reviews, ATS jobs) and list inputs need an API key, sent as an Authorization: Bearer ... header. Plans start at $29/month, and failed results are not counted. Details are at siftwright.com/web-data-for-ai-agents.

Reusing the client for other servers

Nothing in rpc() or call_tool() is specific to this server. Change MCP_URL, and the script will list and call tools on any remote MCP server that speaks Streamable HTTP and answers with plain JSON. Servers that stream text/event-stream responses or require an Mcp-Session-Id header from initialize need a few more lines, so check the response's Content-Type before calling json.load.

Disclosure: I work on Siftwright, the service used in the examples.

來源:DEV Community · dev.to