AI coding assistants are great with the file you have open and poor at answering questions about a 40-project solution they have never seen: "Who calls this stored procedure?", "Which tables does cancelling an order touch?", "What does this DTO look like?". This post walks through an MCP server I built to fix that. It reads C# solutions with Roslyn and SQL Server schemas through system views, stores a structured map of both in MongoDB, and exposes that map to any AI assistant as more than 40 Model Context Protocol tools.

#1. The Problem: Context, Not Intelligence

A language model can reason about code perfectly well. What it lacks in a large legacy system is the map: which class lives in which project, which methods call which stored procedures, which tables those procedures read and write. Pasting files into a chat doesn't scale, and plain text search misses what a name means. Order the class, Order the table and order the variable all look the same to grep.

The approach: precompute the map once, keep it fresh on a schedule, and let the assistant query it instead of guessing. The Model Context Protocol (MCP) is the standard way to plug that kind of query surface into Claude, Copilot, Cursor or any other MCP client.

#2. Architecture at a Glance

Diagram
Source repositories ──┐
                       ├──▶ Sync worker ──▶ Roslyn analyzer ────────┐
 SQL Server database ──┘   (per workspace)  Schema extractor ───────┤
                                                                    ▼
                                                   MongoDB (one database per workspace)
                                                                    │
 AI assistant ◀──── MCP endpoint /{workspace}/mcp ◀─── tool executor ┘
  • Sync worker: a background service that, per workspace and on a schedule, downloads the source, analyses it and extracts the database schema.
  • Roslyn analyzer: turns every class and method into structured metadata: signatures, dependencies, stored procedures used, complexity and documentation.
  • Schema extractor: reads tables, columns, keys, indexes and stored procedures from SQL Server's catalogue views.
  • MongoDB: one database per workspace, holding classes, methods, method source, tables and stored procedures.
  • MCP endpoint: JSON-RPC over HTTP at /{workspace}/mcp, backed by a single tool executor.
  • Blazor dashboard: workspaces, sync status and live logs for whoever operates it.

#3. Step 1: Fetching Source Without a Working Copy

The server never keeps a clone. Each sync asks the Git host's REST API for the repository's full item list (optionally on a specific branch), then downloads every file into a directory created for that run only:

C#
// 1. List every item in the repository (optionally on a given branch)
var itemsUrl = $"{baseUrl}/repositories/{repoId}/items"
             + $"?scopePath=/&recursionLevel=Full{branchFilter}";

// 2. Download each file into a throwaway directory for this sync run
foreach (var item in items.Where(i => !i.IsFolder))
{
    var localPath = Path.Combine(repoDir, item.Path.TrimStart('/'));
    Directory.CreateDirectory(Path.GetDirectoryName(localPath)!);
    var bytes = await http.GetByteArrayAsync(FileUrl(repoId, item.Path));
    await File.WriteAllBytesAsync(localPath, bytes);
}
C#
var workDir = Path.Combine(Path.GetTempPath(), $"code-sync_{Guid.NewGuid():N}");
Directory.CreateDirectory(workDir);
try
{
    // download → analyze → extract schema → save
}
finally
{
    Directory.Delete(workDir, recursive: true);   // nothing left on disk, even on failure
}
Three small decisions keep this robust

The temp directory has a GUID in its name, so overlapping runs can never collide. Cleanup sits in finally, so a failed run leaves nothing behind. And a missing branch returns "skip this repository" instead of an exception, so one misconfigured repo doesn't cancel the whole sync.

#4. Step 2: Understanding the Code with Roslyn

Regexes can find the word class. Roslyn, the C# compiler as a library, knows what every identifier binds to. The analyzer loads each solution through MSBuildWorkspace, compiles each project, and walks every document:

C#
// Once per process: point Roslyn at an installed MSBuild
if (!MSBuildLocator.IsRegistered)
    MSBuildLocator.RegisterDefaults();

