
People increasingly ask an assistant before they open a search page. "Find me remote KYC jobs that need German" is a reasonable thing to type into a chat window, and the assistant will either guess, scrape something, or call a tool.
We run a job board with a public JSON API and a set of plain Markdown pages for crawlers. Both work, but neither is something an assistant can discover and use on its own. The Model Context Protocol fixes that: a client adds one URL, gets a list of typed tools with descriptions, and calls them.
This post is about putting a remote MCP server inside an existing FastAPI app. The server itself is under 200 lines. Most of the time went into routing, lifecycle and one security default.
What we wanted
The goals were deliberately narrow:
- No API key. The data is already public on the site, so authentication would only add friction.
- Read-only. No tool writes anything, so a confused model cannot post a job or touch an account.
- Same process as the website. No second service to deploy, monitor and keep in sync.
- Same answers as the website. If a person and an assistant search for the same thing, they should see the same jobs.
The last goal turned out to be the one we broke first.
The tools
We ended up with seven tools: search_jobs, get_job, market_stats, market_history, list_professions, get_profession and get_company. They map one-to-one onto pages and endpoints that already existed.
The Python SDK's FastMCP class makes a tool out of a typed function. The type hints become the JSON schema, and the docstring becomes the description the model reads.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP(
"Job board",
instructions="Tools return live data from an index of open jobs. "
"Cite the source page when you use the numbers.",
stateless_http=True,
json_response=True,
streamable_http_path="/",
)
@mcp.tool()
def search_jobs(query: str = "", department: str = "", country: str = "",
work_format: str = "", page: int = 1, limit: int = 20) -> dict:
"""Search open jobs. query matches title, company and tags
(e.g. 'VIP manager', 'KYC'); country: English name or 'Remote';
work_format: office / remote / hybrid. Up to 50 per page."""
limit = max(1, min(50, limit))
...
The docstring is the real interface. A model never reads your code, only that text, so we listed the valid department names right in it and gave two example queries. Before we did that, clients tended to invent department names that matched nothing.
Choosing return shapes
Two kinds of output came out of this.
Lists and numbers return dicts. search_jobs returns total, page, pages and a list of compact job objects with a stable url on each. The model can page through results and link the user to a specific job.
Long documents return Markdown strings. get_job, get_profession and get_company return the same Markdown we already serve to crawlers. Models handle headings and bullet lists better than a deeply nested JSON blob, and we did not have to write a second serializer.
@mcp.tool()
def get_job(job_id: int) -> str:
"""Full job posting as markdown."""
with SessionLocal() as db:
job = db.get(Job, int(job_id))
if not job or job.status not in ("approved", "archived"):
return f"Job {job_id} not found or no longer open."
text = job_markdown(job)
if job.status == "archived":
text = "> This job is archived (closed at the source).\n\n" + text
return text
Notice the "not found" path returns a sentence, not an exception. An exception reaches the model as a generic tool error. A sentence tells it what happened and lets it recover, for example by calling search_jobs again.
Archived jobs get the same treatment. Assistants often hold old links from earlier in a conversation, and "this job is closed" is a more useful answer than a 404.
Stateless, JSON responses
The Streamable HTTP transport supports sessions and server-sent event streams. We need neither: every tool is a quick database read that returns in one response.
stateless_http=True means each request stands alone, with no session id to track. json_response=True makes the server answer with a plain JSON body instead of opening an SSE stream. That keeps the endpoint friendly to proxies and load balancers that buffer or time out long-lived connections.
Mounting inside FastAPI
The SDK gives you an ASGI app. Mounting it looks like one line:
app.mount("/mcp", mcp.streamable_http_app())
It is not one line. Three things went wrong.
The trailing slash. Starlette's Mount("/mcp") matches /mcp/ and everything under it, but clients send the URL exactly as the user typed it: /mcp, no slash. The request fell through to the static file handler. A redirect would have been the obvious fix, but some clients do not follow a redirect on POST. So we added a small route for the bare path that rewrites the scope and calls the same app:
from starlette.routing import Route
class McpRoot:
async def __call__(self, scope, receive, send):
scope = dict(scope)
scope["root_path"] = scope.get("root_path", "") + "/mcp"
scope["path"], scope["raw_path"] = "/", b"/"
await mcp_app(scope, receive, send)
app.router.routes.insert(0, Route("/mcp", endpoint=McpRoot(),
methods=["GET", "POST", "DELETE"]))
app.mount("/mcp", mcp_app)
It goes at position 0 because our static site handler is registered as a catch-all and would otherwise win.
The session manager. Even in stateless mode, the transport needs its session manager running, and you start it with an async context manager. If you use the SDK's app directly, its lifespan handles that. Once you mount it inside another app, the inner lifespan never runs, and the first request fails.
We start it from the outer app's startup hook. There is one catch: run() may only be called once per manager instance. In production that is true. In tests, we build a TestClient(app) many times in one process, and the second one crashed with a RuntimeError. The fix resets the flag after a clean shutdown:
@app.on_event("startup")
async def mcp_start():
manager = mcp.session_manager
if getattr(manager, "_has_started", False):
manager._has_started = False # tests start the app many times
app.state.mcp_cm = manager.run()
await app.state.mcp_cm.__aenter__()
@app.on_event("shutdown")
async def mcp_stop():
cm = getattr(app.state, "mcp_cm", None)
if cm:
await cm.__aexit__(None, None, None)
Touching a private attribute is not pretty. It is isolated in one place, and it only matters when the app starts twice in one process.
The 421. Locally everything worked. On the public domain every request returned 421 Misdirected Request.
The SDK ships with DNS-rebinding protection turned on. It exists for a good reason: a server on localhost with access to your files should not answer a web page that tricks your browser into calling it. The protection allows only localhost Host headers, so a real domain is rejected.
Our server is public, holds no secrets and runs no actions, so we turned it off explicitly, with a comment explaining why:
from mcp.server.transport_security import TransportSecuritySettings
mcp = FastMCP(
...,
# Rebinding protection is for local servers: it only accepts
# localhost Host headers. We are a public, read-only server.
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=False),
)
If your MCP server can read private data or do anything on a user's behalf, do not copy this line. Keep the protection and add your real host to the allowed list instead.
Pin the SDK
In our first deploy the import failed on the server but not on a laptop. The requirement was mcp>=1.12, the server installed a fresh major version, and the class we imported had been renamed there. The same commit also dropped a constructor argument the older version did not accept.
We pinned mcp>=1.12,<2. The import is also wrapped in try/except ImportError, so if the package is missing, the website starts without the /mcp endpoint and logs one line. A broken optional integration should not take the whole site down.
One search path, not two
This is the bug from the goals section.
The first version of search_jobs did a substring match:
needle = query.strip().lower()
rows = [j for j in rows if needle in f"{j.title} {j.company} {j.tags}".lower()]
It was fine for a demo. Later the website got a proper search engine with FTS5, synonyms between Russian and English role names, country names and typo tolerance. The MCP tool kept its own little loop. For weeks an assistant asking for a role in Russian got zero results, while the same word on the site returned a full page.
The fix was to delete the loop and call the site's search module, then keep its ranking order:
if needle:
ranked = {job_id: i for i, job_id in
enumerate(search_engine.search_jobs(db, needle).ids)}
rows = sorted((j for j in rows if j.id in ranked),
key=lambda j: ranked[j.id])
The lesson is not about MCP. Any second entry point to the same data, whether an API, a bot, a feed or an MCP tool, will drift if it has its own copy of the query logic. Make every surface call the same function and test the agreement.
What we would do differently
- Write the tool docstrings first, as if they were the product page. They are what the model sees.
- Return Markdown for documents and small dicts for lists. Avoid giant nested JSON.
- Treat "not found" as a normal answer with a hint, not an exception.
- Test the endpoint on the public hostname early. Two of our three bugs were invisible on localhost.
- Never let a tool reimplement logic that already lives elsewhere in the app.
We use this at SpinHire, a job board for the iGaming industry: https://spinhire.io/mcp is the endpoint described above.
About the author
- SpinHire (spinhire.io) is a job board built only for the iGaming industry: casino, sports betting, game studios, affiliates, payments and compliance. We index 6,600+ live roles from 430+ companies every 6 hours and keep the data open: a public jobs API without a key (CC BY 4.0), XML and RSS feeds, and an MCP server for AI assistants. Here we write about building that index, iGaming tech careers and developer salaries.
Comments
Join the discussionNo comments yet. Be the first to comment.




