Logo vun Django MCP 服务器

Django MCP 服务器

Organisatioun
gts360

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

Editeurgts360
Repositorydjango-mcp-server
SproochPython
Forks
60
Stären
382
Disponibel Tools
0
Transporttypstdio, streamable-http
Kategorien
LizenzMIT
Linken
  • Tools mat KI-Workflows verbannen

    Django MCP 服务器 stellt MCP-Funktioune bereit, déi vu kompatibele KI-Clienten a KI-Agente kënne benotzt ginn.

  • 0 disponibel Tools

    Kuckt Iech déi opruffbar Aktiounen hei drënner un, mat Nimm a Beschreiwungen, wa se vum Server geliwwert ginn.

  • Konfiguratioun fir ze kopéieren

    Benotzt d'Installatiounsbeispiller, fir dëse Server an Ärem bevorzugte MCP-Client ze konfiguréieren.

  • Indicateure fir Open Source

    382 Stären an 60 Forks aus dem verlinkte Repository.

Django MCP Server

PyPI version License Published on Django Packages Python versions Django versions

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.

🚀 Django-Style declarative style tools to allow AI Agents and MCP clients tool to interact with Django. 🚀 Expose Django models for AI Agents and MCP Tools to query in 2 lines of code in a safe way. 🚀 Convert Django Rest Framework APIs to MCP tools with one annotation. ✅ Working on both WSGI and ASGI without infrastructure change. ✅ Validated as a Remote Integration with Claude AI. 🤖 Any MCP Client or AI Agent supporting MCP , (Google Agent Developement Kit, Claude AI, Claude Desktop ...) can interact with your application.

Many thanks 🙏 to all the contributor community

Maintained ✨ with care by Smart GTS software engineering.

Licensed under the MIT License.


Features

  • Expose Django models and logic as MCP tools.
  • Serve an MCP endpoint inside your Django app.
  • Easily integrate with AI agents, MCP Clients, or tools like Google ADK.

Quick Start

1️⃣ Install

bash
pip install django-mcp-server

Or directly from GitHub:

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

2️⃣ Configure Django

✅ Add mcp_server to your INSTALLED_APPS:

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

✅ Add the MCP endpoint to your urls.py:

python
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 :

python
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:

python
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 :

bash
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 :

python
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 : *

Test in Claude Desktop

You can test MCP servers in Claude Desktop. As for now claude desktop only supports local MCP Servers. So you need to have your app installed on the same machine, in a dev setting probably.

For this you need :

  1. To install Claude Desktop from claude.ai
  2. Open File > Settings > Developer and click Edit Config
  3. Open claude_desktop_config.json and setup your MCP server :
    json
    {
     "mcpServers": {
         "test_django_mcp": {
             "command": "/path/to/interpreter/python",
             "args": [
                 "/path/to/your/project/manage.py",
                 "stdio_server"
             ]
         }
     }

NOTE /path/to/interpreter/ should point to a python interpreter you use (can be in your venv for example) and /path/to/your/project/ is the path to your django project.

Advanced topics

Publish Django Rest Framework APIs as MCP Tools

You can use drf_publish_create_mcp_tool / drf_publish_update_mcp_tool / drf_publish_delete_mcp_tool / drf_publish_list_mcp_tool as annotations or method calls to register DRF CreateModelMixin / UpdateModelMixin / DestroyModelMixin / ListModelMixin based views to MCP tools seamlessly. Django MCP Server will generate the schemas to allow MCP Clients to use them.

NOTE in some older DRF versions schema generation is not supported out of the box, you should then provide to the registration annotation the

python
from mcp_server import drf_publish_create_mcp_tool

@drf_publish_create_mcp_tool
class MyModelView(CreateAPIView):
    """
    A view to create MyModel instances
    """
    serializer_class=MySerializer

notice that the docstring of the view is used as instructions for the model. You can better tune this like :

python
@drf_publish_create_mcp_tool(instructions="Use this view to create instances of MyModel")
class MyModelView(CreateAPIView):
    """
    A view to create MyModel instances
    """
    serializer_class=MySerializer

Finally, you can register after hand in mcp.py for example with:

python
drf_publish_update_mcp_tool(MyDRFAPIView, instructions="Use this tool to update my model, but use it with care")

IMPORTANT

Notice that builti-in authentication classes are disabled by default along with filter_backends, permission_classes and pagination_class, that's because the MCP authentication is used.

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).

