HaughtAI
HaughtAI

Build

Build a connector server

The protocol a custom server must speak, and how to host it.

What you are building

An MCP server is an ordinary HTTPS service that speaks JSON-RPC 2.0 over HTTP. You host it. A Connector is what that server becomes once it is reachable and published — until then it is yours alone, and you can use it in HaughtStudio without publishing anything.

Two ways to put one to work:

PrivatePublished
Where it is usedOnly by you, in HaughtStudioBy anyone, from HaughtStuff
The addressAnything reachable from the studio — LAN, tunnel, http://A public HTTPS address
Who authenticatesWhatever you configureThe key you are issued when you publish
What it costsNothingSet by you, in tokens

Start private. A server that answers one request from your own studio is the same server that passes the publish check — see Publish a Connector.

The four messages

Everything is one POST to a single path. The body is a JSON-RPC request; the answer is either JSON or an event stream, on that same response.

1. initialize

POST /mcp HTTP/1.1
Host: tools.example.com
Content-Type: application/json
Accept: application/json, text/event-stream

{"jsonrpc":"2.0","id":1,"method":"initialize",
 "params":{"protocolVersion":"2025-06-18","capabilities":{},
           "clientInfo":{"name":"HaughtAI","version":"1.0"}}}

Answer with a result carrying the protocol version you accept and the capabilities you have. This is the only handshake there is:

HTTP/1.1 200 OK
Content-Type: application/json

{"jsonrpc":"2.0","id":1,
 "result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},
           "serverInfo":{"name":"Weather","version":"1.0"}}}

If you want the client to keep a session, return an Mcp-Session-Id response header here. It is optional, and a stateless server should not ask for one. If you do return it, honour it on later requests.

2. notifications/initialized

A notification with no id, sent after the handshake. There is no reply. An empty 202 or a bare 200 is correct.

3. tools/list

{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
{"jsonrpc":"2.0","id":2,
 "result":{"tools":[
   {"name":"lookup_city",
    "description":"Look up the current weather for one city.",
    "inputSchema":{"type":"object",
                   "properties":{"city":{"type":"string","description":"City name, for example 'Oslo'."}},
                   "required":["city"]}}]}}

Every tool needs a non-empty name. The description is what the model reads when deciding whether to call it, so write it as a sentence about use, not as a restatement of the name. Offer at least one tool: a server that answers with none cannot be published.

4. tools/call

{"jsonrpc":"2.0","id":3,"method":"tools/call",
 "params":{"name":"lookup_city","arguments":{"city":"Oslo"}}}
{"jsonrpc":"2.0","id":3,
 "result":{"content":[{"type":"text","text":"7 °C and raining."}]}}

Three outcomes that look similar and mean different things:

  • The tool ran. A result. This is a completed call.
  • The tool ran and failed. A result with isError: true.
  • The tool was refused. A JSON-RPC error instead of a result.
{"jsonrpc":"2.0","id":3,
 "result":{"content":[{"type":"text","text":"Unknown city."}],"isError":true}}
{"jsonrpc":"2.0","id":3,
 "error":{"code":-32602,"message":"Unknown tool: lookup_city"}}

The distinction is not cosmetic: it decides whether the caller is charged. A result — including one carrying isError — is a call that happened. An error is a refusal, and nothing is charged.

JSON or an event stream

Either is accepted. A JSON body is simpler and is the right default. If you answer as SSE, use one data: line per message and close the response — a stream held open indefinitely will sit there until the client gives up:

HTTP/1.1 200 OK
Content-Type: text/event-stream

event: message
data: {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{}}}

Authentication

Use a bearer token in the Authorization header. That is the only form the client sends, and the only form the publish check will supply.

  • Compare in constant time. A length-varying comparison leaks the token a byte at a time.
  • Fail closed. If no token is configured, refuse every request with 503. The alternative — accepting everything — is a server that runs unauthenticated and nobody notices.
  • Answer 401 with a JSON body when the token is missing or wrong, and include a WWW-Authenticate header.

When you publish, you are issued a key. That key is what your server checks, and it is the value to compare against. It is shown once, on the pending screen, and can be replaced later.

if not CONNECTOR_KEY:
    return JSONResponse({"error": "unauthorized"}, status_code=503)

scheme, _, token = request.headers.get("authorization", "").partition(" ")
if scheme.lower() != "bearer" or not hmac.compare_digest(token.strip(), CONNECTOR_KEY):
    return JSONResponse({"error": "unauthorized"}, status_code=401,
                        headers={"WWW-Authenticate": 'Bearer'})

Stay stateless

Do not keep a call's state in memory between requests. A request may be answered by a different instance than the previous one, so an initialize on one instance and a tools/call on another will fail as an unknown session.

Three ways to be safe, in order of preference:

  1. Make every call self-contained. Take everything the tool needs in its arguments.
  2. Put state in shared storage — a database, a cache — keyed by something in the request.
  3. Return no session id and ignore the one a client sends. A stateless server that never issues a session cannot break on the second instance.

This is the single most common reason a server that works on a laptop fails once it is deployed. Long jobs make it worse — see Pitfalls.

A server you can run

A complete server, with the key check, the health route and both tools. Install mcp and uvicorn, then run it:

