
Python web apps need very little to support WebMCP. The tool runs in the browser as a few lines of JavaScript, and your Django or FastAPI app does the real work behind it. New to the topic? Start with what WebMCP is.
A FastAPI endpoint
Query validation stops bad input before your code runs, and a response model limits what leaves the server:
from fastapi import APIRouter, Query
from pydantic import BaseModel
router = APIRouter()
class ProductOut(BaseModel):
name: str
price: float
url: str
@router.get('/agent/products', response_model=list[ProductOut])
async def search_products(q: str = Query(min_length=1, max_length=80)):
return await search_catalog(q, limit=5) # your own functionA Django view
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from .models import Product
@require_GET
def agent_products(request):
q = request.GET.get('q', '').strip()[:80]
if not q:
return JsonResponse({'error': 'missing_query'}, status=400)
items = Product.objects.filter(published=True, name__icontains=q)[:5]
return JsonResponse(list(items.values('name', 'price', 'slug')), safe=False)Add a rate limit too, for example at the proxy or with your framework’s throttling tools.
The browser script
Load this from your base template or frontend:
const mc = document.modelContext || navigator.modelContext;
if (mc && mc.registerTool) {
mc.registerTool({
name: 'search_products',
description: 'Search published products. Returns name, price and link.',
inputSchema: {
type: 'object',
properties: { q: { type: 'string', description: 'Keywords' } },
required: ['q'],
},
annotations: { readOnlyHint: true },
execute: async ({ q }) => {
const res = await fetch('/agent/products?q=' + encodeURIComponent(q));
return await res.text();
},
});
}Sessions, CSRF and permissions
Tools run in the page, so same-origin requests carry the visitor’s cookies, and login_required or your FastAPI dependencies work as usual. For POST tools in Django, send the csrftoken cookie in the X-CSRFToken header, and mark the tool with consequentialHint: true.
Safety rules
- Start read-only. Search and details first; mark them with
readOnlyHint. - Ask before acting. Mark cart, booking and form actions with
consequentialHint, so the visitor confirms. - Check on the server. The browser is not a security boundary, so validate every input and permission in your backend.
- Return little. Send only what a customer may see, never admin data or other customers’ records.
Test it
- Use a recent Chrome with WebMCP turned on, through the origin trial or the testing flag.
- Call each tool with good and bad inputs.
- Check that normal visitors see no change.
- Run the free WebMCP checker on the exact page where your tools live.
When an MCP server fits better
If AI apps should use your data without opening your site, build an MCP server instead. See WebMCP vs MCP and our MCP server development service. For the browser side, see our WebMCP integration services.
Frequently asked questions
Is there a Python library for WebMCP?
WebMCP is a browser API, so the tool itself is JavaScript. Python provides the endpoint behind it. For a server that AI apps connect to, use an MCP SDK instead.
How do I handle CSRF in Django?
For POST tools, read Django’s csrftoken cookie and send it in the X-CSRFToken header. Read-only GET tools do not need it.
Does this work with a separate frontend?
Yes. Register tools in your frontend and call your Python API. If it is on another domain, set up CORS and credentials carefully.
Should I build WebMCP or an MCP server in Python?
Choose WebMCP to help visitors on your site, using their session. Choose an MCP server for AI apps that connect without opening your site.
How we can help
- WebMCP Integration ServicesWebMCP development for any stack, from WordPress and Shopify to Next.js, Laravel and Django: search, FAQs and forms offered as secure tools for AI browser agents, with a free audit.
- Python & FastAPI DevelopmentHigh-performance Python backends and FastAPI microservices for SaaS, AI inference APIs, ETL pipelines, and event-driven systems.
- MCP Server Development ServicesCustom Model Context Protocol (MCP) servers that expose your APIs, databases, and internal tools to Claude, Cursor, ChatGPT, and any MCP-compatible AI.
Talk to an engineer about your project
Tell us what you are building. We reply within one business day with a candid view on scope, approach and effort.
Book a free strategy callWritten by the UnlockLive IT engineering team. UnlockLive IT Limited works with clients through its Los Angeles headquarters and Toronto office and delivers engineering from its Dhaka delivery centre. About us