var workspace = MSBuildWorkspace.Create();
workspace.WorkspaceFailed += (_, e) => logger.LogWarning(e.Diagnostic.Message);

foreach (var slnPath in Directory.GetFiles(sourceDir, "*.sln", SearchOption.AllDirectories))
{
    var solution = await workspace.OpenSolutionAsync(slnPath);
    foreach (var project in solution.Projects)
    {
        if (await project.GetCompilationAsync() is null) continue;

        foreach (var document in project.Documents.Where(d => d.FilePath!.EndsWith(".cs")))
        {
            var root  = await document.GetSyntaxRootAsync();      // what the code says
            var model = await document.GetSemanticModelAsync();   // what it means
            foreach (var cls in root!.DescendantNodes().OfType<ClassDeclarationSyntax>())
                results.Add(Describe(cls, model!, project, slnPath));
        }
    }
}

The key distinction is syntax tree vs semantic model. The syntax tree is the shape of the text: this is a class declaration, that is a method call. The semantic model is what the compiler concluded: this identifier is the type OrderRepository from the Shop.Data assembly. Almost everything useful below comes from the semantic model.

#What gets extracted per class

Each class becomes one document with its methods nested inside. The ID combines namespace, class, project and file, so the same class name in two projects stays distinct:

JSON
{
  "_id": "[email protected]:OrderService.cs",
  "className": "OrderService",
  "namespace": "Shop.Orders",
  "project": "Shop.Orders",
  "solution": "Shop.sln",
  "layer": "Application",
  "type": "Service",
  "documentation": "Creates, prices and cancels orders.",
  "baseTypes": ["IOrderService"],
  "dependencies": [
    { "target": "OrderRepository", "project": "Shop.Data", "referenceType": "ProjectReference" }
  ],
  "methods": [
    {
      "methodName": "CancelOrderAsync",
      "returnType": "Task<bool>",
      "parameters": [{ "name": "orderId", "type": "int" }],
      "storedProcedures": ["usp_CancelOrder"],
      "cyclomaticComplexity": 4,
      "linesOfCode": 21
    }
  ]
}

#Dependencies from the semantic model

For every identifier in a class, ask the semantic model which type it refers to. Framework types are skipped, and only types defined in the solution's own projects are kept, labelled as same-project or cross-project references:

C#
foreach (var id in cls.DescendantNodes().OfType<IdentifierNameSyntax>())
{
    // Ask the semantic model what this name actually refers to
    if (model.GetSymbolInfo(id).Symbol is not INamedTypeSymbol type) continue;
    if (type.ContainingNamespace?.ToString().StartsWith("System") == true) continue;

    // Keep only types that live in this solution's own projects
    var owner = solution.Projects.FirstOrDefault(p => p.AssemblyName == type.ContainingAssembly?.Name);
    if (owner is null) continue;

    deps.TryAdd($"{type.Name}:{owner.Name}", new DependencyInfo
    {
        Target = type.Name,
        Project = owner.Name,
        ReferenceType = owner.AssemblyName == model.Compilation.Assembly.Name
            ? "SameProject" : "ProjectReference",
    });
}

That turns "what does this class depend on?" into an exact answer across project boundaries, which plain text search cannot give.

#Stored procedures, found where they are named

In data-heavy .NET code, stored procedure names usually appear as string literals passed to SqlCommand or Dapper. Scanning each method's string literals for procedure-style names links C# methods to database logic, and that link powers tools like "who calls this procedure?":

C#
var names = method.DescendantNodes()
    .OfType<LiteralExpressionSyntax>()
    .Where(l => l.IsKind(SyntaxKind.StringLiteralExpression))
    .Select(l => l.Token.ValueText)
    .Where(s => Regex.IsMatch(s, @"^(sp_|usp_|proc_)[A-Za-z0-9_]+$", RegexOptions.IgnoreCase))
    .Distinct();

#Complexity and size

