TL;DR
- A custom MCP server in Python is one file: create an
MCPServerfrom the officialmcpSDK, put@mcp.tool()on plain functions, callmcp.run(). On mcp 1.x the same class isFastMCP. - The server below parses a repo with the stdlib
astmodule into an import graph and exposes three tools:who_imports,imports_ofandmost_imported. It is 116 lines with docstrings and blank lines. - On Django (2,943 Python files) the first call took 30 to 36 seconds to parse everything, then each answer came back in about 10 ms.
who_imports("django.utils.deprecation")returned 83 modules, the same setgit grepfinds. - It only sees static imports. Django loads its default email backend from a string in settings, so the graph shows 3 test modules importing it and nothing else.
Everything below ran on 17 November 2026: mcp 2.3.0 (and 1.30.0 for the FastMCP check), Python 3.13.5, Django at commit 6a8248f, Claude Code 2.1.288 with Haiku 4.5.
Coding agents are good at reading files and bad at knowing which files to read. "Who imports this module" is the question they answer by grepping, and grep gets it wrong the moment someone writes from . import deprecation. An import graph answers it in one call. So here is a small MCP server that builds one for a Python repo and lets any MCP client (Claude Code, Cursor, your own script) ask it questions.
What does a custom MCP server need?
Three things:
- A process that speaks the Model Context Protocol. The official Python SDK (
pip install mcp) handles that. Over stdio, the client starts your script and talks JSON-RPC on its stdin and stdout. - Tools. Each tool is a Python function. The SDK reads the function name, the type hints and the docstring and turns them into the tool's name, input schema and description. The description is what the model reads when it decides whether to call your tool, so write it for the model.
- Data worth asking about. Here that is the import graph.
Set up a venv and install the SDK:
python -m venv venv venv/bin/pip install mcp # venv\Scripts\pip on Windows venv/bin/pip show mcp | head -2 Name: mcp Version: 2.3.0 In mcp 2.x the high-level server class is MCPServer in mcp.server.mcpserver. Many tutorials still use mcp 1.x, where it is FastMCP in mcp.server.fastmcp. If you import the old path on 2.x, the SDK tells you exactly that:
ModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed ... The server: a Python import graph in 116 lines
Save this as codegraph_server.py:
"""A small MCP server that answers import questions about a Python codebase.""" import ast import os import sys from collections import defaultdict from functools import cache from pathlib import Path from mcp.server.mcpserver import MCPServer ROOT = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() SKIP_DIRS = {".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist"} mcp = MCPServer("codegraph") def module_name(path: Path) -> str: parts = list(path.relative_to(ROOT).with_suffix("").parts) if parts[-1] == "__init__": parts.pop() return ".".join(parts) @cache def graph(): """Parse every .py file once and return (files, imports, importers).""" files = {} # module name -> file path for folder, dirs, names in os.walk(ROOT): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] # prune, do not descend for name in names: if name.endswith(".py"): path = Path(folder, name) files[module_name(path)] = path imports = defaultdict(set) # module -> modules it imports for mod, path in files.items(): try: tree = ast.parse(path.read_bytes()) except (SyntaxError, ValueError): continue is_pkg = path.name == "__init__.py" for node in ast.walk(tree): if isinstance(node, ast.Import): targets = [alias.name for alias in node.names] elif isinstance(node, ast.ImportFrom): base = node.module or "" if node.level: # relative import: resolve against this package pkg = mod.split(".") drop = node.level - 1 if is_pkg else node.level pkg = pkg[: len(pkg) - drop] if drop else pkg base = ".".join(pkg + ([base] if base else [])) # "from pkg import name": name is a submodule or an attribute targets = [f"{base}.{a.name}" for a in node.names] else: continue for target in targets: while target and target not in files: # a.b.Class -> a.b target = target.rpartition(".")[0] if target and target != mod: imports[mod].add(target) importers = defaultdict(set) for mod, deps in imports.items(): for dep in deps: importers[dep].add(mod) return files, imports, importers def resolve(name: str) -> str | None: """Accept a dotted module name or a file path relative to the repo root.""" files = graph()[0] if name.endswith(".py") or "/" in name or "\\" in name: path = (ROOT / name).resolve() name = module_name(path) if path.is_relative_to(ROOT) else name return name if name in files else None @mcp.tool() def who_imports(module: str) -> str: """List the modules that import a module (dotted name or file path).""" mod = resolve(module) if mod is None: return f"{module} is not a module in this repo" users = sorted(graph()[2][mod]) return f"{len(users)} modules import {mod}:\n" + "\n".join(users) @mcp.tool() def imports_of(module: str) -> str: """List the repo modules that a module imports (dotted name or file path).""" mod = resolve(module) if mod is None: return f"{module} is not a module in this repo" deps = sorted(graph()[1][mod]) return f"{mod} imports {len(deps)} repo modules:\n" + "\n".join(deps) @mcp.tool() def most_imported(limit: int = 10, prefix: str = "") -> str: """Rank modules by how many other modules import them. prefix limits both the ranked modules and their importers to one package, for example "django.db" (leave empty for the whole repo). """ files, _, importers = graph() def inside(m: str) -> bool: return not prefix or m == prefix or m.startswith(prefix + ".") counts = {m: sum(inside(u) for u in importers[m]) for m in files if inside(m)} top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:limit] lines = [f"{n:5d} {m}" for m, n in top] return f"{len(counts)} modules scanned under {prefix or ROOT.name}\n" + "\n".join(lines) if __name__ == "__main__": mcp.run() # stdio transport by default On mcp 1.x, change the one import to from mcp.server.fastmcp import FastMCP as MCPServer. I ran that variant on mcp 1.30.0 with the 1.x ClientSession and stdio_client, and it listed the same three tools and answered most_imported with no other change.
How does it turn Python files into an import graph?
The interesting part is graph(). Four details carry most of the weight.
Module names come from paths. django/db/models/base.py becomes django.db.models.base, and __init__.py becomes the package name. This assumes the repo root is on the import path, which holds for most projects. A src/ layout needs src as the root you pass in.
Relative imports are resolved by hand. from . import x inside django/core/mail/message.py means django.core.mail.x. Inside django/core/mail/__init__.py the same line means the same package, because a package's __init__ is the package. That is the drop = node.level - 1 if is_pkg else node.level line. Grep cannot do this, which is the main reason an AST beats a text search here.
from pkg import name is ambiguous. name can be a submodule (from django.db.models import fields) or an attribute (from django.db.models import Q). The loop builds pkg.name and walks up one dot at a time until it hits a real module file. A submodule stops at itself, a class or function stops at the module that defines or re-exports it. Anything that never hits a repo file (stdlib, third-party) drops out, so the graph only has edges inside your repo.
It parses once. @cache on graph() means the first tool call pays for the parse and every later call is a dict lookup. There is no file watcher. Restart the server after big changes.
ast.walk visits every node, so imports inside functions and inside if TYPE_CHECKING: blocks count the same as top-level ones. For "what is affected if I change this module" that is what you want. For "which import cycle will fail at load time" it is not, and the difference is the subject of my post on Python circular imports.
How do you test an MCP server without an editor?
Write a client. The SDK ships one, and it starts the server as a subprocess over stdio exactly as an editor would. This is try_it.py:
"""Start codegraph_server.py over stdio and call its tools, like an agent would.""" import asyncio import sys import time from mcp import Client, StdioServerParameters REPO = sys.argv[1] CALLS = [ ("most_imported", {"limit": 8}), ("most_imported", {"limit": 5, "prefix": "django.db"}), ("who_imports", {"module": "django/utils/deprecation.py"}), ("imports_of", {"module": "django.db.models.base"}), ("who_imports", {"module": "django.core.mail.backends.smtp"}), ("who_imports", {"module": "django.not_a_module"}), ] async def main() -> None: server = StdioServerParameters( command=sys.executable, args=["codegraph_server.py", REPO] ) async with Client(server) as client: tools = await client.list_tools() for tool in tools.tools: print(f"tool: {tool.name} {list(tool.input_schema['properties'])}") for name, args in CALLS: start = time.perf_counter() result = await client.call_tool(name, args) took = time.perf_counter() - start print(f"\n>>> {name}({args}) [{took:.2f}s]") print(result.content[0].text) asyncio.run(main()) I pointed it at a clone of Django:
venv/bin/python try_it.py ../django tool: who_imports ['module'] tool: imports_of ['module'] tool: most_imported ['limit', 'prefix'] >>> most_imported({'limit': 8}) [30.29s] 2943 modules scanned under django 798 django.test 639 django.db.models 369 django.core.exceptions 316 django.db 248 django.conf 219 django.urls 213 django.test.utils 203 django.db.migrations >>> most_imported({'limit': 5, 'prefix': 'django.db'}) [0.01s] 123 modules scanned under django.db 45 django.db 32 django.db.models 30 django.db.models.expressions 20 django.db.models.fields 16 django.db.models.functions >>> who_imports({'module': 'django/utils/deprecation.py'}) [0.00s] 83 modules import django.utils.deprecation: django.conf django.contrib.admin.options django.contrib.postgres.aggregates.general django.contrib.postgres.aggregates.mixins django.core.mail ... tests.validators.tests tests.version.tests >>> imports_of({'module': 'django.db.models.base'}) [0.01s] django.db.models.base imports 24 repo modules: django django.apps django.conf django.core.checks django.core.exceptions django.db ... django.utils.translation >>> who_imports({'module': 'django.core.mail.backends.smtp'}) [0.00s] 3 modules import django.core.mail.backends.smtp: tests.mail.test_backends tests.mail.test_handler tests.mail.tests >>> who_imports({'module': 'django.not_a_module'}) [0.00s] django.not_a_module is not a module in this repo A few things to read off this:
- The first call is the slow one. 30.29 s in this run and 36 s in another, almost all of it
ast.parseover 2,943 files and about 20 MB of source. The calls after it took 10 ms or less. - The whole repo includes the tests.
django.testtops the ranking because Django's test suite has thousands of modules that import it. Theprefixargument scopes both sides to one package, and insidedjango.dbthe most depended-on file after the two package roots isexpressions.py(30 importers). - Paths and dotted names both work. Agents pass whatever they last saw, so
resolve()accepts either. - Unknown names get a plain sentence back, not an exception. The model can read it and try another name.
Does the graph agree with git grep?
For django.utils.deprecation, a fair check is a grep that catches the absolute import and both relative forms:
git grep -lE "django\.utils\.deprecation|from django\.utils import .*deprecation|from \.+deprecation import|from \.+ import .*\bdeprecation\b" -- '*.py' | wc -l 84 Converting those 84 paths to module names and diffing against the tool's 83 left exactly one line: django.utils.deprecation itself, which mentions its own dotted name in a string. Same 83 modules, 29 in django/ and 54 in tests/. The difference is that the grep took me a few tries to write, and an agent would have to get it right every time, for every module.
How do you add a custom MCP server to Claude Code?
For everyday use, register it once from inside your repo:
claude mcp add codegraph -- /abs/path/venv/bin/python /abs/path/codegraph_server.py /abs/path/your-repo Cursor and most other clients take the same mcpServers JSON shape (the Cursor MCP setup guide has the file locations). For a one-off headless test I passed a config file instead, so nothing was written to my Claude Code settings:
{ "mcpServers": { "codegraph": { "command": "/abs/path/venv/bin/python", "args": ["/abs/path/codegraph_server.py", "/abs/path/django"] } } } Then one non-interactive run from inside the Django clone, on the cheapest model, with my user settings and other MCP servers switched off. Read, Grep and Glob were available, but only the three codegraph tools were pre-approved:
claude -p "I want to change the public behaviour of django/utils/deprecation.py. Which parts of the django package (not the tests) import it? Group them by top-level subpackage and keep the answer short." \ --model haiku \ --mcp-config codegraph.json --strict-mcp-config --setting-sources local \ --tools "Read,Grep,Glob" \ --allowedTools "mcp__codegraph__who_imports,mcp__codegraph__imports_of,mcp__codegraph__most_imported" \ --permission-prompts none --output-format stream-json --verbose The transcript, reformatted from the JSON stream and with the tool result cut:
tool_use mcp__codegraph__who_imports {"module": "django.utils.deprecation"} tool_result 83 modules import django.utils.deprecation: django.conf django.contrib.admin.options ... assistant Here are the non-test imports, grouped by top-level subpackage: | Subpackage | Modules | |---|---| | **conf** | conf | | **contrib** | admin.options, postgres.aggregates.* (2 modules) | | **core** | mail*, management.commands, paginator, signing, validators | | **db** | backends.base.creation, models.fields*, models.query, models.sql.*, transaction | | **http** | response | | **template** | base, engine | | **utils** | crypto, functional, html, log, version | The largest impacts are in **core** (mail, management, pagination, signing, validators) and **db** (models and backends). **contrib** also uses it, so changes to the public API will ripple through fairly widely. result num_turns 2, duration 31.0 s, cost $0.029 One tool call, no file reads, no grep. Most of the 31 seconds was the first parse. Checked against the real list, the grouping is right except for one module the model left out of the db row (django.db.models.functions.datetime). The tool returned it. Summarising is where a small model slips, so for an edit plan, ask for the module list itself.
A second prompt asked which modules inside django.db the rest of django.db depends on most, and what the top non-package module imports. Haiku chained two calls on its own:
tool_use mcp__codegraph__most_imported {"prefix": "django.db", "limit": 10} tool_result 123 modules scanned under django.db 45 django.db 32 django.db.models 30 django.db.models.expressions ... tool_use mcp__codegraph__imports_of {"module": "django.db.models.expressions"} tool_result django.db.models.expressions imports 11 repo modules: django.core.exceptions django.db django.db.models ... That run cost $0.012. Two runs is an anecdote, not a benchmark, but in both of them the model picked the graph tool over grep without being told to.
What can a 100-line import graph not see?
- Imports that are not import statements. Django's default email backend is set as a string,
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"inglobal_settings.py, and loaded withimport_string. The graph shows 3 test modules importingsmtp.pyand no production code, which is accurate about imports and wrong about usage. The same goes forimportlib.import_module,INSTALLED_APPS, entry points and plugin registries. Before calling anything unused based on this graph, grep for its dotted name as a string. - Calls and names. It knows
expressions.pyimportsdjango.db.models. It does not know that the import sits inside one method and pulls inJSONField(line 1249). Function-level and top-level imports look the same here. - Packages count as modules.
from django.db import connectionis an edge todjango/db/__init__.py, which is correct but makes package roots look busy. - Anything that is not Python, and anything that changed since the first call.
- Big repos. One process, one thread, a full re-parse on every restart. Caching the graph to disk keyed by file modification time, or parsing with a
ProcessPoolExecutor, would be the next 20 lines.
Where does a bigger code graph tool help?
The pattern scales: parse once, store a graph, expose a few narrow tools with good docstrings. What changes at scale is everything around it. Tools built for this parse many languages with tree-sitter, resolve calls and not just imports, update incrementally on each commit, and add git history (who changes a file, what changes with it) next to the graph. repowise is one of them (I build it). The comparison of code graph MCP servers runs several side by side on the same questions.
For one Python repo and the question "who imports this", the 116 lines above get you the same answer as a careful grep, in one tool call.
How I ran this
All runs on 17 November 2026 on a Windows laptop: Python 3.13.5, a fresh venv with mcp 2.3.0, and a second venv with mcp 1.30.0 for the FastMCP check (run against FastAPI). The repo is a full clone of Django (6a8248f for the server runs, d3954c9 after the clone was updated, which is where the git grep check ran). The tool output above is the raw output of try_it.py, cut where marked with .... Claude Code 2.1.288 with --model haiku (claude-haiku-4-5), two headless runs with --strict-mcp-config and --setting-sources local, transcripts taken from --output-format stream-json. Timings are single runs on one machine.
FAQ
How do I build a custom MCP server in Python?
Install the official SDK with pip install mcp, create MCPServer("name") (FastMCP on mcp 1.x), decorate functions with @mcp.tool() and call mcp.run(). Type hints become the input schema and the docstring becomes the description the model reads. A client starts the script over stdio, so there is no web server to run.
What is the difference between FastMCP and MCPServer?
They are the same high-level server class in the official Python SDK under two names. mcp 1.x calls it FastMCP in mcp.server.fastmcp. mcp 2.x renamed it MCPServer in mcp.server.mcpserver and raises an error with the new path if you use the old import. The @mcp.tool() decorator and mcp.run() work the same in both for a server like this one.
How do I test an MCP server before connecting it to Claude Code or Cursor?
Use the SDK's own client. Client(StdioServerParameters(command=..., args=[...])) starts the server as a subprocess, and list_tools() and call_tool() show exactly what an editor will see. Once that works, register the server with claude mcp add or your editor's mcpServers config.

