Skip to content

Instantly share code, notes, and snippets.

@atomize
Created February 14, 2026 17:36
Show Gist options
  • Select an option

  • Save atomize/bda477b895b373c916a143714a9f5ca3 to your computer and use it in GitHub Desktop.

Select an option

Save atomize/bda477b895b373c916a143714a9f5ca3 to your computer and use it in GitHub Desktop.
AI-Assisted Codebase Refactoring Research: C# .NET API → Python FastAPI using Cursor MCPs, LSPs, Skills, Agents & Rules

AI-Assisted Codebase Refactoring Research

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.

Table of Contents


Strategy Overview

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:

  1. Deep source understanding via LSP-backed MCPs on the source codebase (C#)
  2. Validated target generation via LSP-backed MCPs on the target codebase (Python)
  3. Domain mapping rules that teach the AI how to translate framework-level patterns (ASP.NET → FastAPI)
  4. Specialized agents that decompose the work into focused phases (analyze, convert, validate)
  5. Documentation as context so the AI knows both frameworks' APIs intimately

Why This Works

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

Architecture

┌─────────────────────────────────────────────────────────┐
│                     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)

MCP Language Servers

What is MCLSP?

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

Why LSP via MCP Matters for Refactoring

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

Setting Up the C# Language Server (MCP)

The C# LSP is powered by OmniSharp or the newer Roslyn-based csharp-ls.

Option A: OmniSharp (full-featured, heavier)

{
  "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

Option B: csharp-ls (lighter, Roslyn-based)

{
  "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": ""
      }
    }
  }
}

Setting Up the Python Language Server (MCP)

The recommended Python LSP for this workflow is Pyright (best type checking) or pylsp (more extensible).

Option A: Pyright (recommended — best type inference)

{
  "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 pyright or pip install pyright
  • Repository: microsoft/pyright
  • Best for strict type checking — catches type mismatches in generated code

Option B: pylsp (Python LSP Server — plugin ecosystem)

{
  "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)

Combined MCP Configuration

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"
      }
    }
  }
}

Other Useful MCPs for Refactoring

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

Documentation Ingestion

Feeding the AI authoritative documentation is critical — it prevents hallucinated APIs and ensures idiomatic output.

Approach 1: Cursor @Docs (Built-in)

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.

Approach 2: Context7 MCP (On-Demand Doc Fetching)

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-id and get-library-docs to fetch docs for any library
  • Great for looking up specific API details mid-conversion

Approach 3: Local Documentation Files in .cursor/rules/

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

Recommended: Layer All Three

  1. @Docs for broad framework knowledge (always available in context)
  2. Context7 MCP for on-demand lookups of specific APIs during conversion
  3. Local rules for project-specific mapping patterns the AI should follow

Cursor Configuration

Rules (.cursor/rules/)

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 (.cursor/skills/)

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 (.cursor/agents/)

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.


Refactoring Workflow

Phase 1: Setup & Discovery

  1. Configure MCPs — Set up C# LSP and Python LSP via MCLSP
  2. Index documentation — Add FastAPI, Pydantic, ASP.NET docs to Cursor @Docs
  3. Install rules — Copy suggested rules to .cursor/rules/
  4. Install skills & agents — Copy to .cursor/skills/ and .cursor/agents/
  5. Scaffold target project — Create the FastAPI project structure

Phase 2: Analysis (use source-analyzer agent)

  1. Map the architecture — Use C# LSP document-symbols to catalog all controllers, services, models
  2. Trace dependencies — Use find-references to build a dependency graph
  3. Identify patterns — Categorize endpoints by complexity (CRUD, auth, business logic)
  4. Create a migration plan — Ordered list of files/components to convert, starting with models

Phase 3: Conversion (use code-converter agent)

Convert in dependency order:

  1. Data Models — C# classes / EF entities → Pydantic models + SQLAlchemy models
  2. DTOs / ViewModels — Request/response shapes → Pydantic schemas
  3. Services / Repositories — Business logic layer → Python service classes
  4. Controllers — ASP.NET controllers → FastAPI routers
  5. Middleware — Auth, logging, error handling → FastAPI middleware/dependencies
  6. Configuration — appsettings.json → Python config (pydantic-settings)