Django Rest Framework Serializer integration

You can annotate a tool with drf_serialize_output(...) to serialize its output using django rest framework, like :

python
from mcp_server import drf_serialize_output
from .serializers import FooBarSerializer
from .models import FooBar

class MyTools(MCPToolset):
   @drf_serialize_output(FooBarSerializer)
   def get_foo_bar():
       return FooBar.objects.first()

Use low level mcp server annotation

You can import the DjangoMCP server instance and use FastMCP annotations to declare mcp tools and resources :

python
from mcp_server import mcp_server as mcp
from .models import Bird


@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

⚠️ Important:

  1. Always use Django's async ORM API when you define async tools.
  2. Be careful not to return a QuerySet as it will be evaluated asynchroniously which would create errors.

Customize the default MCP server settings

In settings.py you can initialize the DJANGO_MCP_GLOBAL_SERVER_CONFIG parameter. These will be passed to the MCPServer server during initialization

python
DJANGO_MCP_GLOBAL_SERVER_CONFIG = {
    "name":"mymcp",
    "instructions": "Some instructions to use this server",
    "stateless": False
}

Session management

By default the server is statefull, and state is managed as Django session request.session object, so the session backend must thus be set up correctly. The request object is available in self.request for class based toolsets.

NOTE The session middleware is not required to be set up as MCP sessions are managed independently and without cookies. . You can make the server stateless by defining : DJANGO_MCP_GLOBAL_SERVER_CONFIG

IMPORTANT state is managed by django sessions, if you use low level @mcp_server.tool() annotation for example the behaviour of preserving the server instance accross calls of the base python API is not preserved due to architecture of django in WSGI deployments where requests can be served by different threads !

Authorization

The MCP endpoint supports Django Rest Framework authorization classes You can set them using DJANGO_MCP_AUTHENTICATION_CLASSES in settings.py ex. :

python
DJANGO_MCP_AUTHENTICATION_CLASSES=["rest_framework.authentication.TokenAuthentication"]

IMPORTANT Now the MCP Specification version 2025-03-26 advices to use an OAuth2 workflow, so you should integrate django-oauth-toolkit with djangorestframework integration setup, and use 'oauth2_provider.contrib.rest_framework.OAuth2Authentication' in DJANGO_MCP_AUTHENTICATION_CLASSES. Refer to the official documentation of django-oauth-toolkit

Advanced / customized setup of the view

You can in your urls.py mount the MCPServerStreamableHttpView.as_view() view and customize it with any extra parameters.

Custom output format (renderers) for ModelQueryToolset

You can define any DRF rendrer to produce output, for this it must be declared in your settings:

python
DJANGO_MCP_OUTPUT_RENDERER_CLASSES = [
    "rest_framework.renderers.JSONRenderer",
    "rest_framework_csv.renderers.CSVRenderer"
]

Then in your ModelQueryToolset declaration you can add

python
    ...
    output_format="csv"

further you can instruct the tool to attach the result as an [MCP Embedded Resource] rather than direct return with

python
    ...
    output_as_resource=True

NOTE some renderers like drf-excel are designed in a way that does not allow using them outside of DRF View, they will not work here..

Secondary MCP endpoint

in mcp.py

python
from mcp_server.djangomcp import DjangoMCP

second_mcp = DjangoMCP(name="altserver")

@second_mcp.tool()
async def my_tool():
    ...

in urls.py

python
...
from yourapp.mcp import second_mcp
...
path("altmcp", MCPServerStreamableHttpView.as_view(mcp_server=second_mcp))
...

IMPORTANT When you do this the DJANGO_MCP_AUTHENTICATION_CLASSES settings is ignored and your view is unsecure. You SHOULD Setup DRF Authentication for your view, for exemple :

