← Back to blog

Hosted MCP Over SSE with curl and Python

September 11, 2026 · Eric · 6 min read

Agent Media Tools serves an MCP server at https://agentmediatools.com/api/mcp. Most MCP documentation stops at "paste this URL into your client". This post goes one layer down and drives the protocol by hand: open an SSE session with curl, read the sessionId the server hands you, POST JSON-RPC, and read the replies off the stream. Once you have seen that exchange, wiring it into Python is about forty lines — no MCP SDK required.

What the endpoint actually is

Step 1 — Open the SSE stream

export MT_KEY="mt_your_key_here"

# Keep this connection open. -N disables curl buffering.
curl -N -sS "https://agentmediatools.com/api/mcp" \
  -H "Authorization: Bearer $MT_KEY" | tee sse.log

Two lines come back immediately. The first is the event name, the second is the URL you must POST to:

event: endpoint
data: /api/mcp?sessionId=3f9c1d6e-6a2b-4b7a-9d1e-2c6f4b8a7d10

That sessionId is per-connection state held in memory. It is not a token you can reuse tomorrow, and it is not tied to your key — it identifies this transport instance.

Step 2 — Capture the session id

# second terminal: stream in the background, then pull the id out
curl -N -sS "https://agentmediatools.com/api/mcp" \
  -H "Authorization: Bearer $MT_KEY" > sse.log &

ENDPOINT=$(grep -m1 '^data: /api/mcp' sse.log | sed 's/^data: //')
SID="${ENDPOINT#*sessionId=}"
echo "$SID"

Step 3 — initialize, then send the notification

curl -sS -o /dev/null -w 'HTTP %{http_code}\n' \
  -X POST "https://agentmediatools.com/api/mcp?sessionId=$SID" \
  -H "Authorization: Bearer $MT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl-walkthrough","version":"0.1"}}}'

The response body is empty and the status is HTTP 202. The handshake result is now sitting on the SSE stream:

grep -o 'media-tool-mcp' sse.log | head -1
# → media-tool-mcp

Then confirm initialization. A notification has no id, so the server does not reply to it:

curl -sS -o /dev/null -X POST "https://agentmediatools.com/api/mcp?sessionId=$SID" \
  -H "Authorization: Bearer $MT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'

Two rules matter from here on. First, Content-Type: application/json is mandatory — the transport parses the body strictly and rejects anything else. Second, every POST needs the ?sessionId= of a live stream; if the stream has closed you get 404 MCP session not found and you have to reconnect and start over.

Step 4 — Read the tool catalog

curl -sS -o /dev/null -X POST "https://agentmediatools.com/api/mcp?sessionId=$SID" \
  -H "Authorization: Bearer $MT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'

# last SSE message received so far
last() { grep '^data: {' sse.log | tail -1 | sed 's/^data: //'; }
last | python3 -m json.tool | head -40

With the default server configuration tools/list returns 113 tool entries (the build defines 114; the easy_mode_execute meta-tool is only exposed when the Easy Mode intelligence layer is enabled). A local stdio deployment started with AMT_EASY_MODE=true exposes a much shorter list — the three control tools plus the optimized local workflows — while discovery still reaches the whole catalog.

ToolWhat it does
hash_textMD5 / SHA1 / SHA256 / SHA384 / SHA512 for a string
unit_convertLength, weight, temperature, volume, speed
resize_imageWidth, height, or percent on a public image URL
find_tools_easyPlain-language tool discovery with local / remote / sensitive labels
run_tool_easyOne consistent runner for anything discovery returned
run_workflow_easyChain up to 12 tools, referencing earlier results with $steps.ID.path

Step 5 — Call tools and read the results

Deterministic tools make the best first target because they need no credit and no file handling. Here is hash_text:

curl -sS -o /dev/null -X POST "https://agentmediatools.com/api/mcp?sessionId=$SID" \
  -H "Authorization: Bearer $MT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"hash_text","arguments":{"text":"hello","algorithm":"sha256"}}}'

last

The tool result is JSON-encoded inside a text content block, so the payload you parse looks like this:

{"success":true,"input":"hello","algorithm":"sha256","hash":"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824","length":64}

unit_convert works the same way, with a category so the unit table is unambiguous:

-d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"unit_convert","arguments":{"value":5,"from":"km","to":"mi","category":"length"}}}'
# → {"success":true,"value":5,"from":"km","to":"mi","result":3.1069,"category":"length"}

File tools take a public URL instead of an upload. resize_image fetches the image server-side (up to 20 MB, 30-second timeout), processes it, and returns a download path:

-d '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"resize_image","arguments":{"image_url":"https://example.com/photo.jpg","width":800,"format":"webp","quality":82}}}'
# → {"success":true,"filename":"a7f3c1d92b.webp","filesize":48213,"downloadUrl":"/downloads/a7f3c1d92b.webp"}