Cyclomatic complexity is 1 plus the number of decision points. With a syntax tree that is a count of node types. Lines of code skip blanks and comments. Together they let an assistant answer "where are the riskiest methods?":

C#
int complexity = 1
    + method.DescendantNodes().OfType<IfStatementSyntax>().Count()
    + method.DescendantNodes().OfType<WhileStatementSyntax>().Count()
    + method.DescendantNodes().OfType<ForStatementSyntax>().Count()
    + method.DescendantNodes().OfType<ForEachStatementSyntax>().Count()
    + method.DescendantNodes().OfType<CaseSwitchLabelSyntax>().Count()
    + method.DescendantNodes().OfType<CatchClauseSyntax>().Count()
    + method.DescendantNodes().OfType<ConditionalExpressionSyntax>().Count()
    + method.DescendantNodes().OfType<BinaryExpressionSyntax>()
          .Count(b => b.IsKind(SyntaxKind.LogicalAndExpression) || b.IsKind(SyntaxKind.LogicalOrExpression));

#Documentation, layer and type

XML doc comments come from the symbol (GetDocumentationCommentXml()) with the <summary> extracted. Layer and type are inferred from conventions: namespaces containing .Api, .Application, .Infrastructure or .Domain, and class names ending in Controller, Service, Repository, Dto or Request. Cheap heuristics, but they make questions like "list the infrastructure classes in project X" possible.

#Method source, stored separately

The full source of every method is saved in its own collection, keyed by file and method name. Metadata documents stay small and fast to scan, and get_method_source can still hand the assistant the exact code when it needs it, instead of the assistant guessing at an implementation from its signature.

#5. Step 3: Reading the Database Schema

SQL Server describes itself. INFORMATION_SCHEMA.TABLES, COLUMNS, ROUTINES and PARAMETERS give tables, columns, procedure definitions and parameters. The sys.* catalogue views fill in what the standard views don't cover, such as foreign keys and indexes:

SQL
SELECT fk.name  AS ForeignKey,
       c.name   AS ColumnName,
       rt.name  AS ReferencedTable,
       rc.name  AS ReferencedColumn
FROM sys.foreign_keys fk
JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
JOIN sys.columns c  ON fkc.parent_object_id = c.object_id  AND fkc.parent_column_id = c.column_id
JOIN sys.tables  t  ON fk.parent_object_id = t.object_id
JOIN sys.tables  rt ON fk.referenced_object_id = rt.object_id
JOIN sys.columns rc ON fkc.referenced_object_id = rc.object_id AND fkc.referenced_column_id = rc.column_id
WHERE t.name = @TableName;

With foreign keys and procedure definitions stored next to the code metadata, the assistant can follow a feature end to end: controller → service → stored procedure → tables → related tables.

#6. Step 4: Storing the Map in MongoDB

Code metadata is naturally nested (class → methods → parameters) and its shape changes as the analyzer learns new tricks, so a document store fits better than a relational schema. Every write is an idempotent upsert keyed on a natural identity: class ID for classes, schema plus name for tables and procedures. Re-running a sync updates in place instead of duplicating:

C#
var ops = tables.Select(t => new ReplaceOneModel<TableSchema>(
    Builders<TableSchema>.Filter.And(
        Builders<TableSchema>.Filter.Eq(x => x.Schema, t.Schema),
        Builders<TableSchema>.Filter.Eq(x => x.TableName, t.TableName)),
    t) { IsUpsert = true });

await collection.BulkWriteAsync(ops);   // one round trip, safe to re-run

One ordering detail matters: class metadata is saved before the database step runs. If the SQL server is unreachable, the code map is still updated, and a partial sync beats an all-or-nothing one.

#7. Multi-Tenancy: One Server, Many Workspaces

One deployment serves several independent codebases. Each workspace is a document describing what to sync and how often:

JSON
{
  "name": "shop-platform",              // also the MongoDB database name
  "repositories": ["shop-api", "shop-admin"],
  "branch": "main",
  "dbConnectionString": "Server=…;Database=ShopDb;…",
  "dbName": "ShopDb",
  "syncFrequencyMinutes": 240,
  "status": "Pending",                  // Pending → Active → Pending | Failed | Disabled
  "lastRunUtc": "2026-09-23T04:00:00Z",
  "nextRunUtc": "2026-09-23T08:00:00Z"
}

Each workspace gets its own MongoDB database, named after the workspace, so data never mixes and removing a workspace is a single drop. A provisioner creates the database and its collections the first time a workspace syncs.

At request time a scoped TenantProvider carries the workspace name taken from the URL, and every Mongo access resolves its database through it:

C#
public class TenantProvider : ITenantProvider   // registered as Scoped
{
    public string? DatabaseName { get; set; }
}

public IMongoDatabase GetDatabase() =>
    _client.GetDatabase(_tenant.DatabaseName ?? _settings.DefaultDatabase);

[HttpPost("{workspace}/mcp")]
public async Task Mcp(string workspace)
{
    _tenant.DatabaseName = workspace;   // every query in this request now targets that workspace
    …
}

The MCP URL itself selects the workspace: https://host/shop-platform/mcp and https://host/billing/mcp are two different code maps behind the same server.

#8. Scheduling Syncs

A single BackgroundService wakes every minute, finds workspaces that are due, and runs them one by one with a small state machine: Pending → Active → Pending, or Failed on error, with Disabled to pause one:

C#
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        using var scope = _scopeFactory.CreateScope();
        var configs = await scope.ServiceProvider
            .GetRequiredService<IWorkspaceConfigService>().GetAllAsync();

        foreach (var cfg in configs.Where(c => c.Status != Status.Disabled
                                            && (c.NextRunUtc is null || c.NextRunUtc <= DateTime.UtcNow)))
        {
            try
            {
                await MarkAsync(cfg, Status.Active);
                await _provisioner.ProvisionAsync(cfg);          // create database + collections if new
                await RunSyncForWorkspaceAsync(cfg, stoppingToken);
                cfg.LastRunUtc = DateTime.UtcNow;
                cfg.NextRunUtc = cfg.LastRunUtc.Value.AddMinutes(cfg.SyncFrequencyMinutes);
                await MarkAsync(cfg, Status.Pending);
            }
            catch (Exception ex)
            {
                await MarkAsync(cfg, Status.Failed);             // one bad workspace doesn't stop the others
                _logger.LogError(ex, "Workspace {Name} failed", cfg.Name);
            }
        }

        await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
    }
}

#An isolated container per sync

The subtle part: each workspace has its own repositories, access token and source database, but the sync services read their settings through IOptions<T>. Rather than mutate app-wide singletons (and race with the next workspace), each run builds a fresh, short-lived DI container with that workspace's options baked in:

C#
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(Options.Create(new RepositorySettings
{
    Repositories = cfg.Repositories,
    Branch = cfg.Branch,
    AccessToken = cfg.AccessToken ?? defaults.AccessToken,
}));
services.AddSingleton(Options.Create(new DatabaseSettings
{
    ConnectionString = cfg.DbConnectionString,     // source SQL database
    Databases = [cfg.DbName],
}));
services.AddSingleton(Options.Create(new MongoDbSettings
{
    ConnectionString = defaults.MongoConnectionString,
    DatabaseName = cfg.Name,                       // destination: this workspace's database
}));
services.AddScoped<ICodeAnalyzerService, CodeAnalyzerService>();
services.AddScoped<ISchemaExtractorService, SchemaExtractorService>();
services.AddScoped<IMetadataSyncService, MetadataSyncService>();
// …the rest of the sync pipeline

using var provider = services.BuildServiceProvider();
await provider.GetRequiredService<IMetadataSyncService>().SyncAsync(ct);

The pipeline code stays unaware of tenants: it just reads its options. The container is disposed when the run ends, taking the per-workspace credentials with it.

#9. Speaking MCP

MCP is JSON-RPC 2.0. A client sends initialize to learn the server's capabilities, tools/list to discover tools with their JSON Schemas, and tools/call to run one. The endpoint accepts POSTs and answers in the Streamable HTTP style as server-sent events, with standard JSON-RPC error codes (-32700 parse error, -32601 unknown method, -32603 internal error):

C#
switch (request.Method)
{
    case "initialize":
        await Send(new { protocolVersion = "2024-11-05",
                         capabilities = new { tools = new { } },
                         serverInfo = new { name = "code-intelligence", version = "1.0.0" } });
        break;

    case "tools/list":
        await Send(new { tools = ToolDefinitions.GetAll()
            .Select(t => new { name = t.Name, description = t.Description, inputSchema = t.InputSchema }) });
        break;

    case "tools/call":
        var result = await _executor.ExecuteAsync(toolName, args);
        // MCP wants a content array; the structured result travels as JSON text
        await Send(new { content = new[] { new { type = "text", text = JsonSerializer.Serialize(result) } } });
        break;

    default:
        await SendError(-32601, $"Unknown method: {request.Method}");
        break;
}

#Tools as data

Each tool is declared once, with a name, a description written for the model and a JSON Schema for its arguments. The descriptions matter more than they look: they are the only documentation the assistant reads before choosing a tool.

C#
new ToolDefinition(
    "find_method",
    "Search for methods across all classes",
    Schema(new()
    {
        ["methodName"] = ("string",  "The name of the method to find"),
        ["className"]  = ("string",  "Filter by class name"),
        ["limit"]      = ("integer", "Max results to return (default 50)"),
    }))

A single executor maps tool names to handlers with a switch expression:

C#
public Task<object> ExecuteAsync(string tool, Dictionary<string, object> args) => tool switch
{
    "find_class"                      => FindClassAsync(args),
    "find_method"                     => FindMethodAsync(args),
    "get_method_source"               => GetMethodSourceAsync(args),
    "search_stored_procedures"        => SearchStoredProceduresAsync(args),
    "get_class_dependencies"          => GetClassDependenciesAsync(args),
    "get_table_schema"                => GetTableSchemaAsync(args),
    "get_table_relationships"         => GetTableRelationshipsAsync(args),
    "find_stored_procedures_by_table" => FindStoredProceduresByTableAsync(args),
    "class_count_by_layer"            => ClassCountByLayerAsync(args),
    // …40-odd more
    _ => throw new InvalidOperationException($"Unknown tool: {tool}"),
};

The catalogue is grouped by the questions developers actually ask:

  • Search: find_class, find_method, find_dto, search_by_namespace, search_class_name.
  • Method analysis: get_method_signature, get_method_source, list_class_methods, find_methods_by_return_type, trace_method_calls.
  • Structure: get_project_structure, get_layer_analysis, list_solutions, list_projects, get_class_dependencies.
  • Database: get_table_schema, get_table_relationships, get_table_foreign_keys, get_stored_procedure, get_sp_parameters, find_stored_procedures_by_table.
  • Code ↔ database: search_stored_procedures finds the C# methods that call a procedure.
  • Statistics: count_classes, class_count_by_layer, top_classes_by_method_count, top_tables_by_size.

Arguments arrive as JsonElements or primitives depending on the client, so handlers read them tolerantly (accepting either form, with sensible defaults such as a 50-result limit) instead of failing on a type mismatch.

#What it looks like in use

Text
You:        Which methods call usp_CancelOrder, and what does that procedure touch?

Assistant → search_stored_procedures { "storedProcName": "usp_CancelOrder" }
          ← OrderService.CancelOrderAsync, AdminOrderController.ForceCancel
Assistant → get_stored_procedure     { "name": "usp_CancelOrder" }
          ← definition + parameters (@OrderId int, @Reason nvarchar(200))
Assistant → get_table_relationships  { "tableName": "Orders" }
          ← FK Orders.CustomerId → Customers.Id, OrderLines.OrderId → Orders.Id

Assistant:  Two callers use it… it updates Orders and OrderLines, so cancelling
            also affects any report that joins OrderLines. Here is the method source…

Three small, precise tool calls replace pasting a dozen files into the chat, and the answer is grounded in what the compiler and the database actually say.

#10. Operating It

#Settings in MongoDB, with a file fallback

Repository credentials, database connections and access keys can change without a redeploy. A tiny custom IOptions<T> starts with the value from appsettings.json and is overwritten from MongoDB at startup if a stored value exists, so every service keeps using ordinary options injection:

C#
public class MongoOptionsProvider<T> : IOptions<T> where T : class, new()
{
    private T? _value;
    public MongoOptionsProvider(T fallback) => _value = fallback;   // from appsettings.json
    public void SetValue(T? value) { if (value != null) _value = value; }
    public T Value => _value ?? new T();
}

// Program.cs: register with the appsettings value, then overwrite from MongoDB at startup
var repoSettings = new MongoOptionsProvider<RepositorySettings>(
    builder.Configuration.GetSection("Repositories").Get<RepositorySettings>() ?? new());
builder.Services.AddSingleton<IOptions<RepositorySettings>>(repoSettings);
…
repoSettings.SetValue(await settingsService.GetRepositorySettingsAsync());

The settings API masks secrets on read: passwords in connection strings are replaced with asterisks, and access keys show only their first four characters.

#Live logs in the dashboard

A sync over a big solution takes minutes, and watching it helps. A custom Serilog sink raises an event for every log line; the Blazor Server dashboard subscribes and appends lines as they arrive, with no polling and no extra infrastructure:

C#
public class LogSink(LogStreamingService stream) : ILogEventSink
{
    public void Emit(LogEvent e) =>
        stream.Broadcast($"[{e.Timestamp:HH:mm:ss}] [{e.Level.ToString()[..3].ToUpper()}] {e.RenderMessage()}");
}

public class LogStreamingService
{
    public event Action<string>? OnLogReceived;
    public void Broadcast(string line) => OnLogReceived?.Invoke(line);
}

// Program.cs
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.Sink(new LogSink(logStreaming))   // the dashboard subscribes to OnLogReceived
    .WriteTo.File("logs/sync-.log", rollingInterval: RollingInterval.Day)
    .CreateLogger();

A singleton status service does the same for sync state (running, last duration, classes, tables and procedures found, next run), raising OnChange so the dashboard re-renders the moment a sync starts or finishes.

#Access

The dashboard uses cookie authentication with access keys that can be managed at runtime, and a small middleware logs each request's client IP (honouring X-Forwarded-For), user agent and an optional device header for auditing.

#11. What's Next

  • A true call graph. Class-level dependencies are exact today. Resolving every invocation inside each method (Roslyn's SymbolFinder can do this) would make "who calls this method?" as precise as "what does this class use?".
  • Semantic search. Embedding method source and documentation next to the structured metadata would add "find the code that handles refunds" alongside exact-name lookups: RAG over code, grounded by the same map.
  • Incremental syncs. Re-analysing only the files changed since the last commit instead of the whole solution.
  • Secrets at rest. Encrypting stored tokens and connection strings, or moving them to a secret store.

#12. Takeaways

  • Give assistants a map, not a pile of files. Precomputed, structured metadata beats pasting code into a prompt.
  • Use the compiler. Roslyn's semantic model answers "what does this refer to?" exactly; text search can only guess.
  • Link code to data. Connecting methods to stored procedures to tables is where the biggest questions get answered.
  • Make syncs idempotent and partial-failure tolerant. Upserts, a temp directory per run, per-repository error isolation, and saving code before touching the database.
  • Isolate tenants by construction. A database per workspace, a scoped tenant from the URL, and a fresh DI container per sync.