python
...
MCPServerStreamableHttpView.as_view(permission_classes=[IsAuthenticated], authentication_classes=[TokenAuthentication])
...

Testing

The server

You can setup you own app or use the mcpexample django app app.

The client

By default, your MCP Server will be available as a stateless streamable http transport endpoint at <your_django_server>/mcp (ex. http://localhost:8000/mcp) (*without / at the end !).

There are many ways to test :

  1. Using the test MCP Client script : test/test_mcp_client.py
  2. You can test using MCP Inspector tool
  3. or any compatible MCP Client like google agent developement kit.

Integration with Agentic Frameworks and MCP Clients

Google Agent Developement Kit Example

NOTE as of today the official google adk does not support StreamableHTTP Transport but you could use this fork

Then you can use the test agent in test/test_agent with by starting adk web in the test folder. Make sure first :

  1. Install adk with streamablehttp support : pip install git+https://github.com/omarbenhamid/google-adk-python.git
  2. Start a django app with an MCP endpoint : python manage.py runserver in the examples/mcpexample folder.
  3. If you use TokenAuthorization create an access token, for example in Django Admin of your app.
  4. Setup in test/test_agent/agent.py the right endpoint location and authentication header
  5. Enter the test folder.
  6. Run adk web
  7. In the shell you can for example use this prompt : "I saw woody woodpecker, add it to my inventory"

Other clients

You can easily plug your MCP server endpoint into any agentic framework supporting MCP streamable http servers. Refer to this list of clients


Settings

  • DJANGO_MCP_GLOBAL_SERVER_CONFIG a configuration dictionnary for the global MCP server default to empty. It can include the following parmaters

    • name: a name for the server
    • instructions: global instructions
    • stateless : when set to 'True' the server will not manage sessions
  • 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.

  • 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.

  • 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/"

Roadmap

  • ✅ Stateless streamable HTTP transport (implemented)
  • 🔜 STDIO transport integration for dev configuration (ex. Claude Desktop)
  • 🔜 ****
  • 🔜 Stateful streamable HTTP transport using Django sessions
  • 🔜 SSE endpoint integration (requires ASGI)
  • 🔜 Improved error management and logging

Issues

If you encounter bugs or have feature requests, please open an issue on GitHub Issues.


License

MIT License.

Installatioun

TypingMind
Viraussetzungen:

Node.js 18+

{
  "mcpServers": {
    "omarbenhamid-django-mcp-server": {
      "command": "uvx",
      "args": [
        "django-mcp-server"
      ]
    }
  }
}

Django MCP 服务器 MCP mat verschiddene KI-Modeller benotzen

TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Soubal Django MCP 服务器 verbonnen ass, kënnt Dir et mat verschiddene KI-Modeller an TypingMind benotzen, amplaz et fir all Modell separat anzeriichten. Dir kënnt MCP lokal op Ärem Apparat ausféieren oder Iech mat enger Remote-MCP-Server-URL verbannen.

Optioun 1: De lokale Connector benotzen

Benotzt dës Optioun, wann den MCP-Server Zougrëff op lokal Fichieren, Appen oder privat Ressourcen op Ärem Computer brauch.

1

D'MCP-Astellungen opmaachen

Gitt an TypingMind op „Astellungen“, „Erweidert Astellungen“, dann op „Model Context Protocol“ a wielt „Connector ariichten“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Klickt op d'Astellungssymbol.
  3. Gitt op „Erweidert Astellungen“.
  4. Maacht d'Sektioun „Model Context Protocol“ op.
  5. Klickt op „Connector ariichten“ a wielt „Dësen Apparat“.
Ariichtungsbildschierm vum TypingMind-MCP-Connector mat „Dësen Apparat“ ausgewielt
2

De Connector-Befeel ausféieren

Wielt „Dësen Apparat“, kopéiert de Befeel aus TypingMind a féiert en am Terminal aus. Loosst de Prozess lafen, wärend Dir MCP benotzt.

  1. Kopéiert den Ariichtungsbefeel, deen TypingMind uweist.
  2. Maacht Terminal op macOS oder Windows Terminal op Windows op.
  3. Pescht de Befeel an a féiert en aus.
  4. Bestätegt d'Installatioun vum Package, wann den Terminal Iech freet, ob Dir weiderfuere wëllt.
  5. Loosst den Terminal an de Prozess doranner lafen, wärend Dir MCP-Tools benotzt.
3

Django MCP 服务器 als Server derbäisetzen

Wann de Connector-Status „Prett“ ass, klickt op „Serveren änneren“ a pescht d'MCP-Serverkonfiguratioun an.

  1. Waart, bis de Connector-Status „Prett“ weist.
  2. Klickt op „Serveren änneren“.
  3. Pescht d'MCP-Serverkonfiguratioun vu Django MCP 服务器 an.
  4. Späichert d'Serverlëscht.
  5. Aktualiséiert, wann Dir kontrolléiere wëllt, ob de Connector nach ëmmer prett ass.
MCP-Astellunge vun TypingMind mat aktivem Server an dem Knäppchen „Serveren änneren“
{
  "mcpServers": {
    "omarbenhamid-django-mcp-server": {
      "command": "npx",
      "args": [
        "-y",
        "django-mcp-server"
      ]
    }
  }
}
4

D'Verbindung mat verschiddene Modeller benotzen

Späichert d'Serverlëscht, maacht „Plugins“ op an aktivéiert d'MCP-Tools vu Django MCP 服务器. Wielt dann e belibegen ënnerstëtzte KI-Modell an TypingMind a benotzt d'Tools am Chat oder weist se engem KI-Agent zou.

  1. Maacht d'Säit „Plugins“ an TypingMind op.
  2. Aktivéiert d'MCP-Tools vu Django MCP 服务器.
  3. Start e Chat a wielt de KI-Modell, deen Dir benotze wëllt.
  4. Benotzt d'MCP-Tools am Chat oder weist se engem KI-Agent zou.
  5. Wiesselt bei Bedarf op en anere KI-Modell, ouni MCP nei ze verbannen.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat Django MCP 服务器?
Django MCP 服务器
Jo. Ech hunn et gelies.
Dat hunn ech mat Django MCP 服务器 fonnt.

Optioun 2: Eng MCP-Server-URL derbäisetzen

Benotzt dës Optioun, wann Django MCP 服务器 scho remote gehost gëtt oder Är Ekipp ee gemeinsame Connector wëllt, op dee méi Benotzer kënnen zougräifen.

1

MCP-Connectoren opmaachen

Gitt an TypingMind op „Plugins“, maacht „MCP-Connectoren“ op a wielt dann „URL derbäisetzen“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Gitt op „Plugins“.
  3. Maacht „MCP-Connectoren“ op.
  4. Klickt op „URL derbäisetzen“.
TypingMind-Formulaire fir eng benotzerdefinéiert MCP-Server-URL derbäizesetzen
2

D'Server-URL apeschen

Gitt Är Server-URL am Feld „Server-URL“ an. Setzt e Verbindungsnumm, eng Beschreiwung, e Symbol, benotzerdefinéiert HTTP-Headeren oder OAuth-Clientastellungen derbäi, wann de Server se erfuerdert.

  1. Pescht Är Server-URL an d'Feld „Server-URL“.
  2. Gitt en Numm fir d'Verbindung mat Django MCP 服务器 an.
  3. Setzt eng Beschreiwung an e Symbol derbäi, fir d'Verbindung méi einfach erëmzeerkennen.
  4. Setzt benotzerdefinéiert HTTP-Headeren oder OAuth-Clientdetailer derbäi, wann de Server eng Authentifizéierung erfuerdert.
3

D'Verbindung erstellen

Klickt op „Verbindung erstellen“, gitt dann zeréck op d'Plugin-Lëscht a kontrolléiert, ob déi nei MCP-Verbindung aktiv ass.

  1. Klickt op „Verbindung erstellen“.
  2. Gitt zeréck op d'Lëscht vun de MCP-Connectoren.
  3. Kontrolléiert, ob d'Verbindung mat Django MCP 服务器 als aktiv ugewise gëtt.
  4. Aktualiséiert d'Plugin-Lëscht, wann d'Verbindung net direkt ugewise gëtt.
4

Modeller wiesselen ouni nei ze verbannen

Start e Chat mat Ärem bevorzugte Modell, aktivéiert d'Tools vu Django MCP 服务器 ënner „Plugins“ a wiesselt bei Bedarf op en anere Modell. D'MCP-Verbindung bleift am TypingMind-Aarbechtsberäich disponibel.

  1. Start en neie Chat an TypingMind.
  2. Wielt de KI-Modell, deen Dir benotze wëllt.
  3. Aktivéiert d'Tools vu Django MCP 服务器 ënner „Plugins“.
  4. Biet de Modell, den Tool ze benotzen, wann néideg.
  5. Wiesselt op en anere KI-Modell a benotzt déiselwecht MCP-Verbindung weider.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat Django MCP 服务器?
Django MCP 服务器
Jo. Ech hunn et gelies.
Dat hunn ech mat Django MCP 服务器 fonnt.

Heefeg gestallte Froen

Fir wat gëtt de MCP-Server Django MCP 服务器 benotzt?

Django MCP 服务器 ass e MCP-Server, deen et kompatibele KI-Clienten erlaabt, sech mat externen Tools a Kontext ze verbannen. An TypingMind kënnt Dir dëse MCP-Server eemol derbäisetzen a seng Tools an Ärem KI-Aarbechtsberäich zur Verfügung stellen.

Kann ech Django MCP 服务器 MCP mat méi KI-Modeller an TypingMind benotzen?

Jo. TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Sou kënnt Dir Django MCP 服务器 mat verschiddene KI-Modeller wéi Claude, ChatGPT, Gemini oder anere Modeller benotzen, déi Dir an TypingMind konfiguréiert hutt, ouni de MCP-Server fir all Modell separat anzeriichten.

Firwat Django MCP 服务器 MCP mat TypingMind benotzen?

TypingMind ass eng vun de beschte Benotzeruewerfläche fir LLM-Chat, well et méi KI-Modeller, Prompts, Plugins, KI-Agenten, API-Schlësselen a MCP-Tools an engem Aarbechtsberäich zesummebréngt. Wann Django MCP 服务器 verbonnen ass, kënnt Dir seng MCP-Tools mat Äre bevorzugte Modeller benotzen a gläichzäiteg Är Chataarbecht an TypingMind organiséieren.

Wéi verbannen ech Django MCP 服务器 MCP mat TypingMind?

Dir kënnt Django MCP 服务器 iwwer de lokale MCP-Connector oder iwwer d'URL vun engem Remote-MCP-Server mat TypingMind verbannen. Benotzt de lokale Connector, wann de Server Zougrëff op Fichieren, Apps oder privat Ressourcen op Ärem Apparat brauch, an eng Server-URL, wann de MCP-Server op Distanz gehost gëtt.

Wéi eng Tools stellt Django MCP 服务器 MCP an TypingMind zur Verfügung?

Django MCP 服务器 stellt MCP-Funktiounen zur Verfügung, déi Dir op der Plugins-Säit vun TypingMind aktivéiere kënnt, fir se am Chat ze benotzen oder KI-Agenten zouzeweisen.

Muss ech meng API-Schlëssele mat TypingMind deelen, fir Django MCP 服务器 MCP ze benotzen?

Nee. TypingMind setzt op lokal Veraarbechtung a léisst Iech d'Kontroll iwwer Är Modellubidder, API-Schlësselen, Prompts a MCP-Konfiguratioun. Wann Django MCP 服务器 eng Authentifizéierung verlaangt, setzt déi néideg Headeren, OAuth-Astellungen oder lokal Konfiguratioun fir dee MCP-Server derbäi, wann Dir d'Verbindung erstallt.

Änlech MCP-Serveren

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