Goal: Determine the most effective setup for refactoring a codebase from one language/framework to another (starting with C# .NET API → Python FastAPI) using Cursor's AI tooling ecosystem: MCPs, language servers, skills, agents, rules, and documentation ingestion.
- Strategy Overview
- Architecture
- MCP Language Servers
- Documentation Ingestion
- Cursor Configuration
- Refactoring Workflow
- Suggested Setup Files
- Key Links & References
A cross-language refactoring (C# → Python) is more than a syntax translation — it requires understanding semantics, patterns, and idioms in both ecosystems. The most effective AI-assisted approach combines:
- Deep source understanding via LSP-backed MCPs on the source codebase (C#)
- Validated target generation via LSP-backed MCPs on the target codebase (Python)
- Domain mapping rules that teach the AI how to translate framework-level patterns (ASP.NET → FastAPI)
- Specialized agents that decompose the work into focused phases (analyze, convert, validate)
- Documentation as context so the AI knows both frameworks' APIs intimately
Traditional AI refactoring relies entirely on the model's training data. This setup augments the model with:
- Live code intelligence (go-to-definition, find-references, diagnostics) via language servers
- Authoritative docs (not hallucinated API knowledge) via doc ingestion
- Structured workflow (not ad-hoc prompting) via skills and agents
- Persistent conventions (not re-explained every session) via rules
┌─────────────────────────────────────────────────────────┐
│ Cursor Agent │
│ │
│ ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Rules │ │ Skills │ │ Agents │ │ Docs │ │
│ │(patterns)│ │(workflow)│ │(focused) │ │(context) │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ └──────────────┼───────────┼──────────────┘ │
│ ▼ ▼ │
│ ┌──────────────────────┐ │
│ │ MCP Protocol Hub │ │
│ └──────┬───────┬───────┘ │
│ │ │ │
└─────────────────────┼───────┼────────────────────────────┘
│ │
┌────────────┘ └────────────┐
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ C# LSP (MCP) │ │ Python LSP (MCP)│
│ via MCLSP │ │ via MCLSP │
│ │ │ │
│ • go-to-def │ │ • diagnostics │
│ • find-refs │ │ • completions │
│ • hover/type info│ │ • type checking │
│ • diagnostics │ │ • find-refs │
└─────────────────┘ └─────────────────┘
│ │
▼ ▼
Source Codebase Target Codebase
(C# .NET API) (Python FastAPI)
MCLSP (MCP Language Server) is a bridge that exposes any Language Server Protocol (LSP) server as an MCP (Model Context Protocol) server. This gives the AI agent programmatic access to the same code intelligence that your editor uses — go-to-definition, find-references, hover info, diagnostics, completions, and more.
- Repository: nicobailey/mcp-language-server
- Protocol: Wraps any LSP-compliant server into MCP tool calls
- Key benefit: The AI can ask the language server about code rather than guessing from raw text
| Capability | How It Helps Refactoring |
|---|---|
| Go to Definition | Trace C# method implementations to understand full behavior before converting |
| Find References | Discover all callers of a method to ensure nothing is missed in migration |
| Hover / Type Info | Understand exact types, generics, nullability — critical for correct Python typing |
| Diagnostics | Validate generated Python code in real-time; catch errors before you even run it |
| Document Symbols | Get a structural overview of classes, methods, properties in a file |
| Completions | Verify that generated Python code uses valid FastAPI/Pydantic APIs |
The C# LSP is powered by OmniSharp or the newer Roslyn-based csharp-ls.
{
"mcpServers": {
"csharp-lsp": {
"command": "npx",
"args": [
"-y",
"mcp-language-server",
"--workspace", "/path/to/your/csharp-project",
"--language", "csharp"
],
"env": {
"LSP_COMMAND": "OmniSharp",
"LSP_ARGS": "-lsp --encoding utf-8"
}
}
}
}- Install OmniSharp: OmniSharp Releases
- Requires .NET SDK installed on the machine
- Provides rich type info, refactoring suggestions, and full Roslyn analysis
{
"mcpServers": {
"csharp-lsp": {
"command": "npx",
"args": [
"-y",
"mcp-language-server",
"--workspace", "/path/to/your/csharp-project",
"--language", "csharp"
],
"env": {
"LSP_COMMAND": "csharp-ls",
"LSP_ARGS": ""
}
}
}
}- Install:
dotnet tool install --global csharp-ls - Repository: razzmatazz/csharp-language-server
- Lighter weight, still provides go-to-def, find-refs, diagnostics
The recommended Python LSP for this workflow is Pyright (best type checking) or pylsp (more extensible).
{
"mcpServers": {
"python-lsp": {
"command": "npx",
"args": [
"-y",
"mcp-language-server",
"--workspace", "/path/to/your/python-project",
"--language", "python"
],
"env": {
"LSP_COMMAND": "pyright-langserver",
"LSP_ARGS": "--stdio"
}
}
}
}- Install:
npm install -g pyrightorpip install pyright - Repository: microsoft/pyright
- Best for strict type checking — catches type mismatches in generated code
{
"mcpServers": {
"python-lsp": {
"command": "npx",
"args": [
"-y",
"mcp-language-server",
"--workspace", "/path/to/your/python-project",
"--language", "python"
],
"env": {
"LSP_COMMAND": "pylsp",
"LSP_ARGS": ""
}
}
}
}- Install:
pip install python-lsp-server[all] - Repository: python-lsp/python-lsp-server
- Extensible via plugins (mypy, ruff, rope for refactoring)
Add both to your ~/.cursor/mcp.json (or project-level .cursor/mcp.json):
{
"mcpServers": {
"csharp-lsp": {
"command": "npx",
"args": ["-y", "mcp-language-server", "--workspace", "/path/to/source-csharp", "--language", "csharp"],
"env": {
"LSP_COMMAND": "csharp-ls",
"LSP_ARGS": ""
}
},
"python-lsp": {
"command": "npx",
"args": ["-y", "mcp-language-server", "--workspace", "/path/to/target-python", "--language", "python"],
"env": {
"LSP_COMMAND": "pyright-langserver",
"LSP_ARGS": "--stdio"
}
}
}
}| MCP | Purpose | Link |
|---|---|---|
| Context7 | Fetch up-to-date library documentation on demand | upstash/context7 |
| mcp-filesystem | Safe filesystem access for reading/writing project files | modelcontextprotocol/servers |
| mcp-git | Git operations (diff, log, blame) for tracking migration progress | modelcontextprotocol/servers |
| mcp-memory | Persistent memory across sessions for long-running migrations | modelcontextprotocol/servers |
Feeding the AI authoritative documentation is critical — it prevents hallucinated APIs and ensures idiomatic output.
Cursor has native documentation indexing. Add docs via Cursor Settings → Features → Docs:
| Doc Source | URL |
|---|---|
| FastAPI | https://fastapi.tiangolo.com |
| Pydantic v2 | https://docs.pydantic.dev/latest/ |
| SQLAlchemy 2.0 | https://docs.sqlalchemy.org/en/20/ |
| ASP.NET Core Web API | https://learn.microsoft.com/en-us/aspnet/core/web-api/ |
| Entity Framework Core | https://learn.microsoft.com/en-us/ef/core/ |
Once indexed, reference them in prompts with @FastAPI, @Pydantic, etc.
Context7 fetches up-to-date documentation snippets at query time — no pre-indexing needed.
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp@latest"]
}
}
}- Repository: upstash/context7
- The agent can call
resolve-library-idandget-library-docsto fetch docs for any library - Great for looking up specific API details mid-conversion
For mapping-specific knowledge that doesn't exist in any public doc, create reference rules:
.cursor/rules/
dotnet-to-fastapi-patterns.mdc # Pattern mapping reference
entity-framework-to-sqlalchemy.mdc # ORM mapping reference
@Docsfor broad framework knowledge (always available in context)- Context7 MCP for on-demand lookups of specific APIs during conversion
- Local rules for project-specific mapping patterns the AI should follow
Rules provide persistent context that applies automatically. For refactoring, use them to encode:
- Pattern mappings (C# construct → Python equivalent)
- Naming conventions in the target codebase
- Architecture decisions for the Python project
See suggested-rules/ for ready-to-use rule files.
Skills define reusable workflows the agent can follow. For refactoring, create skills for:
- Analyzing a C# controller and producing a conversion plan
- Converting a single endpoint with validation
- Migrating data models (Entity Framework → SQLAlchemy/Pydantic)
See suggested-skills/ for ready-to-use skill files.
Agents are specialized sub-agents with focused system prompts. For refactoring, decompose into:
| Agent | Role |
|---|---|
source-analyzer |
Reads and understands the C# codebase structure using the C# LSP |
code-converter |
Translates C# code to Python following the mapping rules |
target-validator |
Validates generated Python code using the Python LSP and runs tests |
See suggested-agents/ for ready-to-use agent files.
- Configure MCPs — Set up C# LSP and Python LSP via MCLSP
- Index documentation — Add FastAPI, Pydantic, ASP.NET docs to Cursor @Docs
- Install rules — Copy suggested rules to
.cursor/rules/ - Install skills & agents — Copy to
.cursor/skills/and.cursor/agents/ - Scaffold target project — Create the FastAPI project structure
- Map the architecture — Use C# LSP
document-symbolsto catalog all controllers, services, models - Trace dependencies — Use
find-referencesto build a dependency graph - Identify patterns — Categorize endpoints by complexity (CRUD, auth, business logic)
- Create a migration plan — Ordered list of files/components to convert, starting with models
Convert in dependency order:
- Data Models — C# classes / EF entities → Pydantic models + SQLAlchemy models
- DTOs / ViewModels — Request/response shapes → Pydantic schemas
- Services / Repositories — Business logic layer → Python service classes
- Controllers — ASP.NET controllers → FastAPI routers
- Middleware — Auth, logging, error handling → FastAPI middleware/dependencies
- Configuration — appsettings.json → Python config (pydantic-settings)
- LSP diagnostics — Run Python LSP to catch type errors, import issues
- Unit tests — Convert or rewrite C# tests as pytest tests
- API contract tests — Verify endpoints match the original OpenAPI spec
- Integration tests — Test database operations, auth flows
- Use
@Docsand Context7 to look up unfamiliar APIs - Use the C# LSP to deep-dive into complex source methods
- Use the Python LSP to validate each converted file before moving on
This project includes ready-to-use configuration files:
refactoring-research/
├── README.md # This document
├── suggested-rules/
│ ├── dotnet-to-fastapi-patterns.mdc # C# → Python pattern mapping
│ └── refactoring-conventions.mdc # General refactoring conventions
├── suggested-skills/
│ └── convert-endpoint/
│ └── SKILL.md # Workflow for converting a single endpoint
├── suggested-agents/
│ ├── source-analyzer.md # C# codebase analysis agent
│ ├── code-converter.md # Cross-language conversion agent
│ └── target-validator.md # Python validation agent
└── mcp-config-example.json # Example MCP configuration
| Resource | Link |
|---|---|
| MCP Language Server (MCLSP) | https://github.com/nicobailey/mcp-language-server |
| Model Context Protocol Spec | https://modelcontextprotocol.io |
| MCP Servers Collection | https://github.com/modelcontextprotocol/servers |
| Context7 (Doc Fetching MCP) | https://github.com/upstash/context7 |
| OmniSharp (C# LSP) | https://github.com/OmniSharp/omnisharp-roslyn |
| csharp-ls (C# LSP, lighter) | https://github.com/razzmatazz/csharp-language-server |
| Pyright (Python LSP) | https://github.com/microsoft/pyright |
| python-lsp-server (pylsp) | https://github.com/python-lsp/python-lsp-server |
| Resource | Link |
|---|---|
| Cursor Rules | https://docs.cursor.com/context/rules |
| Cursor MCP Setup | https://docs.cursor.com/context/model-context-protocol |
| Cursor @Docs | https://docs.cursor.com/context/@-symbols/@-docs |
| Cursor Agents | https://docs.cursor.com/agent |
| Framework | Documentation URL |
|---|---|
| FastAPI | https://fastapi.tiangolo.com |
| Pydantic v2 | https://docs.pydantic.dev/latest/ |
| SQLAlchemy 2.0 | https://docs.sqlalchemy.org/en/20/ |
| Uvicorn | https://www.uvicorn.org |
| pytest | https://docs.pytest.org/en/stable/ |
| ASP.NET Core Web API | https://learn.microsoft.com/en-us/aspnet/core/web-api/ |
| Entity Framework Core | https://learn.microsoft.com/en-us/ef/core/ |
| AutoMapper | https://docs.automapper.org |
| C# / .NET Concept | Python / FastAPI Equivalent | Notes |
|---|---|---|
| Controller | Router (APIRouter) |
Group by resource/domain |
[HttpGet], [HttpPost] |
@router.get(), @router.post() |
Decorator-based routing |
| Action method params | Function params with type hints | FastAPI auto-validates |
[FromBody] |
Pydantic model param | Auto-parsed from request body |
[FromQuery] |
Query() param |
With default/validation |
[FromRoute] |
Path param | Part of the route string |
[Authorize] |
Depends(get_current_user) |
Dependency injection |
| DI (constructor injection) | Depends() |
FastAPI's DI system |
IActionResult / ActionResult<T> |
Return type hint + Response |
FastAPI auto-serializes |
Entity Framework DbContext |
SQLAlchemy Session |
Via Depends(get_db) |
| EF Migrations | Alembic | Schema migration tool |
| AutoMapper | Manual or Pydantic model_validate |
Model-to-schema conversion |
appsettings.json |
pydantic-settings / .env |
Environment-based config |
| Middleware | FastAPI middleware / Depends |
@app.middleware("http") |
ILogger<T> |
logging module or loguru |
Python standard logging |
| Model validation attributes | Pydantic Field() validators |
Field(min_length=1, max_length=100) |
async Task<T> |
async def → T |
Native async in both |
| Exception filters | Exception handlers | @app.exception_handler() |
| Background services | FastAPI BackgroundTasks or Celery |
Depends on complexity |