Backend Development 19 min read

Integrating FastAPI with MCP for AI‑Driven Test Data Generation

This article explains how to transform a FastAPI service into an MCP‑compatible tool, enabling AI agents to automatically orchestrate multi‑step test data creation, covering installation, project structure, code annotations, tool configuration, and practical integration with the Cursor platform.

DeWu Technology
DeWu Technology
DeWu Technology
Integrating FastAPI with MCP for AI‑Driven Test Data Generation

The article begins with a background on the rising popularity of Model Context Protocol (MCP) and the desire to convert existing test‑data generation tools into MCP‑compliant services that can be orchestrated by AI agents.

AI Data Generation Concept – Describes a typical testing scenario requiring complex pre‑conditions (e.g., a user who has not posted in 30 days, joins a team, posts a dynamic, passes two reviews, and reaches 300 reads). It highlights the need for automated composition of multiple data‑creation scripts.

FastAPI‑MCP Overview – Introduces the FastAPI framework as the base and the uv tool for dependency and virtual‑environment management. Provides the command list for installing uv , creating a virtual environment, activating it, and installing dependencies.

## uv命令
1. 安装uv : `curl -LsSf https://astral.sh/uv/install.sh | sh`
2. 创建环境 - 自定义环境名称和Python版本 `uv venv tools_venv --python 3.12`
3. 激活环境 `source tools_venv/bin/activate`
4. 安装依赖包 `uv pip install -r pyproject.toml`

## 本地启动项目
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

The project structure is shown, including main.py , app package with sub‑folders for api , core , crud , db , models , schemas , and utils , plus Docker and Alembic files.

├── main.py  # 启动 APP 入口文件
├── README.md  # 开发手册
├── Dockerfile  # Docker 镜像文件
├── alembic  # alembic 迁移 DB 自动生成的相关文件
│   ├── README
│   ├── .env.py
│   ├── script.py.mako
│   └── versions  # 存放每次迁移的版本,可用于回滚 DB 版本
├── alembic.ini  # alembic 配置文件
├── app
│   ├── __init__.py  # 注册 app
│   ├── api  # api 开发目录
│   ├── core  # app 的全局配置
│   ├── crud  # 每个 table 的增删改查操作
│   ├── db  # db 配置
│   ├── models  # 存放表结构
│   ├── schemas  # pydantic 模型
│   └── utils  # 工具类
├── .pre-commit-config.yaml  # 配置 git commit 时自动检测工具
└── pyproject.toml  # 依赖库管理

Old solution using the MCP Python SDK required decorating each endpoint with @mcp.tool() , which added significant refactor cost. A minimal demo shows the SDK usage:

from mcp.server.fastmcp import FastMCP
from tools.tools_set import get_user_info
import uvicorn
mcp = FastMCP("Demo")
@mcp.tool()
async def get_user_info_tool(mobile: str) -> Coroutine[Any, Any, Any]:
    """根据输入的手机号获取用户信息"""
    info = get_user_info(mobile)
    return info
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8003)

New solution with fastapi-mcp reduces the boilerplate to three lines:

from fastapi import FastAPI
import uvicorn
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app)
mcp.mount()
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Configuration options such as include_operations , exclude_operations , include_tags , and exclude_tags control which FastAPI routes are exposed as MCP tools. Example combinations are provided.

mcp = FastApiMCP(app, include_operations=["get_user", "create_user"])
# or
mcp = FastApiMCP(app, exclude_operations=["delete_user"])
# or
mcp = FastApiMCP(app, include_tags=["users", "public"])
# or
mcp = FastApiMCP(app, exclude_tags=["admin", "internal"])
# combined example
mcp = FastApiMCP(app, include_operations=["user_login"], include_tags=["public"])
mcp.mount()

Explicit operation_id is recommended for clear tool naming; otherwise FastAPI auto‑generates obscure names that hurt AI accuracy.

# Auto‑generated operation_id (something like "read_user_users__user_id__get")
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

# Explicit operation_id (tool will be named "get_user_info")
@app.get("/users/{user_id}", operation_id="get_user_info")
async def read_user(user_id: int):
    return {"user_id": user_id}

Integration steps for the community data‑generation service include upgrading the FastAPI version, installing fastapi-mcp , adding MCP service creation in main.py , annotating each data‑generation endpoint with clear docstrings, and finally launching the service with uvicorn.run('main:app', host='0.0.0.0', port=8023, reload=True, workers=2) .

Connecting the MCP service to the Cursor AI platform involves creating an mcp.json configuration, enabling the MCP tool in Cursor settings, and verifying the green status indicating a successful connection.

{
  "mcpServers": {
    "fastapi-mcp": {
      "url": "http://localhost:8022/mcp",
      "description": "本地开发环境MCP服务配置"
    },
    "tools-mcp": {
      "url": "http://localhost:8011/mcp",
      "description": "本地开发环境MCP服务配置"
    }
  }
}

Practical scenarios demonstrate how a single natural‑language request (e.g., “I need a test account for a group leader with no posts in the last 30 days, join team A, post a dynamic, pass two reviews, and achieve 300 reads”) is automatically broken down by the AI agent into sequential MCP tool calls, dramatically reducing manual effort.

The article concludes with key takeaways: AI‑driven test data automation lowers the barrier for non‑technical users, fastapi‑mcp offers a low‑cost upgrade path for backend services, clear code annotations are essential for accurate AI tool invocation, and future work includes dynamic workflow orchestration, multi‑agent collaboration, and protocol extensions.

backendAIautomationMCPfastapitest data generation
DeWu Technology
Written by

DeWu Technology

A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.