CONNECTOR_KEY=dev-secret PORT=8080 python mcp_server.py
"""A minimal MCP server, ready to publish as a Connector.

This file is the page. ``devdocs/views.py`` renders it verbatim into the sample
section of ``/docs/mcp/``, and ``tests/test_devdocs.py::TestTheSampleServer``
asserts that the page still shows this file rather than a stale copy of it. Edit
here, and the documentation moves with the code.

What it demonstrates, in the order the gateway exercises it:

* ``initialize``      -> a ``result`` with the protocol version and capabilities
* ``notifications/initialized`` -> accepted, no reply
* ``tools/list``      -> at least one tool, each with a name, a description and
                         an input schema
* ``tools/call``      -> a ``result`` on the SAME response, as JSON or as SSE

Three things a Connector must get right, and this file does:

1. **Bind to the address the platform gives you.** ``0.0.0.0`` and the injected
   port; see the ``__main__`` block at the foot.
2. **Stay stateless.** ``stateless_http=True`` means no per-instance session, so
   a request that lands on a different instance than the last one still works.
3. **Check the bearer token and fail closed.** An unset key refuses everything
   rather than accepting everything -- a server that silently runs unauthenticated
   is worse than one that is down.

Run it with:

    CONNECTOR_KEY=dev-secret PORT=8080 python mcp_server.py
"""

from __future__ import annotations

import hmac
import os

from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route

#: The Connector key. When a server is published, this is the value shown once
#: in the storefront's pending screen -- copy it from there into this variable.
CONNECTOR_KEY = os.environ.get("CONNECTOR_KEY", "")

#: Where the MCP endpoint lives. The storefront asks for the full address, so
#: this path is the last part of it: https://tools.example.com/mcp
MCP_PATH = "/mcp"

mcp = FastMCP(
    "Weather",
    instructions=(
        "A weather lookup. Call lookup_city with a city name. The answer is a "
        "single line of text, suitable to quote directly."
    ),
    # No session state, so any instance can answer any request.
    stateless_http=True,
    # A normal JSON body rather than a held-open stream. Long jobs are the one
    # reason to choose otherwise; see the docs page.
    json_response=True,
)


@mcp.tool()
async def lookup_city(city: str) -> dict:
    """Look up the current weather for one city.

    Call this when the user asks about conditions somewhere. The answer is a
    single sentence, so quote it rather than summarising it.

    Args:
        city: The city name as the user said it, for example 'Oslo'.
    """
    return {"ok": True, "city": city, "report": "7 °C and raining."}


class RequireConnectorKey(BaseHTTPMiddleware):
    """Refuse anything without the Connector key.

    The comparison is constant-time, and an unset key refuses every request: a
    server that cannot authenticate cannot tell a caller apart from anyone else,
    so serving anyway would hand out whatever the tools can reach.
    """

    async def dispatch(self, request, call_next):
        if not CONNECTOR_KEY:
            return JSONResponse(
                {"error": "unauthorized", "detail": "CONNECTOR_KEY is not set."},
                status_code=503,
            )

        presented = request.headers.get("authorization", "")
        scheme, _, token = presented.partition(" ")
        if scheme.lower() != "bearer" or not hmac.compare_digest(
            token.strip(), CONNECTOR_KEY
        ):
            return JSONResponse(
                {"error": "unauthorized", "detail": "A bearer token is required."},
                status_code=401,
                headers={"WWW-Authenticate": 'Bearer realm="weather"'},
            )

        return await call_next(request)


async def health(request):
    """A liveness answer for the platform's probe.

    ``/health`` rather than ``/healthz``: some front ends answer ``/healthz``
    themselves and never forward it to the container, which reads as a healthy
    service that was never asked.
    """
    return JSONResponse({"ok": True})


app = Starlette(
    routes=[
        Route("/health", health, methods=["GET"]),
        Mount("/", app=mcp.streamable_http_app()),
    ],
    middleware=[Middleware(RequireConnectorKey)],
)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=int(os.environ.get("PORT") or "8080"),
        log_level=os.environ.get("LOG_LEVEL", "info").lower(),
    )

Check it before connecting anything

Two requests. If both answer, the server is ready to connect:

curl https://tools.example.com/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'Authorization: Bearer YOUR_CONNECTOR_KEY' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize",
       "params":{"protocolVersion":"2025-06-18","capabilities":{}}}'
curl https://tools.example.com/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'Authorization: Bearer YOUR_CONNECTOR_KEY' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'

The Accept header is not optional. Without application/json in it, a conforming server is entitled to refuse the request — and one of the two clients in this ecosystem will not connect to a server that omits it. Send it even when you are only testing with curl.

Hosting

Any host that runs a container will do. Five things to get right wherever it runs:

WhatWhy
Bind 0.0.0.0 A process bound to loopback is unreachable from outside its own container, which looks exactly like a firewall.
Honour the injected port Most platforms tell you which port to listen on. Ignoring it means the health check fails and the revision never serves.
A health route at /health Some front ends answer /healthz themselves, so that path never reaches you. Use /health.
A request timeout above your slowest tool The platform will cut a request off before your tool finishes, and the caller sees a timeout rather than your answer.
Run as a non-root user Nothing in a tool server needs to write to the filesystem as root.

A minimal container

FROM python:3.12-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY mcp_server.py .
USER nobody

# The platform injects PORT. Nothing else is baked in.
EXPOSE 8080
CMD ["python", "mcp_server.py"]

Build and push the image rather than deploying a process from your laptop: a published Connector has to keep answering when the laptop is closed.

Pitfalls

SymptomCause
Connected locally, unreachable once deployed Bound to 127.0.0.1, or the platform's port was ignored.
"Unknown session" on the second call Session state held in instance memory. See Stay stateless.
The publish check times out but curl works No Accept header, or an event stream that never closes.
Every request refused on a newer SDK Newer SDKs enable host-header protection by default. Disable it or allow your public hostname explicitly.
Tools appear, then disappear The server stopped answering its tool list. A Connector is unpublished by a failed check, not kept alive by a previous success.
A 20-minute tool always times out A single long call. Use a start-then-poll pair — two short tools — rather than one long one.
The caller is charged for a failure Returning isError: true is still a completed call. To avoid a charge, refuse with a JSON-RPC error before doing the work.