django-native-mcp
django-native-mcp
Небольшой Django-нативный фреймворк для MCP-приложений и регистрации инструментов, вдохновлённый Celery.
Он делегирует обработку протокола, схемы, валидацию, сериализацию, stdio и Streamable HTTP
официальному mcp Python SDK.
Это не очередная обёртка вокруг FastMCP, зависимости — только нативный Python SDK
Установка
pip install django-native-mcpДобавьте приложение и его конфигурацию:
# settings.py
INSTALLED_APPS = [
# ...
"django_native_mcp",
]
DJANGO_NATIVE_MCP = {
"APP": "config.mcp:app",
}Создайте приложение:
# config/mcp.py
from django_native_mcp import MCP
app = MCP("backend")
app.autodiscover_tools()Объявите инструменты явно в установленных приложениях Django:
# orders/mcp.py
from django_native_mcp import shared_tool
from .models import Order
@shared_tool
async def get_order(order_id: int) -> dict:
"""Get an order."""
order = await Order.objects.aget(pk=order_id)
return {"id": order.pk, "status": order.status}Зарегистрированное имя — orders.get_order, используется метка приложения Django.
python manage.py mcp_list
python manage.py mcp_inspect orders.get_order
python manage.py mcp_call orders.get_order '{"order_id": 1}'
python manage.py mcp_serve --transport stdioИнструменты должны использовать async def. Фреймворк не добавляет неявные потоки или sync_to_async.
Related MCP server: django-mcp
Прямые инструменты приложения
from django_native_mcp import MCP
app = MCP("backend")
@app.tool(name="system.health")
async def health() -> dict:
return {"ok": True}@app.tool привязывается немедленно к одному приложению. @shared_tool остаётся независимым от приложения, пока автообнаружение не привяжет его.
Streamable HTTP с Django
Официальное ASGI-приложение SDK может обслуживаться самостоятельно:
application = app.asgi_app()Или маршрутизируйте /mcp на MCP, а всё остальное — на Django:
# config/asgi.py
import os
from django.core.asgi import get_asgi_application
from django_native_mcp.asgi import MCPApplication
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django_application = get_asgi_application()
# Import the MCP app only after Django's application registry is ready.
from config.mcp import app as mcp_app
application = MCPApplication(
django=django_application,
mcp=mcp_app,
mcp_path="/mcp",
)Диспетчер передаёт ASGI-lifespan официальному MCP-приложению, поэтому его жизненный цикл транспорта запускается и останавливается внешним ASGI-сервером.
Тестирование
Используйте тонкую обёртку вокруг официального внутрипроцессного клиента:
from django_native_mcp.testing import MCPTestClient
async with MCPTestClient(app) as client:
result = await client.call_tool("orders.get_order", {"order_id": 1})Сквозной пример
Каталог example/ содержит запускаемый проект Django, использующий встроенный auth User, конечную точку Streamable HTTP MCP и автономный клиент OpenAI Responses API, который обнаруживает и вызывает инструмент Django через MCP.
Архитектура
Django apps / mcp.py
↓
shared_tool → ToolDefinition → ToolRegistry → MCP
↓
official MCPServer
↙ ↘
stdio Streamable HTTPРеестр является локальным для процесса и становится доступным только для чтения, когда создаётся его официальный сервер. Каждый воркер строит один и тот же реестр из исходного кода во время запуска.
Не-цели
Этот пакет не является реализацией протокола MCP, генератором ORM-to-MCP, адаптером REST/DRF, заменой Celery, фоновой очередью или фреймворком для AI-агентов. Он не предоставляет автоматически модели Django и не выводит из них права доступа.
Лицензия
MIT
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA Django MCP server that exposes tools and resources to AI agents using simple decorators, with auto-discovery, type safety, and custom authentication.MIT
- AlicenseNot gradedqualityFmaintenanceIntegrates MCP tool hosting into Django applications, enabling easy definition and serving of MCP tools, resources, and prompts via ASGI with support for URL path parameters and logging.72MIT
- AlicenseNot gradedqualityBmaintenanceA Model Context Protocol (MCP) server for developing Django applications. It exposes Django project information through MCP tools, enabling AI assistants to better understand and interact with Django codebases.109MIT
- AlicenseNot gradedqualityCmaintenanceExposes Django REST Framework APIs as MCP tools for AI agents via the Model Context Protocol, with automatic discovery and security.1MIT
Related MCP Connectors
An MCP server that let you interact with Cycloid.io Internal Development Portal and Platform
Your DRF API as MCP tools — 1,800 endpoints become 16 dispatchers, permissioned by Django.
Official Sevalla MCP — full PaaS API access through just 2 tools.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/xelaxela13/django-native-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server