使用说明
Django MCP服务器
Django MCP服务器 是实现 模型上下文协议(MCP) Django的扩展。该模块允许 MCP客户端 和 AI代理 与…互动 任何Django应用程序 无缝。
✅ 工作在你现有的 服务网关接口 应用程序。
🚀 流式HTTP传输(无状态) 实施。
🛣️ 豪华交通 和 服务器发送事件(SSE)响应 在路线图上(需要ASGI)。
根据 MIT许可证.
特性
- 将Django模型和逻辑公开为 MCP工具.
- 在Django应用程序中提供MCP端点。
- 轻松与AI代理、MCP客户端或Google ADK等工具集成。
快速开始
1.️⃣ 安装
pip install django-mcp-server
或者直接从GitHub:
pip install git+https://github.com/omarbenhamid/django-mcp-server.git
2.️⃣ 配置Django
✅ 添加 mcp_server 到你的 INSTALLED_APPS:
INSTALLED_APPS = [
# your apps...
'mcp_server',
]
✅ 添加 MCP端点 到你的 urls.py:
from django.urls import path, include
urlpatterns = [
# your urls...
path("", include('mcp_server.urls')),
]
默认情况下,MCP端点将在以下位置可用 /mcp.
3.️⃣ 定义MCP工具
创建文件 mcp.py 在Django应用程序中,创建MCPToolset的子类:每个方法
不以“_”开头的将作为工具发布。
例子:
from mcp_server import MCPToolset
from .models import Bird
class SpeciesCount(MCPToolset):
mcp_server = None # None to use the global mcp_server or specify a local one, if so you need to register it in urls.py see readme
def _search_birds(self, search_string: str | None = None) -> Bird:
"""Get the queryset for birds,
methods starting with _ are not registered as tools"""
return Bird.objects.all() if search_string is None else Bird.objects.filter(species__icontains=search_string)
def list_species(self, search_string: str | None = None) -> list[dict]:
"""List all species with a search string, returns the name and count of each species found"""
return list(self._search_birds(search_string).values('species', 'count'))
def increment_species(self, name: str, amount: int = 1) -> int:
"""
Increment the count of a bird species by a specified amount and returns tehe new count.
The first argument ios species name the second is the mouunt to increment with (1) by default.
"""
ret = self._search_birds(name).first()
if ret is None:
ret = Bird.objects.create(species=name)
ret.count += amount
ret.save()
return ret.count
高级主题
使用低级mcp服务器注释
您可以导入Django MCP服务器实例,并使用FastMCP注释来声明 mcp工具和资源:
from mcp_server import mcp_server as mcp
from .models import Bird
print("Defining tools")
@mcp.tool()
async def get_species_count(name: str) -> int:
'''Find the ID of a bird species by name (partial match). Returns the count.'''
ret = await Bird.objects.filter(species__icontains=name).afirst()
if ret is None:
ret = await Bird.objects.acreate(species=name)
return ret.count
@mcp.tool()
async def increment_species(name: str, amount: int = 1) -> int:
'''
Increment the count of a bird species by a specified amount.
Returns the new count.
'''
ret = await Bird.objects.filter(species__icontains=name).afirst()
if ret is None:
ret = await Bird.objects.acreate(species=name)
ret.count += amount
await ret.asave()
return ret.count
⚠️ 重要:始终使用 Django的异步ORM API 在这种情况下。
自定义默认MCP服务器设置
在……里面 settings.py 您可以初始化 DJANGO_MCP_GLOBAL_SERVER_CONFIG 参数。这些将是
传递给 MCPServer 服务器初始化期间
DJANGO_MCP_GLOBAL_SERVER_CONFIG = {
"name":"mymcp",
"instructions": "Some instructions to use this server"
}
授权
使用 DRF注释 您可以在urls.py中启用授权:
path("mcp", api_view(['GET','POST'])(permission_classes([IsAuthenticated])(MCPServerStreamableHttpView.as_view())))
为了符合MCP规范,您应该支持OAuth2,因此您应该集成例如 django-oauth工具包 为了这个。
次要MCP终点
在……里面 mcp.py
second_mcp = DjangoMCP(name="altserver")
@second_mcp.tools()
async def my_tool():
...
在urls.py中
...
path("altmcp", MCPServerStreamableHttpView.as_view(mcp_server=second_server))
...
测试
默认情况下,您的MCP服务器将作为 无状态流式http传输 端点位于<your_djangoserver>/mcp(例如。http://localhost:8000/mcp)(*没有/在最后!)。
有很多方法可以测试:
- 使用测试 MCP客户端脚本:test/test_MCP_Client.py
- 您可以使用以下方式进行测试 MCP检查器工具
- 或任何兼容的MCP客户端。
与代理框架和MCP客户端集成
您可以轻松地将MCP服务器端点插入任何支持MCP流式http服务器的代理框架中。 请参阅此 客户列表
路线图
- ✅ 无状态流式HTTP传输 (已实施)
- 🔜 用于开发配置的STDIO传输集成(例如Claude Desktop)
- 🔜 ****
- 🔜 使用Django会话的有状态流式HTTP传输
- 🔜 SSE端点集成(需要ASGI)
- 🔜 改进了错误管理和日志记录
问题
如果您遇到错误或有功能请求,请在 GitHub问题.
许可证
MIT许可证。
