django-openapi-mcp

django-openapi-mcp

Introspects a Django REST API's OpenAPI schema and exposes each endpoint as an MCP tool, enabling Claude or any MCP client to interact with the API via natural language.

Category
访问服务器

README

django-openapi-mcp

This repository is an educational example designed to demonstrate how you can seamlessly bridge Django, Django REST Framework, and the Model Context Protocol (MCP). Feel free to clone, explore, and adapt this code into your own projects!

By leveraging OpenAPI in your Django projects, your API's specification is already complete. We automatically transform existing documentation into ready-to-use AI tools, eliminating the need for hand-written glue code entirely.

If you want an AI assistant (Claude and friends) to operate your Django app, fetch a record, run a filtered query, take an action etc. They need "tools" (i.e. machine-readable descriptions of what your API does). The usual way is to hand-write one for every endpoint, then maintain them forever as the API changes.

This reference project demonstrates how to skip that. This framework reads the OpenAPI schema already generated by drf-spectacular for your Django REST Framework project and automatically exposes each endpoint as a Model Context Protocol (MCP) tool. Your schema is the single source of truth: change the API, and the tools update instanly.

It's built on the official mcp Python SDK, so it speaks the real protocol over stdio (Claude Desktop / Claude Code) and Streamable HTTP (production).

  DRF views ──drf-spectacular──▶ OpenAPI schema ──▶ MCP tools ──▶  Any MCP client (stdio + Streamable HTTP)

Features

  • Your schema is the single source of truth. Each operationId becomes a tool name, parameters become the tool's inputs, descriptions carry through. Just define an endpoint once.
  • Safe by default. Only read-only GET endpoints become tools. Write operations (POST/PUT/PATCH/DELETE) are strictly opt-in. Nothing that can change or delete data is exposed to an AI unless you say so.
  • Authentication included. Real Django APIs are locked down, so the generated tools carry credentials (DRF token, bearer/JWT, or a custom header) through to your endpoints. Auth applies to every call.
  • Zero config to start. If drf-spectacular already works in your project, so does this.
  • Not tied to any one AI. Built on the official SDK over stdio and Streamable HTTP. Anything that speaks MCP (Claude Desktop, Claude Code, your own agent loop) can call the tools. No model or vendor lock-in.

Exploring the Framework

Because this is a reference framework to be adapted into your own projects, the best way to understand it is to clone the repository and run the bundled demo.

git clone https://github.com/Shanahan-Suresh/django-openapi-mcp
cd django-openapi-mcp

Setup

To see how this pattern is integrated, look at the provided example project. It relies on DRF and drf-spectacular. If you adapt this source code for your own project, the wiring requires adding the app and one settings block:

# settings.py
INSTALLED_APPS = [
    # ...
    "rest_framework",
    "drf_spectacular",
    "django_openapi_mcp",  # (assuming you copied this folder from the repo into your project)
]

REST_FRAMEWORK = {
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}

DJANGO_OPENAPI_MCP = {
    "BASE_URL": "http://127.0.0.1:8000",   # where generated tools send requests
}

That's the whole setup. Now run the server:

python manage.py run_mcp_server --transport stdio        # for Claude Desktop / Code
python manage.py run_mcp_server --transport http --port 8800   # Streamable HTTP at /mcp

Two things happen in two places. The schema is read in-process by drf-spectacular when the server starts (no extra HTTP round-trip, no self-call). Tool execution hits your live API at BASE_URL. So your API server needs to be running before an AI actually calls a tool, but not just to list them.

Connect a client

Any MCP-compatible client can launch the server and call the generated tools. With Claude Desktop, open Settings → Developer → Edit Config. That opens the correct claude_desktop_config.json for your install. Add:

{
  "mcpServers": {
    "my-django-api": {
      "command": "/path/to/your/.venv/bin/python",
      "args": ["manage.py", "run_mcp_server", "--transport", "stdio"],
      "cwd": "/path/to/your/django/project",
      "env": { "DJANGO_SETTINGS_MODULE": "config.settings" }
    }
  }
}

Restart the client and your endpoints show up as tools. Every other client connects the same way: Claude Code via claude mcp add, a custom agent over stdio, or Streamable HTTP at /mcp for a deployed server.

Want to confirm it works before wiring up any client? The example/ project ships a runnable probe script and works with the MCP Inspector. See example/README.md. For the full Claude Desktop walkthrough, see docs/claude-desktop.md.

Configuration

All keys live under DJANGO_OPENAPI_MCP in settings.py:

Key Default Purpose
BASE_URL http://localhost:8000 Where generated tools send HTTP requests.
INCLUDE_METHODS ["GET"] HTTP methods to expose. Add write methods to opt in.
EXCLUDE_PATHS [] Path prefixes to skip (e.g. ["/api/schema"]).
INCLUDE_PATHS None If set, only these path prefixes are exposed.
AUTH None Credential passthrough (see below).
SCHEMA_URL None Fetch the schema over HTTP instead of generating it in-process.
SERVER_NAME "django-openapi-mcp" Name advertised to MCP clients.
TIMEOUT 30 HTTP timeout (seconds).

Authentication

DJANGO_OPENAPI_MCP = {
    "AUTH": {"type": "token", "token": "...", "scheme": "Token"},   # Authorization: Token ...
    # {"type": "bearer", "token": "..."}                            # Authorization: Bearer ...
    # {"type": "header", "name": "X-API-Key", "value": "..."}       # custom header
}

Enabling write operations (opt-in)

Read-only is the default. An AI with DELETE access could a bad day waiting to happen. When you actually want write tools, opt in explicitly:

DJANGO_OPENAPI_MCP = {
    "INCLUDE_METHODS": ["GET", "POST"],   # exposes create endpoints too
}

Try the example

The fastest way to see the whole thing work is the runnable demo in example/: a tiny shop API (products + orders, with an in_stock filter). Full walkthrough in example/README.md. The short version:

cd example
python manage.py migrate
python seed.py                       # a few sample products & orders
python manage.py runserver           # terminal 1: the API
python manage.py run_mcp_server      # terminal 2: the MCP server (stdio)

You get four tools (products_list, products_retrieve, orders_list, orders_retrieve), and the in_stock query-param filter shows how a tool argument maps straight through to a query string.


How it works

Three steps, and the source is laid out to match them:

  1. Introspect: drf_spectacular.generators.SchemaGenerator produces the OpenAPI 3 document in-process.
  2. Generate: each operation becomes a tool: operationId → name, summary/description → description, path + query parameters → a JSON Schema ($refs resolved, path params marked required).
  3. Serve: the official SDK's low-level Server advertises the tools (list_tools) and runs them (call_tool) by mapping arguments onto an HTTP request to BASE_URL, with auth attached.

The source mirrors that pipeline:

  • src/django_openapi_mcp/introspect.py: get the OpenAPI schema in-process via drf-spectacular's SchemaGenerator, with a URL fallback and full $ref resolution.
  • src/django_openapi_mcp/tools.py: turn each OpenAPI operation into a tool spec (operationId → name, parameters mapped to JSON Schema, collision handling for duplicate names).
  • src/django_openapi_mcp/server.py: build the MCP server on the SDK's low-level Server, wiring list_tools and call_tool to execute requests against the live API at BASE_URL.
  • src/django_openapi_mcp/transport.py: serve over stdio (Claude Desktop) and Streamable HTTP (production).
  • src/django_openapi_mcp/conf.py / auth.py: config defaults (safe-by-default GET-only) and credential passthrough to every outbound request.

Related projects

There are already several great works in this space, and they're well worth checking out:

License

MIT

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选