Prefix downloadUrl with https://agentmediatools.com to save the result from any HTTP client.

Step 6 — A Python client with requests

The only trick in Python is that the stream and the POSTs are two concurrent HTTP operations. One thread pumps SSE lines into a dictionary keyed by JSON-RPC id; the main thread posts messages and waits for the matching reply.

import json, threading, time, requests

BASE = "https://agentmediatools.com/api/mcp"
HEADERS = {"Authorization": "Bearer mt_your_key_here"}

class MCP:
    def __init__(self):
        self.replies, self.lock = {}, threading.Lock()
        self.stream = requests.get(BASE, headers={**HEADERS, "Accept": "text/event-stream"},
                                   stream=True, timeout=(10, 900))
        self.stream.raise_for_status()
        self.endpoint = self._read_endpoint()          # /api/mcp?sessionId=...
        self.post_url = BASE + "?sessionId=" + self.endpoint.split("sessionId=", 1)[1]
        threading.Thread(target=self._pump, daemon=True).start()

    def _read_endpoint(self):
        for line in self.stream.iter_lines(decode_unicode=True):
            if line and line.startswith("data: /api/mcp"):
                return line[len("data: "):]
        raise RuntimeError("endpoint event never arrived")

    def _pump(self):
        for line in self.stream.iter_lines(decode_unicode=True):
            if line and line.startswith("data: {"):
                msg = json.loads(line[len("data: "):])
                with self.lock:
                    self.replies[msg.get("id")] = msg

    def send(self, payload, wait=True, timeout=60):
        r = requests.post(self.post_url, headers={**HEADERS, "Content-Type": "application/json"},
                          json=payload, timeout=30)
        r.raise_for_status()                            # 202 Accepted
        if not wait:
            return None
        deadline = time.time() + timeout
        while time.time() < deadline:
            with self.lock:
                if payload.get("id") in self.replies:
                    return self.replies.pop(payload["id"])
            time.sleep(0.05)
        raise TimeoutError("no reply for id %s" % payload.get("id"))

    def call(self, name, arguments, rid):
        msg = self.send({"jsonrpc": "2.0", "id": rid, "method": "tools/call",
                         "params": {"name": name, "arguments": arguments}})
        return json.loads(msg["result"]["content"][0]["text"])

mcp = MCP()
mcp.send({"jsonrpc": "2.0", "id": 1, "method": "initialize",
          "params": {"protocolVersion": "2025-06-18", "capabilities": {},
                     "clientInfo": {"name": "python-walkthrough", "version": "0.1"}}})
mcp.send({"jsonrpc": "2.0", "method": "notifications/initialized"}, wait=False)

print(mcp.call("hash_text", {"text": "hello", "algorithm": "sha256"}, 2))
print(mcp.call("unit_convert", {"value": 5, "from": "km", "to": "mi", "category": "length"}, 3))

Handle two failure modes explicitly: a ReadTimeout or ConnectionError on the stream means the session is gone (idle timeout), so reconnect and re-run initialize; and a JSON-RPC reply carrying isError instead of result means the tool itself failed — surface that message rather than retrying the whole session.

Limits, guardrails, and error codes

SignalMeaning
401Missing or invalid Authorization: Bearer mt_… header; a revoked key returns 403
400POST without ?sessionId=, or a body that is not application/json
404Session unknown or already closed — reconnect to get a new sessionId
429 (GET)Too many concurrent streams (3 per API key, 10 per IP), or the key's daily limit is already exhausted
429 (POST)Daily limit reached; the SSE stream is closed at the same time
202Accepted — never treat this as the answer

Two metering details are worth knowing before you build a long-lived client. Opening a session logs a single usage entry against the key (mcp-connect), and every POST re-checks the key's daily limit before the message is dispatched. Free-plan keys default to 25 requests per day; Pro keys use the platform's 1,000-per-day limit. Sessions idle for 30 minutes are swept away, and a background sweeper runs every five minutes, so a client that sits unused overnight will find its sessionId stale.

When plain REST is the better tool

SSE is the right transport when the consumer is an MCP client — Claude, Hermes, Codex, or another agent runtime that expects a tool catalog. For a script, a cron job, or a webhook handler, the direct REST endpoints are shorter: one HTTP request, one JSON response, no session state to babysit. Both paths share the same key and the same daily limits, so you can mix them freely. If your agent already supports remote MCP, the fastest route is the client setup walkthrough in connecting Claude to the hosted MCP server, with the raw protocol here as the fallback when something misbehaves.

Try it in the Toolbox

Run the same tools in the browser, or call them from your agent with an API key.

Open toolbox