Skip to main content

06 - MCP and Cursor: Connect IDE to Databases and APIs

How to connect Cursor to databases and APIs with MCP: mcp.json, official and archived servers, a read-only TypeScript server tested in memory, and security.

What do you think about this article?

06 - MCP and Cursor: Connect IDE to Databases and APIs
Cursor IDEPhoto:Godfrey AtimaPexels

At a Glance

How to connect Cursor to databases and APIs with MCP: mcp.json, official and archived servers, a read-only TypeScript server tested in memory, and security.

The problem: the assistant cannot see your system

You ask Cursor to write a query for the orders table and it invents the columns, because the real schema lives in your database and not in the chat window. The manual fix is to paste the schema into every request, but the copy goes stale the next day. The Model Context Protocol (MCP) is the standard way to give the editor direct, controlled access to an external system: the assistant asks, and a small program answers with the real data.

Direct access has a price, though: every MCP server is code that runs on your machine with your credentials. That is why this article does not just list servers to install. It explains how Cursor is configured, which servers really exist today (two of the most quoted ones have been archived), how to write and test your own server in TypeScript, and where a configuration mistake costs the most. In the previous article, on hooks, you automated what happens around the agent; here you give it tools that reach outward.

How MCP is built: host, client, server

The specification describes an architecture with three roles. Cursor is the host: the application you talk to, which decides which connections to open and when to ask for your consent. For each configured server the host creates a client, which talks to that one server only. The server is the program that exposes the capabilities: it can be a local process launched by Cursor or a remote service.

  • Host: Cursor, which orchestrates the clients, applies the consent rules and keeps the full conversation.
  • Client: one instance per server, in a one-to-one relationship, which attaches version and capabilities to every request.
  • Server: exposes tools, resources and prompts, and receives only the context it needs.

The separation has a practical consequence: a server sees neither your conversation nor the other servers, so a badly written server can only go wrong inside its own perimeter. It is one of the design principles stated in the architecture page of the specification and the reason to prefer a small server for each system over a single server that does everything.

Tools, resources and prompts

A server offers three kinds of primitives, which differ in who decides to use them. The comparison below is the quickest way to choose which one to use when you write your own.

PrimitiveWho triggers itExample in an orders server
ToolThe model, after your approvalRunning a SELECT with a filter
ResourceThe application or you, to attach data to the contextThe list of tables
PromptYou, by picking a request template"Analyze the performance of this query"

In practice almost everything goes through tools, because they are the only primitive the model invokes on its own when the task requires it. Resources are for data you want to attach explicitly, prompts for requests you repeat often. In its MCP documentation Cursor states that it supports tools, prompts, resources, roots and elicitation.

Transports and specification revision

Messages travel as JSON-RPC over one of two standard transports. With stdio Cursor launches the server as a child process and talks over standard input and output: this is the case for local servers, and Cursor manages the process lifecycle by itself. With Streamable HTTP the server is a remote service you connect to with a URL. The old HTTP+SSE transport is declared deprecated in the changelog of the current revision, which says to migrate to Streamable HTTP, even though Cursor's documentation still lists SSE among the ones it can use.

