DotnetEfCoreMcp.Server
0.1.78-preview
{ "servers": { "dotnetefcoremcp.server": { "type": "stdio", "command": "dnx", "args": ["dotnetefcoremcp.server@0.1.78-preview", "--yes"] } } }
.vscode/mcp.json settings file.
dotnet tool install --global DotnetEfCoreMcp.Server --version 0.1.78-preview
dotnet new tool-manifest
dotnet tool install --local DotnetEfCoreMcp.Server --version 0.1.78-preview
#tool dotnet:?package=DotnetEfCoreMcp.Server&version=0.1.78-preview&prerelease
nuke :add-package DotnetEfCoreMcp.Server --version 0.1.78-preview
dotnet-efcore-mcp
An MCP (Model Context Protocol) server that lets an AI agent query an existing Entity Framework Core application's database — without writing a single line of app code.
Point it at a compiled project (its bin/Debug/**/*.dll output), give it a connection string, and it will:
- Load the assembly and discover the
DbContexttype(s) it contains. - Reflect over the EF Core model (entities, properties, keys, relationships) to build a schema the agent can understand.
- Accept LINQ-style queries from the agent and execute them against the real database through the real
DbContext— read-only by default.
The goal is a generic, reusable bridge between "I have an EF Core project" and "an AI agent can safely explore and query its data", instead of hand-writing MCP tools per project.
Why
Most existing EF Core + MCP integrations require the tools to be baked into the application itself (source generators, hand-written MCP tool methods, etc.). There isn't a mature, drop-in server that:
- Accepts an arbitrary, already-compiled
DbContextassembly. - Discovers its model dynamically via reflection instead of design-time source generation.
- Exposes safe, generalized schema discovery and querying to an MCP client, or to a plain shell command (see Choose MCP or CLI).
This project fills that gap. See DEVELOPMENT.md for the module guides and the status below for what ships today.
How it works
Agent (MCP client)
│ MCP tools: list_contexts, get_schema, run_query, ...
▼
dotnet-efcore-mcp server
│ 1. Loads target assembly (AssemblyLoadContext, isolated/collectible)
│ 2. Locates DbContext type(s), builds/serializes the EF Core model
│ 3. Resolves connection string for the requested context (Connections registry)
│ 4. Builds a DbContext instance, translates the requested query, executes it
▼
Target application's database
- The target project is never modified. We load its build output (the
.dllinbin/Debug/<tfm>/), not its source. - Connections are configured on the MCP server, not read from the target project's own configuration (appsettings, user secrets, etc.), so the server controls what a context is allowed to connect to.
- Queries run against the real model (including any Fluent API configuration, value converters, owned types, etc.) because we use the actual compiled
DbContext, not a re-implemented schema.
Status
Feature complete and in production use. Every planned module has landed and is covered by
tests (dotnet test), and the server is being used day to day against real applications:
| Area | What's in place |
|---|---|
| Assembly loading | Isolated, collectible AssemblyLoadContext; automatic reload on rebuild; optional allowed-root restriction; named multi-target registry (load_assembly targetName, list_loaded_assemblies, select_target). |
DbContext discovery |
Reflection-based discovery and construction, including split/multiple contexts and ASP.NET Core Identity contexts. |
| Connections | Server-side registry with provider allowlisting, mandatory per-connection AccessPolicy, redacted metadata, production guard rails, and opt-in startup-derived connections from the target app's own design-time factory. |
| Schema discovery | Paged/cursored get_schema, plus list_entities, get_entity_schema, and search_schema for cheap targeted lookups. |
| Query execution | Roslyn-compiled LINQ over the real model, read-only by default, in-process / out-of-process / pooled host modes, bounded result shaping and row caps, and preview_query_sql for SQL inspection without execution. |
| Migrations | Always-on read-only list_migrations, describe_migration, and compare_schema, and gated generate_migration_script (preview only, never executed). |
| Mutations | Gated single-entity insert_entity / update_entity / delete_entity, off by default and never available for production or read-only connections. |
| Raw SQL | Gated run_sql_query, off by default and never available for production or read-only connections. |
| Observability | Structured logging plus optional OpenTelemetry metrics and tracing (export disabled by default). |
| Distribution | Published to NuGet.org as a .NET tool / dnx-runnable MCP server, with an update-notification check and an onboard verb that installs agent hooks and skills. |
See DEVELOPMENT.md for the module-by-module breakdown. The work tracker has no open items; new gaps and feature requests are tracked as GitHub issues.
Prior art / inspiration
Research turned up no ready-made server doing exactly this, but several related projects informed the approach:
- ProjGraph.Mcp — reads EF Core
DbContext/ModelSnapshotsource to produce an ERD; closest match for schema discovery, but static-analysis based rather than loading a live assembly. - Elarion — source-generates MCP tools directly on top of an app's own
DbContext; a good reference for exposing EF Core over MCP, but requires building the tools into the app. - How to Expose an EF Core Database to an AI Agent via MCP — blueprint article covering
IDbContextFactory, allowlisted model inspection, read-only projections, pagination, and tenant scoping; the closest conceptual match to this project's goals.
Getting started
AccessPolicyis mandatory for every connection. Before your first tool call succeeds, each connection configured underConnections:<name>must also declare anAccessPolicy(at minimumAllowContextsnaming yourDbContext's full CLR type name) — there is no default/implicit policy. Omitting it makes every MCP tool call fail immediately with aConnectionRegistryConfigurationException-derived error identifying the missing section; see Configure connections below for the exact shape, and Per-connection access policy for the fullAllowContexts/DenyContexts/AllowEntities/DenyEntitiesreference.
Prerequisites
- .NET SDK 10 (
net10.0). - A target .NET project that has an EF Core
DbContextand has already been built (e.g.dotnet buildproducingbin/Debug/net8.0/MyApp.dllor similar — any TFM the target project builds for is fine; only the server itself targetsnet10.0).
Install as a .NET tool
The server is published to NuGet.org as a .NET tool (a NuGet package with
PackageType=McpServer). It bundles its out-of-process query-execution companion
(DotnetEfCoreMcp.QueryHost) internally, so no extra build step is required after installing —
QueryExecution:Mode=Auto (the default) finds it automatically.
dotnet tool install --global DotnetEfCoreMcp.Server --prerelease
While releases are preview-only, --prerelease is required. If a repository-local NuGet.config
or private feed prevents the tool from resolving, explicitly add NuGet.org for this command:
dotnet tool install --global DotnetEfCoreMcp.Server --prerelease --add-source https://api.nuget.org/v3/index.json
This installs the dotnet-efcore-mcp command. Point an MCP client at it directly (see the
Visual Studio Code setup example below for the .vscode/mcp.json
shape — swap the dotnet run --project ... command/args for dotnet-efcore-mcp with no
arguments once installed as a tool).
Alternatively, run it without a persistent install via dnx:
dnx DotnetEfCoreMcp.Server --prerelease --yes
Install via npm
A thin npm wrapper (in npm/) is packaged as dotnet-efcore-mcp so MCP clients/skill
managers that expect an npx-launchable server (e.g.
vercel-labs/skills) can install it without a user
running dotnet tool install by hand:
npx -y dotnet-efcore-mcp
The wrapper still requires the .NET SDK to be installed locally: on first run it installs (and
on later runs updates) the matching DotnetEfCoreMcp.Server .NET tool version from NuGet.org,
then execs straight into it. See npm/README.md for full details and
troubleshooting.
Note: the npm package is not published to the public registry yet. CI packs and stamps it on every release, but the publish step stays skipped until an
NPM_TOKENsecret (or npm Trusted Publishing) is configured — see.github/workflows/publish.yml. Until then, use the .NET tool ordnxinstall above, or publish the wrapper manually fromnpm/for testing.
Preview builds are published to NuGet.org from every push to main; stable releases are
published from tagged GitHub Releases (see
.github/workflows/publish.yml).
Choose MCP or CLI
One tool, two equal surfaces, both built on dotnet-agent-surface and backed by the same tool implementations (same gates, same redaction, same output):
| MCP server | CLI | |
|---|---|---|
| Start it | dotnet-efcore-mcp (no arguments) |
dotnet-efcore-mcp cli <operation> ... |
| For | MCP clients (VS Code, Claude Code, Copilot, Codex, ...) | Agents that run shell commands, skills, scripts, CI |
| State | One long-lived process | One process per call; load_assembly, select_target and swap_connection are remembered in a session file |
The MCP server is the default and behaves exactly as before. Every install path below gives you both.
# MCP: point your client at the command with no arguments (see the VS Code setup below)
dotnet-efcore-mcp
# CLI: operations use the MCP tool names; snake_case and kebab-case both work
dotnet-efcore-mcp cli --help
dotnet-efcore-mcp cli list-contexts --assembly .\MyApp\bin\Debug\net10.0\MyApp.dll
dotnet-efcore-mcp cli run-query --assembly .\MyApp\bin\Debug\net10.0\MyApp.dll --connection Dev `
--context-name AppDbContext --query "Orders.Where(o => o.Total > 10).Take(5)"
How to run the CLI per install method:
| Installed via | CLI command |
|---|---|
dotnet tool install --global |
dotnet-efcore-mcp cli <operation> ... |
dotnet tool install --local |
dotnet tool run dotnet-efcore-mcp cli <operation> ... |
dnx |
dnx DotnetEfCoreMcp.Server --prerelease --yes -- cli <operation> ... |
npx |
npx -y dotnet-efcore-mcp cli <operation> ... |
Global options (before or after the operation): --assembly <dll> (loads the target; exit 1 if it
cannot be loaded), --workspace <dir> (discover the target there; defaults to the current directory when
nothing else names a target, and loads the first assembly that actually contains a DbContext; also the default workspace-path of list-assembly-candidates), --target <name>, --connection <name>, --config Key=Value (any
configuration key, e.g. --config ToolOutput:Format=json), --session <id>, and the adapter flags
--output toon|json, --fields, --full. Operation parameters are kebab-case flags (--context-name);
long values can come from a file (--query @query.linq) or stdin (--query -).
Output and exit codes. A tool's result goes to stdout byte-for-byte (the same text the MCP tool
returns, untruncated), and nothing else does: logs go to stderr at Warning. Exit codes: 0 success,
1 operation error (the same message the MCP tool would return), 2 usage error, 130 cancelled.
Sessions. Every CLI call is a new process, so load_assembly, select_target and swap_connection
record their intent (names and paths only, never connection strings) in a per-user session file, and the
next call restores it:
dotnet-efcore-mcp cli load-assembly --assembly-path .\MyApp\bin\Debug\net10.0\MyApp.dll
dotnet-efcore-mcp cli swap-connection --connection-name Dev
dotnet-efcore-mcp cli run-query --context-name AppDbContext --query "Orders.Take(5)"
dotnet-efcore-mcp cli session show # where the state lives; `session clear` forgets it
The session defaults to one per working directory; override it with --session <id> or
DOTNET_EFCORE_MCP_SESSION. run_query cursors also work across calls (the session keeps a stable
signing key unless you configure QueryExecution:CursorSigningKey). Each call still reloads the
assembly, so per-call latency is higher than a warm MCP server; a background daemon is future work.
CLI-mode differences. No background services run (no reload watcher, update check or telemetry
export; use dotnet-efcore-mcp version --check-updates). QueryExecution:Mode=Pooled runs as Auto.
dotnet-efcore-mcp cli skill generate --out-dir <dir> writes an agent skill that documents the CLI.
Connections, access policies and every gate (RawSqlExecution:Enabled, EntityMutations:Enabled,
Migrations:Enabled) are configured exactly as for MCP.
Updating
Whether you need to do anything depends on how you installed the server:
| Installed via | Stays current? | To update |
|---|---|---|
npx -y dotnet-efcore-mcp |
Yes | Nothing — the wrapper updates the .NET tool on every launch. |
dnx DotnetEfCoreMcp.Server |
Yes | Nothing — dnx fetches the newest matching version per run. |
dotnet tool install --global |
No | dotnet tool update --global DotnetEfCoreMcp.Server --prerelease |
dotnet tool install --local |
No, by design | dotnet tool update --local DotnetEfCoreMcp.Server --prerelease |
To see what you are running and whether anything newer exists:
dotnet-efcore-mcp version --check-updates
Because preview builds ship frequently, a global install can fall behind without any sign of it.
The server therefore checks nuget.org once a day for a newer version and reports the result
through the read-only onboard tool, so your agent can tell you. It only ever tells you — it
never installs or updates anything by itself. No notice is shown for install methods that
already update themselves, or when the install method cannot be determined.
To turn the check off, use any of:
DOTNETEFCOREMCP_NO_UPDATE_CHECK=1 |
Environment variable; any value disables it. |
UpdateCheck:Enabled=false |
Server configuration. |
DOTNET_CLI_TELEMETRY_OPTOUT=1 |
Honored as an opt-out here too. |
| Running in CI | Detected automatically; set CI=false to override. |
The check is a plain unauthenticated GET to nuget.org for this package's published version list.
It sends no identifying information, runs in the background so it cannot delay startup, times out
after three seconds, and stays silent on any failure. It queries nuget.org directly and does not
honor NuGet.Config, so on a private mirror either point it elsewhere with UpdateCheck:Source or
disable it.
Onboarding: hooks and skills
Two things make this server easy to miss. First, the agent only reads the server's
ServerInstructions when the client actually loads the MCP server — with dynamic tool loading
that often happens late, or never, and long sessions forget them anyway. Second, the optional
integrations below are not discoverable from inside a session at all unless something mentions
them.
onboard is the single entry point for both:
dnx DotnetEfCoreMcp.Server --yes --prerelease -- onboard status # read-only; shows what exists
dnx DotnetEfCoreMcp.Server --yes --prerelease -- onboard install
(--prerelease is required while releases are preview-only, same as the dotnet tool install
command above. The hooks that get written pin the exact version that installed them, so they do
not need the flag.)
Everything is opt-in, status is the default and only reads, and nothing already on disk that
this tool did not write is ever replaced.
| Component | What it does |
|---|---|
| Hooks | At session start, tell the agent this server exists and what it is for. After it writes a LINQ query, remind it to validate with preview_query_sql/run_query. |
| Skills | Workflows the agent loads on demand — notably dotnet-efcore-mcp-feedback, for filing a usable issue about this server without leaking your code. |
Workspace or user-wide
--scope workspace (the default) writes into the repository so you can commit it and the whole
team gets it on clone. --scope user writes into your home directory once and applies to every
repository you open.
--scope workspace (default) |
--scope user |
|
|---|---|---|
| Claude Code | .claude/settings.json |
~/.claude/settings.json |
| GitHub Copilot CLI | .github/hooks/dotnet-efcore-mcp.json |
~/.copilot/hooks/dotnet-efcore-mcp.json |
| Codex CLI | .codex/hooks.json |
~/.codex/hooks.json |
| Skills | .github/skills/ |
~/.agents/skills/ |
Workspace is the default because it is the reviewable choice: the config lands where a human can read it in a diff, and it cannot silently change behavior in unrelated projects.
A user-wide session-start hook fires in every session on the machine, so it stays silent unless the workspace actually references EF Core — EF Core guidance in a front-end repo is just noise. A workspace hook always speaks, since installing it into that repository was already the opt-in.
Options
# Just the skills, user-wide
dnx DotnetEfCoreMcp.Server --yes --prerelease -- onboard install --scope user --what skills
# Just the hooks, only for Codex, in another repository
dnx DotnetEfCoreMcp.Server --yes --prerelease -- onboard install --what hooks --client codex --path ../my-app
# Remove whatever this tool installed, leaving unrelated config intact
dnx DotnetEfCoreMcp.Server --yes --prerelease -- onboard uninstall
--what hooks|skills|all, --client claude|copilot|codex|all (comma-separated),
--skill <name>, --path <dir>, and --force are all accepted. Existing settings and unrelated
hooks in those files are preserved, and hooks install/hooks status remain available if you
only care about hooks.
From inside a session
The server also exposes an onboard MCP tool, so the agent can report what is set up and point at
the command to install the rest, without anyone hunting through this README.
Reporting status is always available and read-only. Installing over MCP is off by default and requires opting in server-side:
{ "Onboarding": { "AllowInstall": true } }
That gate exists because an installed hook adds a command the agent's CLI executes on every
subsequent tool call — a broader grant than it first appears, and the same reason
RawSqlExecution and EntityMutations are opt-in. A tool description asking the agent to confirm
with the user is a prompt, not an enforcement boundary. With the gate off, the agent still reports
what's missing and hands you the exact command, so you stay the one who runs it.
Once hooks are installed, the agent gets a short reminder after it writes an EF Core LINQ query,
pointing it at preview_query_sql, run_query, and get_entity_schema. The reminder is
rate-limited (once per 10 minutes per session) and resets as soon as the agent actually uses the
server, so it nudges without nagging. A secondary reminder suggests schema discovery when the
agent reads several entity source files by hand.
Note: Claude Code and Codex CLI ask you to review and approve repo-local hooks the first time they run, so a committed hook cannot execute without consent. Hooks run
dnx, which requires the .NET SDK onPATH. Restart your agent CLI (or reload the window) after installing so it rescans hooks and skills.
For the detection heuristics and per-client hook contracts, see Agent hooks. For the onboarding surface as a whole, see Agent onboarding.
Agent skills
The skills onboard installs live under skills/. A skill teaches your agent a
workflow it would otherwise have to reinvent each time.
| Skill | What it does |
|---|---|
dotnet-efcore-mcp-feedback |
Turns a frustrating encounter with this server into a self-contained GitHub issue — scrubbed of your private code and connection strings, with a reproduction the maintainer can run against this repo's own tests/Fixtures/SampleApp. |
Reporting a problem with this server is unusually awkward, which is why the feedback
skill exists: the evidence lives inside someone's private codebase alongside a real
DbContext and a real connection string, so a useful report has to be a translation
rather than a copy-paste. The skill does that translation — strip the secrets,
generalize the model shape, rebuild the failure against the sample fixture — so the
issue is reproducible by someone who will never see your repo.
onboard install works from a plain dnx/dotnet tool install with no clone, because the skill
folders are packed into the tool. If you do have a clone and are editing a skill, the scripts
in skills/ install it as a symlink so your edits are picked up without reinstalling:
./skills/install-skills.ps1 -Link # Windows
./skills/install-skills.sh --link # macOS / Linux
See skills/README.md for those options.
Build & test
dotnet build dotnet-efcore-mcp.slnx
dotnet test dotnet-efcore-mcp.slnx
(Note: the solution file is dotnet-efcore-mcp.slnx, the newer XML-based solution
format — not a classic .sln. dotnet build/dotnet test from the repo root also
auto-discover it without naming it explicitly.)
Configure connections (server-side only)
Connection strings are never read from the target project's own configuration and are
never accepted from an MCP client — only a logical connection name is ever passed
across the MCP boundary. Configure real connections on the server via dotnet user-secrets
(local/dev) and/or environment variables (any environment); the two sources are additive,
with environment variables overriding user-secrets for the same key, per the standard
IConfiguration provider order.
Each connection needs ConnectionString, plus optional Provider (one of Sqlite,
SqlServer, PostgreSql), Environment (Development, Staging, Production, or
Unspecified), AccessMode (ReadOnly — the default — or ReadWrite; see the note in
docs/development/connections.md about its current
scope), and CommandTimeoutSeconds (defaults to 30). It also requires an AccessPolicy
section — there is no default policy, and a connection without one fails every tool call with
an actionable "missing a required AccessPolicy section" error. At minimum, set
AccessPolicy:AllowContexts:0 to your DbContext's full CLR type name (e.g.
MyApp.Data.AppDbContext); see
Per-connection access policy for the full
AllowContexts/DenyContexts/AllowEntities/DenyEntities shape.
Provider is optional because it's normally inferred from the EF Core provider package
referenced by the currently loaded target project assembly (e.g. referencing
Microsoft.EntityFrameworkCore.SqlServer infers SqlServer). Inference only ever looks at
the target assembly's compiled package references — never at the target project's own
configuration or connection strings. An explicit Provider always takes precedence over
inference, and is required if the target project references zero or more than one supported
EF Core provider package (inference then fails with an actionable error naming the
Connections:<name>:Provider key to set).
Keep the committed appsettings.json placeholder empty. For example, configure three named
environments with user-secrets, letting the provider be inferred:
cd src/DotnetEfCoreMcp.Server
dotnet user-secrets init
dotnet user-secrets set "Connections:MyApp.Development:ConnectionString" "Server=...;Database=...;..."
dotnet user-secrets set "Connections:MyApp.Development:Environment" "Development"
dotnet user-secrets set "Connections:MyApp.Development:AccessPolicy:AllowContexts:0" "MyApp.Data.AppDbContext"
dotnet user-secrets set "Connections:MyApp.Staging:ConnectionString" "Server=...;Database=...;..."
dotnet user-secrets set "Connections:MyApp.Staging:Environment" "Staging"
dotnet user-secrets set "Connections:MyApp.Staging:AccessPolicy:AllowContexts:0" "MyApp.Data.AppDbContext"
dotnet user-secrets set "Connections:MyApp.Production:ConnectionString" "Server=...;Database=...;..."
dotnet user-secrets set "Connections:MyApp.Production:Environment" "Production"
dotnet user-secrets set "Connections:MyApp.Production:AccessPolicy:AllowContexts:0" "MyApp.Data.AppDbContext"
Or use environment variables (useful in containers/CI, and always takes precedence over user-secrets for the same key):
$env:DOTNETEFCOREMCP_Connections__MyApp.Development__ConnectionString = "Server=...;Database=...;..."
$env:DOTNETEFCOREMCP_Connections__MyApp.Development__Environment = "Development"
$env:DOTNETEFCOREMCP_Connections__MyApp.Development__AccessPolicy__AllowContexts__0 = "MyApp.Data.AppDbContext"
If a target project references more than one supported EF Core provider (or none), set
Provider explicitly for the affected connection(s):
dotnet user-secrets set "Connections:MyApp.Development:Provider" "SqlServer"
The first non-production connection is active at startup. Use the list_connections MCP
tool to inspect redacted connection metadata and swap_connection to change the active
default used by get_schema and run_query when no connection name is supplied.
Connections can be added, changed, or removed while the server is running. The registry
re-reads its configuration source whenever that source changed on disk, so a connection
added with dotnet user-secrets set becomes visible to list_connections, run_query, and
swap_connection without restarting the MCP client. If an expected connection is still
missing — for example because it comes from a configuration source whose changes cannot be
detected from file metadata — call reload_connections to force a re-read; it reports which
connection names were added or removed. An active connection selected with swap_connection
survives a refresh as long as it still exists.
Production connections are always forced to ReadOnly, even if configured otherwise. They
are never selected automatically and swap_connection requires an explicit
allowProduction: true acknowledgement before activating one. A production-only registry
therefore starts without an active connection.
Visual Studio Code setup
VS Code reads workspace MCP servers from .vscode/mcp.json. This example launches the server
from a sibling clone, passes the open workspace to automatic assembly discovery, and prompts for
the connection string without committing it:
{
"servers": {
"dotnet-efcore": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"C:\\repos\\dotnet-efcore-mcp\\src\\DotnetEfCoreMcp.Server"
],
"cwd": "${workspaceFolder}",
"env": {
"DOTNETEFCOREMCP_WORKSPACEPATH": "${workspaceFolder}",
"DOTNETEFCOREMCP_CONNECTIONS__Workspace__PROVIDER": "SqlServer",
"DOTNETEFCOREMCP_CONNECTIONS__Workspace__CONNECTIONSTRING": "${input:efcore-connection-string}",
"DOTNETEFCOREMCP_CONNECTIONS__Workspace__ACCESSMODE": "ReadOnly",
"DOTNETEFCOREMCP_CONNECTIONS__Workspace__ENVIRONMENT": "Development",
"DOTNETEFCOREMCP_CONNECTIONS__Workspace__ACCESSPOLICY__ALLOWCONTEXTS__0": "MyApp.Data.AppDbContext"
}
}
},
"inputs": [
{
"id": "efcore-connection-string",
"type": "promptString",
"description": "EF Core database connection string",
"password": true
}
]
}
ACCESSPOLICY__ALLOWCONTEXTS__0 (replace MyApp.Data.AppDbContext with the full CLR name of your
DbContext) is required — every connection must declare an explicit AccessPolicy, and the
server throws ConnectionRegistryConfigurationException on startup for any connection without
one (see Per-connection access policy for the full
AllowContexts/DenyContexts/AllowEntities/DenyEntities shape).
Change PROVIDER to Sqlite or PostgreSql when appropriate. On first start VS Code prompts
for the input and stores it securely; it is passed directly to the server process as configuration,
not through an MCP tool call. Use MCP: List Servers from the Command Palette to start, stop,
or restart this workspace server. See the official VS Code MCP server configuration
and sensitive input variable reference.
When WorkspacePath is configured and TargetAssemblyPath is not, startup scans the workspace's
C# projects and automatically loads the best existing output. Assemblies whose metadata suggests
they contain a DbContext-derived type are preferred first; Debug builds are then preferred, with
the newest output and higher target framework breaking remaining ties. Dependency and ref
assemblies are excluded. If nothing has been built yet, the server still starts—build the target
project and restart the server, or use list_assembly_candidates followed by load_assembly.
By default, the candidate tool returns one preferred output per project, noting other available
builds in otherBuildsOfThisProject; pass includeAllBuilds: true to inspect every
configuration/TFM output or pathFilter to narrow a monorepo to projects whose path contains a
specific project or folder name.
The VS Code Agent Host does not forward servers requiring interactive inputs to remote agents. This prompted configuration is intended for local VS Code chat; configure secrets in the remote environment separately for remote Agent Host use.
Point the server at a target project
For clients other than VS Code, set WorkspacePath to a repository/workspace root to get the same
automatic discovery behavior. Alternatively, set TargetAssemblyPath in configuration (it takes
precedence over discovery and is loaded once at startup; failures are logged as a warning, not
fatal) — e.g. via dotnet user-secrets set "TargetAssemblyPath" "C:\path\to\MyApp\bin\Debug\net8.0\MyApp.dll" —
or call the load_assembly MCP tool at runtime with the same path. load_assembly can be called
again any time (e.g. after rebuilding the target project) to reload it.
By default, load_assembly accepts any absolute path (trusted local/dev usage is assumed —
the MCP client is presumed to run at the same trust level as whoever launched the server).
To restrict which directories may be loaded from, configure one or more allowed roots; any
path outside them is rejected before the assembly is touched:
dotnet user-secrets set "AssemblyLoader:AllowedRoots:0" "C:\repos\MyApp\bin"
Automatic reload after rebuild
Once an assembly has been loaded (via startup discovery, TargetAssemblyPath, or load_assembly),
the server watches its DLL on disk and automatically reloads it whenever the file changes — e.g.
when dotnet build/MSBuild finishes rebuilding the target project — so load_assembly normally
never needs to be called again after the first load. File-change events are debounced (MSBuild
writes the DLL more than once per build) and a reload attempt is retried a few times if the file is
still locked because a build is still in progress. If every retry fails (or the rebuilt assembly
fails to load, e.g. bad IL mid-write), the server logs a warning and keeps serving the previously
loaded assembly; call load_assembly manually once the issue is resolved. Disable this behavior
with:
dotnet user-secrets set "AssemblyLoader:AutoReloadEnabled" "false"
Using Git worktrees
The server, the target project, or both can live in a Git worktree
(e.g. git worktree add ../myapp-feature) instead of the primary checkout — WorkspacePath,
TargetAssemblyPath, and load_assembly all operate on plain absolute filesystem paths, so
worktrees need no special handling. Two things worth knowing:
- In VS Code,
${workspaceFolder}resolves to whichever worktree is currently open, so themcp.jsonexample above works unchanged when the whole repo (server + target project) is checked out as a worktree — just open that worktree's folder. - If the server and the target project live in different worktrees (or different repos
entirely), point
WorkspacePath/TargetAssemblyPathat the target project's worktree path explicitly rather than relying on${workspaceFolder}, since that variable only reflects the workspace VS Code currently has open, not the server's own working directory.
Tune query execution limits
Two safety limits are configurable under QueryExecution (both have sane defaults, so this
section is optional):
MaxTake(default200) — the hard cap on rows returned by a single query, regardless of the client-requestedtake.MaxIncludedCollectionItems(default5) — caps how many items are materialized per parent and included collection navigation (for exampleinclude: ["Orders.OrderLines"]). Requested collection branches use deterministic, database-side filtered includes, so a customer with 100,000 orders cannot blow up the response.MaxIncludeDepth(default3) andMaxIncludeCount(default5) — bound, respectively, the maximum number of dot-separated segments in oneincludepath and the maximum number ofincludepaths accepted per request.
dotnet user-secrets set "QueryExecution:MaxTake" "100"
dotnet user-secrets set "QueryExecution:DefaultTake" "50"
dotnet user-secrets set "QueryExecution:MaxQueryLength" "4000"
Run the server
The server communicates over stdio (standard input/output carries the MCP JSON-RPC protocol; all logging goes to standard error instead, so it never corrupts the protocol stream):
dotnet run --project src/DotnetEfCoreMcp.Server
Configure your MCP client (e.g. an agent host) to launch this as a stdio-based MCP server
process, or reference the same command from an mcp.json/equivalent client configuration.
MCP tool contract
All tools are [McpServerTool]-attributed methods on a single class and operate against
exactly one currently-loaded target assembly at a time (see load_assembly).
Errors are surfaced as ModelContextProtocol.McpException with an actionable message
(no connection strings, no raw stack traces).
Successful tool payloads use TOON by default,
which reduces structural overhead for agent consumption. This affects only the text content
returned by each tool: the stdio transport remains MCP JSON-RPC. To retain the legacy,
indented JSON tool payloads, set ToolOutput:Format to json (for example,
dotnet user-secrets set "ToolOutput:Format" "json").
| Tool | Parameters | Returns |
|---|---|---|
list_assembly_candidates |
workspacePath?: string (defaults to the working directory; the CLI's --workspace), pathFilter?: string, includeAllBuilds?: bool |
workspacePath and DbContext-first (application assemblies before test projects), preference-ordered candidates (assembly path, project, configuration, target framework, write time, preferred flag). By default, one preferred candidate per project is returned with otherBuildsOfThisProject; set includeAllBuilds to list every configuration/TFM output. |
load_assembly |
assemblyPath: string, targetName?: string |
Loaded assembly path/time and discovered DbContext names, full names, and construction kinds. Pass targetName to register an additional named target instead of replacing the default one. |
list_contexts |
targetName?: string |
Current assembly path, stale flag, and discovered contexts; hiddenByAccessPolicy counts contexts the active connection's access policy hides (with a warning) |
get_schema |
contextName?: string, connectionName?: string, page?: int, pageSize?: int, cursor?: string, targetName?: string |
A bounded entity page with properties (CLR type, nullability, PK/FK/concurrency-token flags, column name/type), keys, relationships, navigations, and inheritance metadata. Follow nextCursor for page-size-independent continuation. |
list_entities |
contextName?: string, connectionName?: string, targetName?: string |
Lightweight policy-filtered list of entity CLR names and relational table names for discovery before requesting a full schema. |
get_entity_schema |
entityName: string, contextName?: string, connectionName?: string, targetName?: string |
Complete policy-filtered definition for one exact entity (same shape as get_schema's entities). Builds and caches the resolved context's schema on demand. |
search_schema |
contextName?: string, query: string, maxResults?: int, connectionName?: string, targetName?: string |
Compact, case-insensitive substring matches (entityName, entityNameMatched, matchingProperties, matchingRelationships) across entity/property/relationship names, plus totalMatchCount and truncated. maxResults defaults to 10 and is capped at 25. Same lazy cache-build behavior as get_entity_schema. |
run_query |
contextName: string, query: string, connectionName?: string, targetName?: string, include?: string[], pagination?: { mode: "cursor", cursor?: string } |
Root DbSet name, scalar-or-sequence result, effective sequence page size, safely projected rows, a hasMoreRows continuation flag, and (in cursor mode) a nextCursor. include accepts dot-separated navigation paths (e.g. ["Orders.OrderLines"]), validated against the EF Core model before execution (unknown/scalar segments, cycles, repeated navigations, and duplicate paths are rejected, subject to MaxIncludeDepth/MaxIncludeCount); when supplied, each collection level is deterministically ordered and capped server-side at MaxIncludedCollectionItems before materialization, and only the requested branches are projected. |
preview_query_sql |
contextName: string, query: string, connectionName?: string, targetName?: string, include?: string[] |
The provider-generated SQL for a run_query-style expression, obtained from the compiled, unexecuted IQueryable via ToQueryString(). Uses the same execution-mode routing as run_query, so it works in every QueryExecution:Mode (including the default Auto); ApplicationFactory connections require an isolated mode (OutOfProcess, Pooled, or Auto). When successful, the ToQueryString() call itself never opens a database connection, runs a command, or reads/writes rows — however, a caller-supplied expression may force enumeration or execute side effects before that point. Rejects scalar/element results, already-materialized results, and non-translatable operators (e.g. Zip) with a message directing the caller to run_query instead. include is validated identically to run_query and reflected in the previewed SQL (including any split-query plan applied for nested collection includes). |
run_sql_query |
contextName: string, sql: string, connectionName?: string, parameters?: object[] |
Rows, row count, affected rows, maximum rows, and more-rows flag; disabled by default and restricted to development ReadWrite connections |
test_connection |
contextName: string, connectionName?: string |
Redacted connection-health diagnostic: context name, resolved connection name, provider, environment, and a healthy/failed/timedOut status. Never returns query rows, schema, or a connection string, and never changes the active connection |
insert_entity |
contextName: string, entity: string, values: object, connectionName?: string |
Inserted scalar values and actual affected rows; disabled by default and restricted to development ReadWrite connections |
update_entity |
contextName: string, entity: string, key: object, values: object, concurrency?: object, connectionName?: string |
Updated scalar values and actual affected rows, or a stable not-found-or-concurrency-conflict result |
delete_entity |
contextName: string, entity: string, key: object, concurrency?: object, connectionName?: string |
Actual affected rows, or a stable not-found-or-concurrency-conflict result |
list_migrations |
contextName: string, connectionName?: string, migrationsAssembly?: string, fullLists?: bool |
Known, applied, and pending migrations plus databaseExists and appliedStateAvailable, and dotnet ef-style diagnostics: migrations[], knownMigrationCount, lastAppliedMigration, unknownAppliedMigrations, pendingMigrations[].outOfOrder, hasPendingModelChanges. Always available on every connection, including production and ReadOnly (read-only, no DDL/DML) |
describe_migration |
contextName: string, migrationId: string, connectionName?: string, migrationsAssembly?: string, direction?: "up" \| "down" |
The structured operations (kind, table, column, type, nullability, …) of one migration, matched by full ID or unique suffix, plus operationCount. Never opens the database; available on every connection |
compare_schema |
contextName: string, connectionName?: string, migrationsAssembly?: string, tables?: string[], includeExtras?: bool |
Live catalog vs. EF model: notInDatabase, different, optional extraInDatabase, hasDifferences, comparedTableCount, truncated. Missing tables/columns include migration attribution. Always available, including production and ReadOnly |
generate_migration_script |
contextName: string, connectionName?: string, fromMigration?: string, toMigration?: string, idempotent?: bool, migrationsAssembly?: string |
The SQL EF Core's IMigrator.GenerateScript would produce between two migration IDs — never executed. Disabled by default |
list_connections |
(none) | Registered connections with provider, access mode, environment, source, production flag, and which is active, plus registryLoadedAtUtc. Connection strings are never exposed |
reload_connections |
(none) | Forces a re-read of the connection registry configuration and reports addedConnections/removedConnections plus the refreshed list. Opens no database connection and runs no query; the active connection is preserved when it still exists |
swap_connection |
connectionName: string, allowProduction?: bool |
The new active connection. Production connections require allowProduction: true |
list_loaded_assemblies |
(none) | Every registered target assembly (logical name, source path, load timestamp, default flag) |
select_target |
targetName: string |
The new default target used when targetName is omitted elsewhere. Does not unload any other target. The target loaded without a targetName is named default and can be selected by that name; warns when the selected target contains no DbContext |
onboard |
workspacePath?: string, apply?: bool, scope?: string, what?: string, force?: bool |
What hooks/skills exist and what is installed (read-only by default), plus any pending update notice. apply: true also requires the server-side Onboarding:AllowInstall setting |
query is Roslyn-compiled C# rooted at an exact, public DbSet<T> property on the selected
context, such as Customers.Where(c => c.Age > 18).Select(c => new { c.Id, c.Name }).
If the trimmed text parses as one complete expression, the server wraps it as return <query>; (this is the currently supported execution path). An optional single trailing ; is accepted and stripped.
If the query uses a top-level { ... } block or contains multiple statements, the server rejects it: statement mode is not supported by design due to access-policy enforcement constraints. Expression-mode queries (the currently supported path) allow the server to validate entity access before compilation. For full P0 #9 status, see the development guide.
The compiled query source automatically brings in a using for the DbContext's own namespace
and every DbSet<T> entity type's namespace (plus one level of enum properties declared on
those entities), so sibling types that live alongside the context or its entities — including
enums such as PartnerType.Transport — can usually be referenced unqualified, the same way an
inherited DbSet property like Orders already resolves without qualification. If a type lives
in a different namespace than the context/entities (or its short name collides with another
type reachable this way), qualify it explicitly (e.g. MyNamespace.PartnerType.Transport).
IQueryable results are materialized server-side and capped at 50 rows by default (up to a configured maximum of 200 rows, unless
reconfigured); no terminal .ToList()/.FirstOrDefault() call is required. Results are not
automatically ordered; add an explicit OrderBy() when using Skip()/Take() to ensure stable
pagination. Scalars are returned as scalars. Non-IQueryable results (for example a client-side
Zip after AsEnumerable() or an already-materialized List<T>) are also returned as scalars
rather than row-shaped query results.
For forward-only keyset paging, pass pagination: { mode: "cursor" } with an explicitly
ordered mapped-entity query; each response with hasMoreRows: true returns an opaque
nextCursor for the next request. Cursor mode appends primary-key tie-breakers, rejects
Skip(), and is omitted entirely for legacy offset/Take paging.
Queries default to QueryTrackingBehavior.NoTracking. An explicit .AsTracking() can opt back
into tracking, but SaveChanges() remains blocked unless the server operator enables
QueryExecution:AllowMutationsInRunQuery and the selected connection is both non-production and
ReadWrite.
run_sql_query is an explicitly opt-in escape hatch for development diagnostics and migrations;
prefer the always-on run_query whenever its LINQPad-style C# contract is sufficient.
Enable raw SQL only in a local or development server configuration, then restart the MCP server;
it cannot be enabled per request or per agent session:
dotnet user-secrets set "RawSqlExecution:Enabled" "true"
# Or for the current process:
$env:DOTNETEFCOREMCP_RAWSQLEXECUTION__ENABLED = "true"
Raw SQL positional values must use provider parameters named @p0, @p1, and so on (for
example, SELECT * FROM Users WHERE Id = @p0 with parameters: [42]); values are passed as
ADO.NET parameters rather than interpolated. Result rows are materialized up to the configured
maximum (200 by default), but the command itself is not rewritten with a dialect-specific
LIMIT or TOP. The tool remains unavailable for production and ReadOnly connections even
when globally enabled. On an eligible development ReadWrite connection it can run mutating
SQL, including DELETE, TRUNCATE, or schema changes—enable it only where that risk is
acceptable.
Schema and query tools need a configured connection because constructing the DbContext (even
for schema-only inspection) needs its provider and connection string. With multiple configured
connections, omitting connectionName uses the active connection selected by swap_connection;
pass connectionName to override that selection. get_schema, get_entity_schema,
search_schema, and query tools all follow this same rule.
list_migrations is always-on, read-only inspection (no DDL/DML, never mutates the target
database): it reports which migrations the assembly knows about, which are recorded as applied
in __EFMigrationsHistory, and which are pending. When the target database is unreachable,
databaseExists is false, every known migration is reported pending, and
appliedStateAvailable is false rather than presenting metadata as confirmed applied state.
Like dotnet ef migrations list, it also returns every known migration in order with its applied
state (migrations[]), knownMigrationCount, lastAppliedMigration, history rows the loaded code
doesn't know (unknownAppliedMigrations), pending migrations that sort before the last applied one
(outOfOrder), and hasPendingModelChanges (model differs from the latest snapshot).
It is available on every connection, including production and ReadOnly connections, because it only reads
__EFMigrationsHistory and migration metadata.
describe_migration shows what one migration does (for example, AddColumn Customers.Email TEXT NULL) as structured operations, without generating SQL or opening the database. Pass a full
migration ID or a unique suffix such as AddCustomerEmail, and direction: "down" for the
rollback operations.
compare_schema compares the model with the live database catalog using
EfCore.SchemaCompare (MIT, Jon P Smith).
It reports missing/different tables, columns, keys, and indexes; missing tables/columns include
introducedBy and introducedByIsPending migration attribution. Like list_migrations, it is
always available, including production and ReadOnly connections. Optional tables filters
results (case-insensitive, schema-qualified or not); includeExtras: true adds database-only
columns/indexes in mapped tables. It still reads the whole catalog, and TPT/TPC, name-case
mismatches, complex types, and JSON mappings have limitations; see the
contract and limitations. Output is capped at
Migrations:MaxDriftEntries entries (default 500, truncated: true when capped). The wall-clock
budget is the connection's CommandTimeoutSeconds plus Migrations:CancellationMargin (default
5 seconds); on timeout/cancellation the caller stops waiting, while the synchronous reader may
finish in the background. It never applies migrations or fixes the schema.
generate_migration_script previews the SQL EF Core's IMigrator.GenerateScript would produce
between two migration IDs — it never executes the script, opens a transaction, or calls
SaveChanges. It is disabled by default; enable it (and restart the server, the same as
RawSqlExecution:Enabled) with:
dotnet user-secrets set "Migrations:Enabled" "true"
# Or for the current process:
$env:DOTNETEFCOREMCP_MIGRATIONS__ENABLED = "true"
Even when enabled, it is rejected for production and ReadOnly connections. The returned script
is capped at Migrations:MaxScriptLength characters (100,000 by default) and truncated at a
best-effort statement boundary, with truncated set to true when that happens. Not every
provider supports idempotent scripts (for example, SQLite does not); retry with
idempotent: false if generate_migration_script reports that limitation.
Troubleshooting: a query fails because a column or table doesn't exist
Errors such as Invalid column name 'X', Invalid object name 'T', no such column,
no such table, or column ... does not exist usually mean the code was deployed ahead of the
schema. run_query and run_sql_query append a pointer to this workflow when they see one. All
steps except the last are read-only and work on production connections:
list_migrations contextName=AppDbContext connectionName=prod [migrationsAssembly=App.Migrations]
→ pendingMigrations, lastAppliedMigration, unknownAppliedMigrations, hasPendingModelChanges
compare_schema contextName=AppDbContext connectionName=prod tables=[OrderLines]
→ notInDatabase[{ table, column, introducedBy, introducedByIsPending }]
describe_migration contextName=AppDbContext migrationId=<introducedBy>
→ the AddColumn/CreateTable operations the database is missing
generate_migration_script contextName=AppDbContext connectionName=dev
fromMigration=<prod's lastAppliedMigration>
→ preview SQL to hand to whoever deploys schema changes
generate_migration_script needs Migrations:Enabled and a non-production ReadWrite
connection, so run it against a development database that has the same migrations assembly.
introducedBy absent with hasPendingModelChanges: true means the model changed without a
migration (dotnet ef migrations add was forgotten). No tool applies migrations. See
Migration inspection for the full contracts.
Security
Because this server can execute arbitrary queries against a real database on behalf of an agent, security is a first-class concern, not an afterthought. See the Connection management and Query execution module guides for the implemented safeguards (connection string storage, query allowlisting/read-only enforcement, result limits, auditing).
Contributing
Issues and PRs are welcome. Start with DEVELOPMENT.md for the module layout and build/test instructions, and use the Conventional Commit style described in AGENTS.md.
If something about this server itself is broken or awkward, the
dotnet-efcore-mcp-feedback skill can turn the encounter
into a reproducible issue without exposing your code or connection strings.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
This package has no dependencies.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.78-preview | 0 | 11/15/2026 |
| 0.1.66-preview | 61 | 11/13/2026 |
| 0.1.62-preview | 51 | 11/10/2026 |
| 0.1.59-preview | 57 | 11/9/2026 |
| 0.1.57-preview | 65 | 11/6/2026 |
| 0.1.45-preview | 81 | 10/16/2026 |
| 0.1.39-preview | 75 | 10/15/2026 |
| 0.1.32-preview | 81 | 10/8/2026 |
| 0.1.26-preview | 86 | 10/2/2026 |
| 0.1.22-preview | 89 | 9/21/2026 |
| 0.1.20-preview | 89 | 9/21/2026 |