Skip to content

Connecting Microsoft SQL Server to an AI Agent On-Premise

Many companies run their ERP on a Microsoft SQL Server in their own server room. If you want an AI agent to answer "Which orders for customer 10423 are still open?", that is the database it has to reach. The hard part is doing it without stalling the accounting team and without handing the agent broader rights than it needs. The general text-to-SQL principles are covered in Connecting an AI Agent to Databases; this guide is about what is specific to SQL Server.

What are we building?

You will end up with a small Python MCP server that exposes two tools to an agent: list the approved views, and run a single SELECT. It authenticates with Kerberos, reads only from its own schema, and either lands on a readable secondary through the availability group listener or reads the primary under snapshot isolation.

If you have read our guide on connecting PostgreSQL to an AI agent, four things work differently here:

  1. Permissions. The agent gets SELECT on one schema of curated views rather than a broad read role. The fixed db_datareader role is too wide for an ERP database.
  2. Locking. By default SQL Server takes shared locks while reading, so a long agent query can hold up postings. Snapshot isolation removes that risk.
  3. Sign-in. Instead of a database password you use Windows authentication over Kerberos, even when the agent runs on Linux.
  4. Offloading. If an Always On availability group exists, the agent can work on a readable secondary and never touch the primary at all.

The same pattern applies to other ERP products that sit on SQL Server, such as Sage 100; a separate guide on its specifics is planned.

What do you need before you start?

You need admin access to the SQL Server for the setup, a Linux or Windows host for the MCP server, Python 3.11 or later and Microsoft ODBC Driver 18. Kerberos requires a service account in Active Directory; the offloading scenario requires an availability group with a listener.

Versions used, as of November 2026:

Ask your ERP vendor first whether an extra schema in the production database is acceptable. Some vendors insist that reporting objects live in a separate database. In that case, create the views there and reference the ERP tables by three-part name.

Step 1: How do you create a dedicated read-only schema?

Grant the agent SELECT on exactly one schema that contains nothing but curated views. The fixed db_datareader role is too broad: according to Microsoft's documentation, its members can read all data from all user tables and views, which in an ERP includes salaries, bank details and pricing terms.

The views do a second job. They turn cryptic ERP column names into plain words that a language model can reason about, and they keep the tool description short.

-- Schema for the agent, owned by dbo
CREATE SCHEMA agent AUTHORIZATION dbo;
GO

-- Curated view with readable column names
CREATE VIEW agent.open_orders AS
SELECT h.DocNo        AS order_no,
       h.CustomerNo   AS customer_no,
       h.DocDate      AS order_date,
       h.DeliveryDate AS delivery_date,
       h.NetAmount    AS net_amount
FROM dbo.OrderHeader AS h
WHERE h.Status = 'open';
GO

-- User for the Active Directory service account
CREATE LOGIN [CORP\svc-ai-agent] FROM WINDOWS;
CREATE USER ai_agent FOR LOGIN [CORP\svc-ai-agent];

-- Read only, this schema only
GRANT SELECT ON SCHEMA::agent TO ai_agent;

-- Belt and braces against writes
ALTER ROLE db_denydatawriter ADD MEMBER ai_agent;

Table and column names are illustrative; swap in your ERP's. The GRANT … ON SCHEMA:: syntax, including the mandatory :: qualifier, is documented in the schema permissions reference. Members of db_denydatawriter cannot add, modify or delete data in user tables, which protects you if someone later grants extra rights by mistake.

Never give the agent's user ALTER on the schema. The same reference warns that ALTER on a schema can be used, through ownership chaining, to reach securables in other schemas.

Step 2: How do you stop the agent from blocking the ERP?

Turn on ALLOW_SNAPSHOT_ISOLATION for the database and have the agent start every session with SET TRANSACTION ISOLATION LEVEL SNAPSHOT. Snapshot transactions don't request locks when reading, don't block writers, and aren't blocked by them.

Why it matters: with READ_COMMITTED_SNAPSHOT off, which is SQL Server's default, the engine uses shared locks to protect rows during reads, as the isolation level reference explains. A model-generated query that scans a large document table without a useful index holds those locks for as long as it runs, and postings queue up behind it.

-- Once, as an administrator
ALTER DATABASE [ERP] SET ALLOW_SNAPSHOT_ISOLATION ON;

The option has to be on before any transaction can use the SNAPSHOT level. The agent then opts in per session, and the ERP keeps behaving exactly as before.

Why not simply switch on READ_COMMITTED_SNAPSHOT? Because that changes the behaviour of every reader, the ERP included, and that is the vendor's call rather than the agent project's. Even ALLOW_SNAPSHOT_ISOLATION is not free: row versioning adds work to every data modification. Agree the change with whoever runs the database and watch the load for the first few weeks.

Step 3: How do you set up Windows authentication with Kerberos?

Run the MCP server under an Active Directory service account and connect with Trusted_Connection=yes. No database password sits in a config file, and access is tied to an account your IT team already manages and can disable in one place.

On Linux, ODBC Driver 18 supports Kerberos through GSSAPI, according to Microsoft's integrated authentication guide. Three points from that guide matter in production:

  • The service account needs a Kerberos ticket before connecting, obtained with kinit, either interactively or from a keytab provisioned for the service principal.
  • Tickets expire and the ODBC driver does not renew them. Schedule a timer that re-runs kinit from the keytab.
  • If Kerberos fails, the driver on Linux and macOS does not fall back to NTLM. Problems surface immediately rather than as a silent downgrade.
# Get a ticket from the keytab (principal names are case-sensitive)
kinit -kt /etc/ai-agent/svc-ai-agent.keytab svc-ai-agent@CORP.EXAMPLE
klist

Keep the keytab on the host with tight file permissions, never in a repository. On a Windows host you skip kinit and run the MCP server as a service under the service account.

Step 4: How do you route reads to a readable Always On secondary?

Connect to the availability group listener, name the database and set ApplicationIntent=ReadOnly. With read-only routing configured, the primary hands the connection to a readable secondary, so the agent's queries never run on the primary.

Microsoft's read-only routing guide lists the client requirements: TCP, the listener of a group with read-only routing, a database in that group, and an application intent of read-only. The connection string reference also recommends MultiSubnetFailover=Yes for listeners.

Two properties of a secondary suit agents well. According to Microsoft, all queries on secondary databases are automatically mapped to snapshot isolation, and locking hints are ignored. A stray WITH (TABLOCKX) from the model does no harm there.

The trade-off is lag. Microsoft describes the latency as typically a few seconds, though it can grow considerably when, for example, the network has problems. That is fine for "which orders are open?" and wrong for "has the payment from ten seconds ago been posted?". Check your licensing terms before you use a secondary for read workloads.

Step 5: How do you build the MCP server?

The server offers two tools: list the views in schema agent, and run one SELECT with a row cap. The real protection is the permission model from step 1. The check in code only catches obvious mistakes early and gives the model an error message it can act on.

uv init sql-agent && cd sql-agent
uv add "mcp[cli]==2.3.0" "pyodbc==5.5.0"
# server.py - read-only access to schema agent
import os
import re
from contextlib import closing

import pyodbc
from mcp.server import MCPServer

mcp = MCPServer("sql-server-erp")

CONN_STR = (
    "Driver={ODBC Driver 18 for SQL Server};"
    f"Server=tcp:{os.environ['MSSQL_LISTENER']},1433;"
    f"Database={os.environ['MSSQL_DATABASE']};"
    "Encrypt=yes;TrustServerCertificate=no;"
    "Trusted_Connection=yes;"
    "ApplicationIntent=ReadOnly;MultiSubnetFailover=Yes;"
)
MAX_ROWS = 200
ALLOWED = re.compile(r"^\s*(SELECT|WITH)\b", re.IGNORECASE)
FORBIDDEN = re.compile(
    r"\b(INSERT|UPDATE|DELETE|MERGE|EXEC|EXECUTE|DROP|ALTER|CREATE|"
    r"GRANT|INTO|OPENROWSET|OPENQUERY|XP_\w+)\b|;",
    re.IGNORECASE,
)


def connect() -> pyodbc.Connection:
    conn = pyodbc.connect(CONN_STR, autocommit=True, timeout=10)
    conn.timeout = 30  # query timeout in seconds
    conn.execute("SET TRANSACTION ISOLATION LEVEL SNAPSHOT;")
    return conn


@mcp.tool()
def list_views() -> list[str]:
    """List the approved views in schema agent."""
    with closing(connect()) as conn:
        rows = conn.execute(
            "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS "
            "WHERE TABLE_SCHEMA = 'agent' ORDER BY TABLE_NAME"
        ).fetchall()
    return [f"agent.{r.TABLE_NAME}" for r in rows]


@mcp.tool()
def run_query(sql: str) -> dict:
    """Run exactly one SELECT against views in schema agent."""
    if not ALLOWED.match(sql) or FORBIDDEN.search(sql):
        return {"error": "Only a single SELECT without semicolons."}
    with closing(connect()) as conn:
        cur = conn.execute(sql)
        columns = [c[0] for c in cur.description]
        rows = cur.fetchmany(MAX_ROWS)
    return {
        "columns": columns,
        "rows": [[str(v) for v in r] for r in rows],
        "truncated": len(rows) == MAX_ROWS,
    }

A few details come straight from the documentation. Encrypt=yes is already the default in ODBC Driver 18, per Microsoft's keyword reference; stating it makes the intent explicit. The timeout argument to pyodbc.connect only sets the login timeout, as the pyodbc wiki notes; queries are governed by Connection.timeout, whose default of zero means no limit at all. Without that line, one badly written query could run indefinitely.

No availability group? Replace the listener with the server name and drop ApplicationIntent and MultiSubnetFailover. The snapshot line still keeps the agent from taking read locks on the primary.

How do you test it?

Test in three layers: permissions directly in SQL, then the tools in the MCP inspector, and only then the agent. When something fails you know which layer is at fault, and you don't mistake a permissions problem for a poor model answer.

Permissions. Sign in as the service account. SELECT TOP 5 * FROM agent.open_orders; must return rows, while SELECT TOP 5 * FROM dbo.OrderHeader; and any UPDATE must fail with a permission error. Don't move on until they do.

Routing. Over the MCP server's connection string, run SELECT @@SERVERNAME;. If it returns a secondary's name, read-only routing works.

Tools. Start the server with the SDK's inspector:

export MSSQL_LISTENER=erp-ag-listener.corp.example
export MSSQL_DATABASE=ERP
uv run mcp dev server.py

Call list_views and run_query by hand, including deliberately bad input such as DELETE FROM agent.open_orders. For a long-running networked deployment, uv run mcp run server.py --transport streamable-http starts the server on the Streamable HTTP transport.

Agent. Ask ten typical business questions and compare the answers with a report you pull from the ERP yourself. When answers drift, look at view names and column descriptions before you suspect the connection.

What about operations, cost and security?

Three things count in production: cap the load, log every query, and keep data on your own network. With the database, the MCP server and, if you choose, the model itself running on-premise, ERP data never leaves the building, which is the point of a sovereign AI setup.

  • Cap the load. Resource governor lets you reserve or limit CPU, memory and physical I/O for a workload group, and you can classify the service account into its own group. Microsoft states that from SQL Server 2025 it is available in Standard edition too; earlier versions offer it only in Enterprise and Developer.
  • Log queries. Record every query in the MCP server with timestamp, the user's question and runtime. That is how you improve the views and how you spot misuse.
  • Cap results. The row limit protects the model's context window as well as the database. For totals and KPIs, aggregate views beat raw rows.
  • Know the limits. Free-form SQL from an agent is the wrong tool for figures that go into financial statements or regulatory filings. Those belong in fixed, reviewed reports.

Most of the effort goes into designing views and agreeing changes with the ERP partner and IT. The ODBC driver, pyodbc and the MCP SDK are free to download.

Where to go next

Start with three to five views for one department, such as inside sales or field service, and widen the scope only once the answers there are reliable. Every new view is a deliberate decision to expose data.

After that, consider adding column descriptions to the tool descriptions, turning frequent questions into fixed, parameterised tools instead of free SQL, and applying the same pattern to other systems. For how agents like this fit into day-to-day processes, see our overview of AI agents for business processes.

Frequently asked questions

Is db_datareader good enough for an AI agent?

Rarely on an ERP database: members of db_datareader can read every user table and view in the database. Grant SELECT on one schema of curated views instead.

Can a read-only agent slow down the ERP?

Yes. Under SQL Server's default read committed behaviour, reads take shared locks. Snapshot transactions don't request locks when reading and don't block writers.

Do I need an Always On availability group?

No. For a handful of small queries, snapshot isolation on the primary is enough. A readable secondary pays off once the agent runs many or expensive queries.

Does Windows authentication work from a Linux host?

Yes. Microsoft ODBC Driver 18 supports Kerberos on Linux and macOS. You need a valid ticket from kinit, and the driver will not renew it for you.

Sources

  1. Microsoft Learn: Database-level roles learn.microsoft.com
  2. Microsoft Learn: GRANT Schema Permissions (Transact-SQL) learn.microsoft.com
  3. Microsoft Learn: SET TRANSACTION ISOLATION LEVEL (Transact-SQL) learn.microsoft.com
  4. Microsoft Learn: Offload read-only workload to secondary replica of an Always On availability group learn.microsoft.com
  5. Microsoft Learn: Configure read-only routing for an Always On availability group learn.microsoft.com
  6. Microsoft Learn: Using Integrated Authentication (ODBC Driver on Linux and macOS) learn.microsoft.com
  7. Microsoft Learn: DSN and Connection String Keywords and Attributes learn.microsoft.com
  8. Microsoft Learn: Download ODBC Driver for SQL Server learn.microsoft.com
  9. Microsoft Learn: Resource governor learn.microsoft.com
  10. PyPI: pyodbc pypi.org
  11. pyodbc Wiki: Connection github.com
  12. PyPI: mcp (Model Context Protocol Python SDK) pypi.org