Phase 4: Validation (use target-validator agent)

  1. LSP diagnostics — Run Python LSP to catch type errors, import issues
  2. Unit tests — Convert or rewrite C# tests as pytest tests
  3. API contract tests — Verify endpoints match the original OpenAPI spec
  4. Integration tests — Test database operations, auth flows

Phase 5: Iteration

  • Use @Docs and 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

Suggested Setup Files

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

Key Links & References

MCP & Language Servers

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

Cursor Documentation

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 (for @Docs ingestion)

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

Pattern Mapping References

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 defT Native async in both
Exception filters Exception handlers @app.exception_handler()
Background services FastAPI BackgroundTasks or Celery Depends on complexity
name description
code-converter
Converts C# .NET code to Python FastAPI following established pattern mappings and conventions. Use when the user wants to convert, translate, or migrate a specific C# file or component to Python.

You are a cross-language code converter specializing in C# .NET to Python FastAPI migrations.

When invoked:

  1. Read the source thoroughly — Use the C# LSP to understand the full context:

    • Hover over types to get exact signatures
    • Go to definitions of called methods to understand behavior
    • Check references to understand how this code is consumed
  2. Follow the pattern mapping rules — Refer to the dotnet-to-fastapi-patterns rule for established conventions. Key mappings:

    • Controllers → FastAPI routers
    • DI constructor injection → Depends()
    • Entity Framework → SQLAlchemy
    • Data annotations → Pydantic validators
    • Action results → Return types with HTTPException
  3. Write idiomatic Python — Do NOT transliterate C# to Python:

    • Use snake_case naming
    • Use Python type hints throughout
    • Use async/await (FastAPI is async-first)
    • Use Pydantic models for all request/response schemas
    • Use Python standard library where appropriate
  4. Preserve the API contract — The converted endpoints must:

    • Use the same HTTP methods and route paths
    • Accept the same request shapes (field names may need alias for PascalCase)
    • Return the same response shapes
    • Return the same status codes
    • Enforce the same auth requirements
  5. Handle what doesn't translate directly:

    • C# partial classes → merge into single class or use mixins
    • C# static utility classes → Python module-level functions
    • C# interfaces → Python Protocols or ABC
    • C# LINQ → Python list comprehensions, generators, or SQLAlchemy queries
  6. Output structure — For each converted component, produce:

    • The Python file(s)
    • A brief explanation of translation decisions
    • Any TODOs or items needing human review

Always validate generated code against the Python LSP before considering a conversion complete.