The current revision of the specification, as of 2026-11-13, is 2026-07-28, and it changed quite a lot: it removed the initialize handshake and the protocol-level sessions, and every request now carries its own version and capabilities. This is not an academic detail: the TypeScript SDK you install from npm (1.32.2, measured in the package's types.js file) declares 2025-11-25 as the latest revision, the one with the handshake. The servers you write today with the SDK therefore speak the previous revision, and an example that hand-sends an initialize message is correct only for that one. In the code below we do not write messages by hand: we let the SDK handle the version.

Where it is configured: mcp.json

Cursor reads servers from a JSON file in two locations: .cursor/mcp.json in the project root, for the tools that repository needs, and ~/.cursor/mcp.json in your home folder, for the ones you want everywhere. The documentation does not say what happens if the same name appears in both: use different names and you will not have to find out.

For a local server the fields are type ("stdio"), command, args, env and envFile. For a remote one url and, if needed, headers are enough. The command must be on the PATH or written with its full path; envFile exists only for stdio servers. The most useful element, however, is interpolation: in the command, args, env, url and headers fields Cursor replaces ${env:NAME} with an environment variable, ${workspaceFolder} with the project root, and ${userHome} with the home folder. The syntax is exactly this, with the colon: forms such as {{env.NAME}} or ${NAME} are not documented.

The first example connects Cursor to the GitHub server hosted by GitHub itself. It is remote, so there is no Docker and no local process. The personal token is not written in the file but read from the GITHUB_PAT variable, so the file can end up in the repository without secrets. GitHub's guide for Cursor notes that this server requires a Personal Access Token and a version of Cursor that supports Streamable HTTP.

{
  "mcpServers": {
    "github": {
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer ${env:GITHUB_PAT}"
      }
    }
  }
}

If you remove headers the server does not receive the token that GitHub's guide requires; if the token has fewer permissions than needed, the tools that require them fail one by one and the others keep working. That is why it is better to create a short-lived token limited to the repositories you need, rather than a token with access to your whole account. GitHub also documents a local variant via Docker with OAuth login, which we do not use here because it requires Docker.

When a stdio server has several secrets, envFile saves you from repeating them one by one. The file it points to contains KEY=value lines and sits in .gitignore: only the path remains in the versioned mcp.json.

{
  "mcpServers": {
    "internal-service": {
      "type": "stdio",
      "command": "node",
      "args": ["${workspaceFolder}/mcp/dist/index.js"],
      "envFile": "${workspaceFolder}/.env.mcp"
    }
  }
}

Here dist/index.js stands for a server you have already compiled: the block is a schema to adapt, not something that starts as it is. Remember that JSON allows neither comments nor trailing commas: a syntax error is the most mundane cause of a server missing from the list.

A ready-made MCP server for Angular

If you work on an Angular project, the most useful server is the CLI's. Angular's documentation describes it as experimental and says it gives the agent tools such as get_best_practices, list_projects and run_target, the last one to run tests or builds. You do not have to write its configuration: ng new --ai-config=cursor (tried with CLI 22.2.7) creates a .cursor/mcp.json with the content below.

{
  "mcpServers": {
    "angular-cli": {
      "command": "npx",
      "args": ["-y", "@angular/cli", "mcp"]
    }
  }
}

The command is npx -y, so it downloads and runs the latest version of the CLI at every start: for an Angular package that is a reasonable risk, for an unknown third-party server it is not. If you want the agent to be able only to read, the documentation provides the --read-only argument after mcp, which registers only the tools that do not modify the project. The complete flow with this server is in the last article of the series, the professional workflow in Angular.

Database servers: what really exists

The first idea is to install "the PostgreSQL MCP server". The reference package, @modelcontextprotocol/server-postgres, exists on the npm registry but its latest version is 0.6.2 from December 2024 and the registry marks it "Archived and unmaintained; no security guarantees". The same goes for @modelcontextprotocol/server-github, latest version of 8 April 2025 with the same notice: for GitHub you use the official server seen above. The @modelcontextprotocol/server-sqlite package mentioned in many guides does not exist in the registry (404 response on 2026-11-13). These are checks you can repeat with npm view before trusting a name copied from a tutorial.

  • Last publication: a server that has been still for years receives no security fixes.
  • The registry's "deprecated" field: signals archiving declared by the maintainer.
  • Repository and maintainer: who writes it and whether they answer reports.
  • Read-only mode: if missing, security depends entirely on the database user.

The last criterion matters most. A database server that accepts any statement leaves your security at a single level, the user you connect with. For this reason, and because a server that opens a database is much simpler than it looks, the most controllable route is to write your own, minimal one. If you choose a third-party server instead, one more caution applies: with npx -y you download and run the latest published version on your computer, and a compromised dependency runs with your permissions.

Writing an MCP server in TypeScript and testing it

The example server exposes a single tool, run_select, and a resource with the list of tables, on a SQLite database. I chose SQLite because the node:sqlite module is included in Node 24 (with the "experimental" warning it prints at startup): there is no service to start, and the security logic is the same you would apply to PostgreSQL. The official SDK is @modelcontextprotocol/sdk, with zod to describe the parameters.

mkdir mcp && cd mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/sdk zod

npm pkg set type=module is required: without it, Node treats the files as CommonJS and rejects the import statements, an error I ran into while testing the code. Node 24 runs .ts files directly when they use only erasable syntax, so the example needs no compile step; for a server you distribute you will use tsc instead and point mcp.json at the compiled file.

The data layer, with security built in

I keep the logic apart from the protocol, so it can be tested without MCP. apriInSolaLettura passes readOnly: true to the constructor: it is the SQLite engine that rejects writes, not a check on the text. eseguiSelect adds a second barrier: it accepts only statements that start with SELECT, rejects an inner semicolon and truncates the result to 50 rows, so a huge table does not fill the model's context window. The check on the text is deliberately the weak barrier: it exists to give the model a clear message, while the real protection is opening the database read-only.

import { DatabaseSync } from "node:sqlite";

const MAX_RIGHE = 50;

// Opens the database read-only: writing is impossible at the engine level,
// not just because of a check on the query text.
export function apriInSolaLettura(percorso: string): DatabaseSync {
  return new DatabaseSync(percorso, { readOnly: true });
}

export function eseguiSelect(db: DatabaseSync, sql: string): unknown[] {
  const pulita = sql.trim().replace(/;+\s*$/, "");
  if (!/^select\s/i.test(pulita)) {
    throw new Error("Only SELECT statements are allowed");
  }
  if (pulita.includes(";")) {
    throw new Error("One statement per call");
  }
  return db.prepare(pulita).all().slice(0, MAX_RIGHE);
}

export function elencaTabelle(db: DatabaseSync): string[] {
  const righe = db
    .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
    .all() as { name: string }[];
  return righe.map((r) => r.name);
}

Measured: with the file opened read-only, a DELETE fails with "attempt to write a readonly database". If you drop readOnly and rely only on the check on the text, the protection depends on two lines of regular expression, and a check like that does not withstand a determined attempt. With PostgreSQL the equivalent is a role with SELECT permissions only, created for this purpose.

The protocol layer

McpServer is the SDK's high-level class. registerTool receives the name, a description that the model reads to decide when to use the tool, and the parameter schema in zod; the function's second argument is your logic. When it fails, it does not throw an exception: it returns isError: true with a text. The specification distinguishes protocol errors from execution errors and recommends that the latter reach the model, so that it can correct the request and try again. The last block at the bottom of the file is the part that launches the real server over stdio, and writes its logs to console.error: only the protocol must go through stdout.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { apriInSolaLettura, eseguiSelect, elencaTabelle } from "./db.ts";

export function creaServer(percorsoDb: string): McpServer {
  const db = apriInSolaLettura(percorsoDb);
  const server = new McpServer({ name: "orders-readonly", version: "1.0.0" });

  server.registerTool(
    "run_select",
    {
      description: "Runs a SELECT on the orders database (max 50 rows, read-only)",
      inputSchema: { sql: z.string().min(1).max(2000) },
    },
    async ({ sql }) => {
      try {
        const righe = eseguiSelect(db, sql);
        return { content: [{ type: "text", text: JSON.stringify(righe) }] };
      } catch (errore) {
        // isError tells the model the call failed, without bringing the server down
        return {
          isError: true,
          content: [{ type: "text", text: (errore as Error).message }],
        };
      }
    },
  );

  server.registerResource(
    "tables",
    "schema://tables",
    { description: "List of the database tables", mimeType: "application/json" },
    async (uri) => ({
      contents: [{ uri: uri.href, text: JSON.stringify(elencaTabelle(db)) }],
    }),
  );

  return server;
}

// Real startup over stdio: every log goes to stderr, stdout belongs to the protocol
if (process.argv[1]?.endsWith("server.ts")) {
  const server = creaServer(process.env.DB_PATH ?? "./orders.db");
  await server.connect(new StdioServerTransport());
  console.error("orders-readonly ready");
}

The condition process.argv[1]?.endsWith("server.ts") prevents importing the module from the test from opening the stdio channel. The stdio transport specification says the server must not write to stdout anything that is not a valid message: a single debug console.log corrupts the stream, because the client receives a line it cannot interpret as a message.

The test, without starting anything

To test the tool you need neither Cursor nor a network port. The SDK provides InMemoryTransport, a pair of linked channels inside the same process: the server on one side, a real client on the other. The script prepares a database with three orders, lists the tools, calls run_select three times (one valid, two that must be rejected) and reads the resource.

import { DatabaseSync } from "node:sqlite";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { creaServer } from "./src/server.ts";

// Prepares a test database with three orders
const scrittura = new DatabaseSync("./orders.db");
scrittura.exec(`DROP TABLE IF EXISTS orders;
  CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total_cents INTEGER);
  INSERT INTO orders (customer, total_cents) VALUES ('Rossi', 4990), ('Bianchi', 12000), ('Rossi', 2500);`);
scrittura.close();

const [latoClient, latoServer] = InMemoryTransport.createLinkedPair();
await creaServer("./orders.db").connect(latoServer);
const client = new Client({ name: "test", version: "1.0.0" });
await client.connect(latoClient);

const { tools } = await client.listTools();
console.log("tools:", tools.map((t) => t.name));

const chiama = async (sql: string) => {
  const r = await client.callTool({ name: "run_select", arguments: { sql } });
  console.log(r.isError ? "ERROR" : "OK", (r.content as { text: string }[])[0].text);
};
await chiama("SELECT customer, SUM(total_cents) AS tot FROM orders GROUP BY customer ORDER BY customer");
await chiama("DELETE FROM orders");
await chiama("SELECT 1; DROP TABLE orders");

const risorsa = await client.readResource({ uri: "schema://tables" });
console.log("resource:", (risorsa.contents[0] as { text: string }).text);
await client.close();

// Output (node prova.ts, Node 24.11.0, SDK 1.32.2; identical in two runs):
// tools: [ 'run_select' ]
// OK [{"customer":"Bianchi","tot":12000},{"customer":"Rossi","tot":7490}]
// ERROR Only SELECT statements are allowed
// ERROR One statement per call
// resource: ["orders"]

The output shows the three things I wanted to verify: the sum per customer is computed by the database (Rossi 4990 + 2500 = 7490 cents), the DELETE and the double statement come back as readable errors and not as crashes, and the resource lists the single table orders. The test does not, however, prove Cursor's behavior: the integration with the editor was not run, because Cursor is not installed on the test machine. To use it, add the second mcp.json block below.

{
  "mcpServers": {
    "orders": {
      "type": "stdio",
      "command": "node",
      "args": ["${workspaceFolder}/mcp/src/server.ts"],
      "env": {
        "DB_PATH": "${workspaceFolder}/data/orders.db"
      }
    }
  }
}

With ${workspaceFolder} the paths stay valid on every machine of the team and you do not need to write them as absolute paths. After saving, the server appears in Cursor's list; if it does not, look at the logs, as explained in the last section.

Security: three levels, and one real vulnerability

An MCP server runs code with your permissions, and Cursor's documentation says so plainly: use only servers from trusted developers, check which data and APIs they touch, limit the permissions of the keys, read the code for critical integrations. By default Cursor asks for approval before every tool call and shows the arguments: leave it on, especially for servers that can write.

  • Credentials: in mcp.json only ${env:NAME} references, never the value.
  • Permissions: a database user with SELECT only, a GitHub token that is limited and expires.
  • Perimeter: the filesystem server receives only the folders you give it, not your home.
  • Environments: one server for development and a separate one for production, never a single one that points to both.

The levels add up and none is enough alone. Permissions are the level that saves you when credentials end up where they should not: if the token ends up in a log by mistake, a read-only token limited to two repositories causes far less damage than one with full access. For production servers it is better not to expose them to the editor at all, and to work on a copy of the data.

The documented vulnerability is CVE-2025-54136 (published on 2025-08-02, CVSS v3.1 score between 7.2 and 8.8 according to the assessments recorded in the NVD). In Cursor versions up to 1.2.4, anyone who could modify an already approved MCP configuration file, in a shared repository or locally, could replace the command that was run without the editor asking for a new confirmation. It was fixed in 1.3. The lesson remains valid even with an updated editor: after every git pull that touches .cursor/mcp.json, read the file's diff as you would read an install script, because that is exactly what it is.

When it does not pay off, and how to diagnose it

MCP is not free. Every active server adds tools whose description the model must read on every request: each extra tool is one more description to read and another chance of picking the wrong one, which is why Cursor lets you disable a server from the Customize page, and the documentation cites reducing the tools in the list among the reasons. A server makes sense when the information changes often (the schema, the issues) and pasting it every time would be annoying; for stable information, such as the project's conventions, the rules from the second article of the series are enough. If instead the task is a long sequence, it is Agent Mode that has to use them, call by call, with your approval.

When a server does not respond, the first place to look is the logs: the documentation says to open the Output panel (Ctrl+Shift+U, Cmd+Shift+U on Mac) and choose "MCP Logs" in the dropdown, where startup, calls and errors appear. For the most frequent failures the symptoms and causes are these.

  1. The server does not start: the command is not on Cursor's PATH, write the full path (which node).
  2. The server does not appear: invalid JSON, check with python3 -m json.tool .cursor/mcp.json or jq ..
  3. It connects and immediately disconnects: something writes to stdout, move the logs to stderr.
  4. It starts but does not authenticate: the ${env:...} variable is not defined in the environment you launched Cursor from.

The order matters here: check the items from the first, because each later failure presupposes that the previous one is ruled out. A server that does not start cannot write to stdout, and there is no point looking for a missing token if the file cannot be read. For the last case, the simplest fix is to launch Cursor from a terminal where the variable is already exported, or to use envFile.

What you can do now

You can configure an MCP server in Cursor with the right syntax, tell maintained servers from archived ones, write a read-only tool for a database in TypeScript and test it with an in-memory client before connecting it to the editor. You also know the limits: the integration with the editor was not run here. The next article moves on to debugging; the previous one, on hooks, shows how to keep control over what the agent does.

Frequently asked questions

Where does the mcp.json file go in Cursor?

In .cursor/mcp.json in the project root for the tools of that repository, or in ~/.cursor/mcp.json for the ones available everywhere. The structure is the same: an mcpServers object with one entry per server.

How do you pass secrets to an MCP server without writing them in the file?

With the ${env:NAME} interpolation in the env, headers, args and url fields, or with envFile for stdio servers. The value stays in an environment variable or in a file excluded from git.

Is Anthropic's MCP server for PostgreSQL still usable?

The npm package @modelcontextprotocol/server-postgres is stuck at 0.6.2 from December 2024 and the registry flags it as archived and without security guarantees. Better a maintained server, or your own minimal read-only one.

The same series also includes Cursor IDE: The Complete Developer Guide.

Sources

The server code was run with Node 24.11.0 and @modelcontextprotocol/sdk 1.32.2 in a temporary folder, with an in-memory client and without opening ports. The mcp.json blocks were validated as JSON (the Angular one is the file created by the CLI) but not tried inside Cursor, which was not installed. The state of the npm packages was read from the registry on 2026-11-13.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects