Skip to content
Back to search

django-mcp-server

Django MCP Server is a Django extensions to easily enable AI Agents to interact with Django Apps through the Model Context Protocol it works equally well on WSGI and ASGI

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/gts360--django-mcp-server/badge.svg)](/listings/gts360--django-mcp-server)

HTML

<a href="/listings/gts360--django-mcp-server"><img src="/api/listings/gts360--django-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1️⃣ Install

pip install django-mcp-server

Or directly from GitHub:

pip install git+https://github.com/omarbenhamid/django-mcp-server.git

---

2️⃣ Configure Django

✅ Add `mcp_server` to your `INSTALLED_APPS`:

INSTALLED_APPS = [
    # your apps...
    'mcp_server',
]

✅ Add the **MCP endpoint** to your `urls.py`:

from django.urls import path, include

urlpatterns = [
    # your urls...
    path("", include('mcp_server.urls')),
]

By default, the MCP endpoint will be available at `/mcp`.

---

3️⃣ Define MCP Tools

In mcp.py create a subclass of `ModelQueryToolset` to give access to a model :

from mcp_server import ModelQueryToolset
from .models import *

class BirdQueryTool(ModelQueryToolset):
    model = Bird

    def get_queryset(self):
        """self.request can be used to filter the queryset"""
        return super().get_queryset().filter(location__isnull=False)

class LocationTool(ModelQueryToolset):
    model = Location

class CityTool(ModelQueryToolset):
    model = City

Or create a sub class of `MCPToolset` to publish generic methods (private _ methods are not published)

Example:

from mcp_server import MCPToolset
from django.core.mail import send_mail

class MyAITools(MCPToolset):
    def add(self, a: int, b: int) -> list[dict]:
        """A service to add two numbers together"""
        return a+b

    def send_email(self, to_email: str, subject: str, body: str):
        """ A tool to send emails"""

        send_mail(
             subject=subject,
             message=body,
             from_email='your_email@example.com',
             recipient_list=[to_email],
             fail_silently=False,
         )

---

Verify with MCP Inspect

Use the management commande mcp_inspect to ensure your tools are correctly declared :

python manage.py mcp_inspect

Use the MCP with any MCP Client

The mcp tool is now published on your Django App at `/mcp` endpoint.

**IMPORTANT** For production setup, on non-public data, consider enabling authorization through : DJANGO_MCP_AUTHENTICATION_CLASSES

Test with MCP Python SDK

You can test it with the python mcp SDK :

from mcp.client.streamable_http import streamablehttp_client
from mcp import ClientSession

async def main():
    # Connect to a streamable HTTP server
    async with streamablehttp_client("http://localhost:8000/mcp") as (
        read_stream,
        write_stream,
        _,
    ):
        # Create a session using the client streams
        async with ClientSession(read_stream, write_stream) as session:
            # Initialize the connection
            await session.initialize()
            # Call a tool
            tool_result = await session.call_tool("get_alerts", {"state": "NY"})
            print(tool_result)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Replace `http://localhost:8000/mcp` by the acutal Django host and run this cript.

Use from Claude AI

As of **June 2025** Claude AI support now MCPs through streamable HTTP protocol with preè-requisites : * * Setup OAuth2, for example : * Install [Django Oauth Toolkit](https://django-oauth-toolkit.readthedocs.io/en/latest/)) * Include `'oauth2_provider.contrib.rest_framework.OAuth2Authentication'` in `DJANGO_MCP_AUTHENTICATION_CLASSES` in `settings.py` * Claude AI requires Dynamic Client Registration. as of today [it is not supported by django oauth toolkit](github.com/jazzband/django-oauth-toolkit/issues/670) but you can use [This Django Oauth Toolkit DCR Add-On](https://github.com/omarbenhamid/django-oauth-toolkit-dcr) * Unless you implement OAuth server Metadata RFC correctly, you need to keep OAuth2 URLS (`/register`, `/token` and `/authorize` at their default location).

Test in Claude Desktop

You can [test MCP servers in Claude Desktop](https://modelcontextprotocol.io/quickstart/server). As for now

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 495 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Django MCP Server
  2. [![PyPI version](https://img.shields.io/pypi/v/django-mcp-server)](https://pypi.org/project/django-mcp-server/)
  3. ![License](https://img.shields.io/pypi/l/django-mcp-server)
  4. [![Published on Django Packages](https://img.shields.io/badge/Published%20on-Django%20Packages-0c3c26)](https://djangopackages.org/packages/p/django-mcp-server/)
  5. ![Python versions](https://img.shields.io/pypi/pyversions/django-mcp-server)
  6. [![Django versions](https://img.shields.io/pypi/frameworkversions/django/django-mcp-server)](https://pypi.org/project/django-mcp-server/)
  7. **Django MCP Server** is an implementation of the **Model Context Protocol (MCP)** extension for Django. This module allows **MCP Clients** and **AI agents** to interact with **any Django application** seamlessly.
  8. 🚀 Django-Style declarative style tools to allow AI Agents and MCP clients tool to interact with Django.<br/>
  9. 🚀 Expose Django models for AI Agents and MCP Tools to query in 2 lines of code in a safe way.<br/>
  10. 🚀 Convert Django Rest Framework APIs to MCP tools with one annotation.<br/>
  11. ✅ Working on both WSGI and ASGI without infrastructure change.<br/>
  12. ✅ Validated as a Remote Integration with Claude AI.<br/>
  13. 🤖 Any MCP Client or AI Agent supporting MCP , (Google Agent Developement Kit, Claude AI, Claude Desktop ...) can interact with your application.
  14. Many thanks 🙏 to [all the contributor community](https://github.com/omarbenhamid/django-mcp-server/graphs/contributors)
  15. Maintained ✨ with care by [Smart GTS software engineering](https://www.smart-gts.com/#contact).
  16. Licensed under the **MIT License**.
  17. ---
  18. ## Features
  19. - Expose Django models and logic as **MCP tools**.
  20. - Serve an MCP endpoint inside your Django app.
  21. - Easily integrate with AI agents, MCP Clients, or tools like Google ADK.
  22. ---
  23. ## Quick Start
  24. ### 1️⃣ Install
  25. ```bash
  26. pip install django-mcp-server
  27. ```
  28. Or directly from GitHub:
  29. ```bash
  30. pip install git+https://github.com/omarbenhamid/django-mcp-server.git
  31. ```
  32. ---
  33. ### 2️⃣ Configure Django
  34. ✅ Add `mcp_server` to your `INSTALLED_APPS`:
  35. ```python
  36. INSTALLED_APPS = [
  37. # your apps...
  38. 'mcp_server',
  39. ]
  40. ```
  41. ✅ Add the **MCP endpoint** to your `urls.py`:
  42. ```python
  43. from django.urls import path, include
  44. urlpatterns = [
  45. # your urls...
  46. path("", include('mcp_server.urls')),
  47. ]
  48. ```
  49. By default, the MCP endpoint will be available at `/mcp`.
  50. ---
  51. ### 3️⃣ Define MCP Tools
  52. In mcp.py create a subclass of `ModelQueryToolset` to give access to a model :
  53. ```python
  54. from mcp_server import ModelQueryToolset
  55. from .models import *
  56. class BirdQueryTool(ModelQueryToolset):
  57. model = Bird
  58. def get_queryset(self):
  59. """self.request can be used to filter the queryset"""
  60. return super().get_queryset().filter(location__isnull=False)
  61. class LocationTool(ModelQueryToolset):
  62. model = Location
  63. class CityTool(ModelQueryToolset):
  64. model = City
  65. ```
  66. Or create a sub class of `MCPToolset` to publish generic methods (private _ methods are not published)
  67. Example:
  68. ```python
  69. from mcp_server import MCPToolset
  70. from django.core.mail import send_mail
  71. class MyAITools(MCPToolset):
  72. def add(self, a: int, b: int) -> list[dict]:
  73. """A service to add two numbers together"""
  74. return a+b
  75. def send_email(self, to_email: str, subject: str, body: str):
  76. """ A tool to send emails"""
  77. send_mail(
  78. subject=subject,
  79. message=body,
  80. from_email='your_email@example.com',
  81. recipient_list=[to_email],
  82. fail_silently=False,
  83. )
  84. ```
  85. ---
  86. ### Verify with MCP Inspect
  87. Use the management commande mcp_inspect to ensure your tools are correctly declared :
  88. ```bash
  89. python manage.py mcp_inspect
  90. ```
  91. ### Use the MCP with any MCP Client
  92. The mcp tool is now published on your Django App at `/mcp` endpoint.
  93. **IMPORTANT** For production setup, on non-public data, consider enabling
  94. authorization through : DJANGO_MCP_AUTHENTICATION_CLASSES
  95. ### Test with MCP Python SDK
  96. You can test it with the python mcp SDK :
  97. ```python
  98. from mcp.client.streamable_http import streamablehttp_client
  99. from mcp import ClientSession
  100. async def main():
  101. # Connect to a streamable HTTP server
  102. async with streamablehttp_client("http://localhost:8000/mcp") as (
  103. read_stream,
  104. write_stream,
  105. _,
  106. ):
  107. # Create a session using the client streams
  108. async with ClientSession(read_stream, write_stream) as session:
  109. # Initialize the connection
  110. await session.initialize()
  111. # Call a tool
  112. tool_result = await session.call_tool("get_alerts", {"state": "NY"})
  113. print(tool_result)
  114. if __name__ == "__main__":
  115. import asyncio
  116. asyncio.run(main())
  117. ```
  118. Replace `http://localhost:8000/mcp` by the acutal Django host and run this cript.
  119. ### Use from Claude AI
  120. As of **June 2025** Claude AI support now MCPs through streamable HTTP protocol with preè-requisites :
  121. *
  122. * Setup OAuth2, for example :
  123. * Install [Django Oauth Toolkit](https://django-oauth-toolkit.readthedocs.io/en/latest/))
  124. * Include `'oauth2_provider.contrib.rest_framework.OAuth2Authentication'` in `DJANGO_MCP_AUTHENTICATION_CLASSES` in `settings.py`
  125. * Claude AI requires Dynamic Client Registration. as of today [it is not supported by django oauth toolkit](github.com/jazzband/django-oauth-toolkit/issues/670) but you can use [This Django Oauth Toolkit DCR Add-On](https://github.com/omarbenhamid/django-oauth-toolkit-dcr)
  126. * Unless you implement OAuth server Metadata RFC correctly, you need to keep OAuth2 URLS (`/register`, `/token` and `/authorize` at their default location).
  127. ### Test in Claude Desktop
  128. You can [test MCP servers in Claude Desktop](https://modelcontextprotocol.io/quickstart/server). As for now
  129. claude desktop only supports local MCP Servers. So you need to have your app installed on the same machine, in a
  130. dev setting probably.
  131. For this you need :
  132. 1. To install Claude Desktop from [claude.ai](https://claude.ai)
  133. 2. Open File > Settings > Developer and click **Edit Config**
  134. 3. Open `claude_desktop_config.json` and setup your MCP server :
  135. ```json
  136. {
  137. "mcpServers": {
  138. "test_django_mcp": {
  139. "command": "/path/to/interpreter/python",
  140. "args": [
  141. "/path/to/your/project/manage.py",
  142. "stdio_server"
  143. ]
  144. }
  145. }
  146. ```
  147. **NOTE** `/path/to/interpreter/` should point to a python interpreter you use (can be in your venv for example)
  148. and `/path/to/your/project/` is the path to your django project.
  149. ## Advanced topics
  150. ### Publish Django Rest Framework APIs as MCP Tools
  151. You can use `drf_publish_create_mcp_tool` / `drf_publish_update_mcp_tool` / `drf_publish_delete_mcp_tool` /
  152. `drf_publish_list_mcp_tool` as annotations or method calls to register DRF CreateModelMixin / UpdateModelMixin
  153. / DestroyModelMixin / ListModelMixin based views to MCP tools seamlessly. Django MCP Server will generate the schemas
  154. to allow MCP Clients to use them.
  155. **NOTE** in some *older DRF versions* schema generation is not supported out of the box, you should then provide to the registration
  156. annotation the
  157. ```python
  158. from mcp_server import drf_publish_create_mcp_tool
  159. @drf_publish_create_mcp_tool
  160. class MyModelView(CreateAPIView):
  161. """
  162. A view to create MyModel instances
  163. """
  164. serializer_class=MySerializer
  165. ```
  166. notice that the docstring of the view is used as instructions for the model.
  167. You can better tune this like :
  168. ```python
  169. @drf_publish_create_mcp_tool(instructions="Use this view to create instances of MyModel")
  170. class MyModelView(CreateAPIView):
  171. """
  172. A view to create MyModel instances
  173. """
  174. serializer_class=MySerializer
  175. ```
  176. Finally, you can register after hand in mcp.py for example with:
  177. ```python
  178. drf_publish_update_mcp_tool(MyDRFAPIView, instructions="Use this tool to update my model, but use it with care")
  179. ```
  180. **IMPORTANT**
  181. Notice that **builti-in authentication classes are disabled** by default along with filter_backends, permission_classes and pagination_class, that's because
  182. the MCP authentication is used.
  183. Since the pagination_class is also disabled, you will need to account for that if you're using an existing paginated DRF view (`self.paginator` will be `None`).
  184. ### Django Rest Framework Serializer integration
  185. You can annotate a tool with `drf_serialize_output(...)` to serialize its output using
  186. django rest framework, like :
  187. ```python
  188. from mcp_server import drf_serialize_output
  189. from .serializers import FooBarSerializer
  190. from .models import FooBar
  191. class MyTools(MCPToolset):
  192. @drf_serialize_output(FooBarSerializer)
  193. def get_foo_bar():
  194. return FooBar.objects.first()
  195. ```
  196. ### Use low level mcp server annotation
  197. You can import the DjangoMCP server instance and use FastMCP annotations to declare
  198. mcp tools and resources :
  199. ```python
  200. from mcp_server import mcp_server as mcp
  201. from .models import Bird
  202. @mcp.tool()
  203. async def get_species_count(name: str) -> int:
  204. '''Find the ID of a bird species by name (partial match). Returns the count.'''
  205. ret = await Bird.objects.filter(species__icontains=name).afirst()
  206. if ret is None:
  207. ret = await Bird.objects.acreate(species=name)
  208. return ret.count
  209. @mcp.tool()
  210. async def increment_species(name: str, amount: int = 1) -> int:
  211. '''
  212. Increment the count of a bird species by a specified amount.
  213. Returns the new count.
  214. '''
  215. ret = await Bird.objects.filter(species__icontains=name).afirst()
  216. if ret is None:
  217. ret = await Bird.objects.acreate(species=name)
  218. ret.count += amount
  219. await ret.asave()
  220. return ret.count
  221. ```
  222. ⚠️ **Important**:
  223. 1. Always use **Django's async ORM API** when you define async tools.
  224. 2. Be careful not to return a QuerySet as it will be evaluated asynchroniously which would create errors.
  225. ### Customize the default MCP server settings
  226. In `settings.py` you can initialize the `DJANGO_MCP_GLOBAL_SERVER_CONFIG` parameter. These will be
  227. passed to the `MCPServer` server during initialization
  228. ```python
  229. DJANGO_MCP_GLOBAL_SERVER_CONFIG = {
  230. "name":"mymcp",
  231. "instructions": "Some instructions to use this server",
  232. "stateless": False
  233. }
  234. ```
  235. ### Session management
  236. By default the server is statefull, and state is managed as [Django session](https://docs.djangoproject.com/en/5.2/topics/http/sessions/)
  237. `request.session` object, so the session backend must thus be set up correctly. The
  238. request object is available in `self.request` for class based toolsets.
  239. **NOTE** The session middleware is not required to be set up as MCP sessions are managed
  240. independently and without cookies.
  241. .
  242. You can make the server stateless by defining : `DJANGO_MCP_GLOBAL_SERVER_CONFIG`
  243. **IMPORTANT** state is managed by django sessions, if you use low level `@mcp_server.tool()` annotation for example
  244. the behaviour of preserving the server instance accross calls of the base python API is not preserved due to architecture
  245. of django in WSGI deployments where requests can be served by different threads !
  246. ### Authorization
  247. The MCP endpoint supports [Django Rest Framework authorization classes](https://www.django-rest-framework.org/api-guide/authentication/)
  248. You can set them using `DJANGO_MCP_AUTHENTICATION_CLASSES` in `settings.py` ex. :
  249. ```python
  250. DJANGO_MCP_AUTHENTICATION_CLASSES=["rest_framework.authentication.TokenAuthentication"]
  251. ```
  252. **IMPORTANT** Now the [MCP Specification version 2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization)
  253. advices to use an OAuth2 workflow, so you should integrate
  254. [django-oauth-toolkit with djangorestframework integration](https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html)
  255. setup, and use `'oauth2_provider.contrib.rest_framework.OAuth2Authentication'` in
  256. `DJANGO_MCP_AUTHENTICATION_CLASSES`. Refer to [the official documentation of django-oauth-toolkit](https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html)
  257. ### Advanced / customized setup of the view
  258. You can in your urls.py mount the MCPServerStreamableHttpView.as_view() view and customize it with any extra parameters.
  259. ### Custom output format (renderers) for ModelQueryToolset
  260. You can define any [DRF rendrer](https://www.django-rest-framework.org/api-guide/renderers/) to produce output, for this
  261. it must be declared in your settings:
  262. ```python
  263. DJANGO_MCP_OUTPUT_RENDERER_CLASSES = [
  264. "rest_framework.renderers.JSONRenderer",
  265. "rest_framework_csv.renderers.CSVRenderer"
  266. ]
  267. ```
  268. Then in your `ModelQueryToolset` declaration you can add
  269. ```python
  270. ...
  271. output_format="csv"
  272. ```
  273. further you can instruct the tool to attach the result as an [MCP Embedded Resource] rather than direct return with
  274. ```python
  275. ...
  276. output_as_resource=True
  277. ```
  278. *NOTE* some renderers like `drf-excel` are designed in a way that does not allow using them outside of DRF View, they will not
  279. work here..
  280. ### Secondary MCP endpoint
  281. in `mcp.py`
  282. ```python
  283. from mcp_server.djangomcp import DjangoMCP
  284. second_mcp = DjangoMCP(name="altserver")
  285. @second_mcp.tool()
  286. async def my_tool():
  287. ...
  288. ```
  289. in urls.py
  290. ```python
  291. ...
  292. from yourapp.mcp import second_mcp
  293. ...
  294. path("altmcp", MCPServerStreamableHttpView.as_view(mcp_server=second_mcp))
  295. ...
  296. ```
  297. **IMPORTANT** When you do this the DJANGO_MCP_AUTHENTICATION_CLASSES settings is **ignored** and
  298. your view is unsecure. You **SHOULD** [Setup DRF Authentication](https://www.django-rest-framework.org/api-guide/authentication/)
  299. for your view, for exemple :
  300. ```python
  301. ...
  302. MCPServerStreamableHttpView.as_view(permission_classes=[IsAuthenticated], authentication_classes=[TokenAuthentication])
  303. ...
  304. ```
  305. ## Testing
  306. ### The server
  307. You can setup you own app or use the [mcpexample django app](examples/mcpexample) app.
  308. ### The client
  309. By default, your MCP Server will be available as a
  310. [stateless streamable http transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)
  311. endpoint at <your_django_server>/mcp (ex. http://localhost:8000/mcp) (*without / at the end !).
  312. There are many ways to test :
  313. 1. Using the test [MCP Client script : test/test_mcp_client.py](test/test_mcp_client.py)
  314. 2. You can test using [MCP Inspector tool](https://github.com/modelcontextprotocol/inspector)
  315. 3. or any compatible MCP Client like google agent developement kit.
  316. ---
  317. ## Integration with Agentic Frameworks and MCP Clients
  318. ### Google Agent Developement Kit Example
  319. **NOTE** as of today the [official google adk does not support StreamableHTTP Transport](https://github.com/google/adk-python/issues/479)
  320. but you could use [this fork](https://github.com/omarbenhamid/google-adk-python)
  321. Then you can use the [test agent in test/test_agent](test/test_agent/agent.py) with by
  322. starting `adk web` in the `test` folder. Make sure first :
  323. 1. Install adk with streamablehttp support : `pip install git+https://github.com/omarbenhamid/google-adk-python.git`
  324. 2. Start a django app with an MCP endpoint : `python manage.py runserver` in the `examples/mcpexample` folder.
  325. 2. If you use TokenAuthorization create an access token, for example in Django Admin of your app.
  326. 3. Setup in `test/test_agent/agent.py` the right endpoint location and authentication header
  327. 4. Enter the `test` folder.
  328. 5. Run `adk web`
  329. 6. In the shell you can for example use this prompt : "I saw woody woodpecker, add it to my inventory"
  330. ### Other clients
  331. You can easily plug your MCP server endpoint into any agentic framework supporting MCP streamable http servers.
  332. Refer to this [list of clients](https://modelcontextprotocol.io/clients)
  333. ---
  334. ## Settings
  335. - **DJANGO_MCP_GLOBAL_SERVER_CONFIG** a configuration dictionnary for the global MCP server default to empty. It can include the following parmaters
  336. - name: a name for the server
  337. - instructions: global instructions
  338. - stateless : when set to 'True' the server will not manage sessions
  339. - **DJANGO_MCP_AUTHENTICATION_CLASSES** (default to no authentication) a list of reference to Django Rest Framework authentication classes to enfors in the main MCP view.
  340. - **DJANGO_MCP_GET_SERVER_INSTRUCTIONS_TOOL** (default=True) if true a tool will be offered to obtain global instruction and tools will instruct the agent to use it, as agents do not always have the MCP server global instructions included in their system prompt.
  341. - **DJANGO_MCP_ENDPOINT** (default="mcp") a string indicating the url endpoint used by the server. If you want it to have a trailing slash, for example, set it to "mcp/"
  342. ## Roadmap
  343. - ✅ **Stateless streamable HTTP transport** (implemented)
  344. - 🔜 **STDIO transport integration for dev configuration (ex. Claude Desktop)**
  345. - 🔜 ****
  346. - 🔜 **Stateful streamable HTTP transport using Django sessions**
  347. - 🔜 **SSE endpoint integration (requires ASGI)**
  348. - 🔜 **Improved error management and logging**
  349. ---
  350. ## Issues
  351. If you encounter bugs or have feature requests, please open an issue on [GitHub Issues](https://github.com/omarbenhamid/django-mcp-server/issues).
  352. ---
  353. ## License
  354. MIT License.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.