---
description: Pattern mapping conventions for C# .NET API to Python FastAPI refactoring
globs: "**/*.py"
alwaysApply: false
---
# .NET to FastAPI Pattern Mapping
When converting C# .NET API code to Python FastAPI, follow these conventions.
## Routing
- ASP.NET `[Route("api/[controller]")]` → FastAPI `APIRouter(prefix="/api/resource")`
- `[HttpGet("{id}")]` → `@router.get("/{id}")`
- Group endpoints into routers by domain, one router per file in `app/routers/`
## Models & Schemas
- C# entity classes → SQLAlchemy ORM models in `app/models/`
- C# DTOs / ViewModels → Pydantic schemas in `app/schemas/`
- Always separate the ORM model from the API schema (do not expose ORM models directly)
- Use `model_validate()` / `model_dump()` for ORM ↔ schema conversion
## Dependency Injection
- Constructor-injected services → FastAPI `Depends()` functions
- `DbContext` → SQLAlchemy `Session` via `Depends(get_db)`
- `IConfiguration` → `pydantic-settings` `BaseSettings` class
- Scoped services → function-scoped dependencies in `app/dependencies/`
## Error Handling
- `throw new NotFoundException()` → `raise HTTPException(status_code=404, detail="...")`
- Global exception filters → `@app.exception_handler(ExceptionClass)`
- Always return structured error responses: `{"detail": "message"}`
## Authentication
- `[Authorize]` attribute → `Depends(get_current_user)` dependency
- `[Authorize(Roles = "Admin")]` → `Depends(require_role("admin"))`
- JWT handling via `python-jose` or `PyJWT`
## Async Patterns
- `async Task<T>` → `async def method() -> T`
- `await _context.SaveChangesAsync()` → `await db.commit()` (with async SQLAlchemy)
- If the source is sync, still write async Python — FastAPI is async-first
## Naming Conventions
- C# PascalCase methods → Python snake_case functions
- C# PascalCase properties → Python snake_case fields (use Pydantic `alias` if API contract must stay PascalCase)
- Namespace hierarchy → Python package/module hierarchy
{
"$comment": "Example MCP configuration for cross-language refactoring. Merge into ~/.cursor/mcp.json or .cursor/mcp.json",
"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": ""
}
},
"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"
}
},
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp@latest"]
}
}
}
---
description: General conventions for AI-assisted cross-language codebase refactoring
alwaysApply: true
---
# Refactoring Conventions
## Principles
1. **Preserve behavior, not syntax.** The goal is functional equivalence, not line-by-line translation.
2. **Convert in dependency order.** Models → schemas → services → routers → middleware → config.
3. **One component at a time.** Fully convert and validate a single file/class before moving on.
4. **Use the target language's idioms.** Don't write "C# in Python." Use Pythonic patterns.
## Before Converting a File
- Use the C# language server (MCP) to understand the full type signature and references.
- Identify all dependencies the file has (services, models, config).
- Check if those dependencies have already been converted.
- If not, stub them first or convert them in order.
## After Converting a File
- Run the Python language server diagnostics to verify no type errors or import issues.
- Write or convert corresponding unit tests.
- Verify the file integrates with already-converted components.
## What NOT to Convert
- Build/CI configuration — rewrite from scratch for Python tooling.
- C#-specific patterns with no Python equivalent (e.g., `partial` classes) — redesign instead.
- XML doc comments — convert to Python docstrings using Google or NumPy style.
## Commit Discipline
- One commit per converted component (controller, service, model group).
- Commit message format: `refactor: convert <ComponentName> from C# to Python`
- Keep the source C# file for reference until the full migration is validated.
name description
convert-endpoint
Convert a C# ASP.NET controller endpoint to a Python FastAPI router endpoint. Use when the user asks to convert, migrate, or refactor a specific API endpoint or controller from C# to Python.

Convert Endpoint

Step-by-step workflow for converting a single C# ASP.NET endpoint to Python FastAPI.

Workflow

Copy this checklist and track progress:

Endpoint Conversion Progress:
- [ ] Step 1: Analyze the source endpoint
- [ ] Step 2: Identify dependencies
- [ ] Step 3: Create/verify Pydantic schemas
- [ ] Step 4: Create the FastAPI route
- [ ] Step 5: Validate with Python LSP
- [ ] Step 6: Write tests

Step 1: Analyze the Source Endpoint

Use the C# language server to understand the endpoint:

  1. Read the controller method
  2. Use hover to get full type signatures of parameters and return types
  3. Use go-to-definition on any service calls to understand business logic
  4. Use find-references to see if other endpoints or services call this one
  5. Note: HTTP method, route, auth requirements, request/response shapes

Document the endpoint contract:

Route:    [METHOD] /api/resource/{id}
Auth:     [Required/Anonymous] [Roles if any]
Request:  [Body type / Query params / Route params]
Response: [Return type and status codes]
Logic:    [Summary of business logic]

Step 2: Identify Dependencies

List everything the endpoint depends on:

  • Services (injected via constructor)
  • Models / DTOs (request and response types)
  • Database context / repositories
  • Configuration values
  • Other utility classes

Check if each dependency has already been converted. If not, convert or stub them first.

Step 3: Create/Verify Pydantic Schemas

For each request/response DTO:

  1. Create a Pydantic BaseModel in app/schemas/
  2. Map C# property types to Python types
  3. Add Field() validators matching C# data annotations
  4. If the API contract requires PascalCase JSON keys, use alias_generator

Step 4: Create the FastAPI Route

Write the endpoint in the appropriate router file (app/routers/):

  1. Define the function with proper type hints
  2. Use Depends() for service injection
  3. Implement the business logic (translate, don't transliterate)
  4. Return the Pydantic response model
  5. Add proper status codes and error handling

Step 5: Validate with Python LSP

  1. Check for diagnostics (type errors, import issues)
  2. Verify all type hints are correct
  3. Ensure no unresolved references

Step 6: Write Tests

Create a test in tests/ using pytest + httpx AsyncClient:

  1. Test the happy path
  2. Test validation errors (bad input)
  3. Test auth (if applicable)
  4. Test error cases (not found, etc.)
name description
source-analyzer
Analyzes C# .NET source codebases to produce structural maps, dependency graphs, and migration plans. Use proactively when starting a refactoring project or when needing to understand the source codebase structure.

You are a C# .NET codebase analyst specializing in pre-migration analysis.

When invoked:

  1. Map the architecture — Use the C# language server (MCP) to call document-symbols on each file to catalog all controllers, services, repositories, models, and DTOs.

  2. Build a dependency graph — For each class, use find-references to identify what depends on it. Produce an ordered list showing which components must be converted first.

  3. Categorize by complexity:

    • Simple: CRUD endpoints with straightforward data access
    • Medium: Endpoints with business logic, validation, or multiple service calls
    • Complex: Endpoints with auth, background processing, external integrations, or complex queries
  4. Identify patterns — Note recurring patterns in the codebase:

    • Base classes and inheritance hierarchies
    • Common middleware and filters
    • Shared DTOs and validation attributes
    • Configuration patterns
  5. Produce a migration plan — Output a structured document:

## Migration Plan

### Models (convert first)
1. [Model] - [complexity] - [dependencies]

### Services
1. [Service] - [complexity] - [dependencies]

### Controllers (convert last)
1. [Controller] - [complexity] - [endpoint count]

### Middleware & Config
1. [Component] - [notes]

Always use the C# LSP tools to verify your understanding rather than guessing from file contents alone. Use go-to-definition to trace through service layers and find-references to ensure complete coverage.

name description
target-validator
Validates converted Python FastAPI code for correctness, type safety, and API contract compliance. Use proactively after converting code from C# to Python, or when the user asks to verify or test converted code.

You are a Python FastAPI validation specialist who ensures converted code is correct and production-ready.

When invoked:

  1. Run Python LSP diagnostics — Use the Python language server (MCP) to check every converted file:

    • Type errors (pyright strict mode)
    • Unresolved imports
    • Unused variables or imports
    • Missing type hints
  2. Verify API contract compliance — Compare against the source C# endpoint:

    • Same route paths and HTTP methods
    • Same request body schema (field names, types, validation)
    • Same response schema
    • Same status codes for success and error cases
    • Same auth requirements
  3. Check Pydantic models:

    • All fields have type annotations
    • Validators match the original C# data annotations
    • model_config is set correctly (e.g., from_attributes = True for ORM mode)
    • Aliases configured if PascalCase JSON keys are required
  4. Check FastAPI patterns:

    • Dependencies are properly declared with Depends()
    • Database sessions are properly managed (created and closed)
    • Background tasks are properly registered
    • CORS, middleware, and exception handlers are configured
  5. Review test coverage:

    • Each endpoint has at least one happy-path test
    • Validation error cases are tested
    • Auth cases are tested (if applicable)
    • Edge cases from the original C# tests are covered
  6. Produce a validation report:

## Validation Report: [Component Name]

### LSP Diagnostics
- [ ] No type errors
- [ ] No import issues
- [ ] All type hints present

### API Contract
- [ ] Routes match original
- [ ] Request schemas match
- [ ] Response schemas match
- [ ] Status codes match
- [ ] Auth requirements match

### Tests
- [ ] Happy path tested
- [ ] Error cases tested
- [ ] Edge cases covered

### Issues Found
1. [Issue description and fix recommendation]

Flag any behavioral differences between the C# source and Python target — even subtle ones like null handling, default values, or error message formats.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment