If you're embedding Neon operations into your own agent runtime, you need a way to expose them as tools: an MCP server for your team, an agent built with a framework like Mastra or Eve, or a dev tool that resets test data. The Model Context Protocol (MCP) lets you publish a catalog of tools that any MCP client can call over stdio or HTTP.
The hosted Neon MCP Server already gives you this by default. It pairs workflow tools for SQL, migrations, diagnostics, docs, and search with Management API tools across projects, branches, endpoints, snapshots, auth, storage, functions, and more. It adds OAuth, category filtering, read-only mode, and project scoping, so you can connect Claude Code, Cursor, or any MCP client.
@neon/tools gives you the same building blocks for your own server. You pick the SDK operations to expose, such as projects.list for listing projects or branches.createAndConnect for creating a ready-to-use branch, and customize how each one appears to the model. Each selection becomes a tool with a Zod schema, flat snake-case inputs, auto-pagination for lists, readiness polling for writes, and approval metadata. The MCP adapter then publishes that catalog with model-facing IDs like list_projects and create_and_connect_branches.
Choose the approach that fits your workflow:
| Approach | When to use it | What you get |
|---|---|---|
| Hosted Neon MCP Server | Connect your own agent to Neon | Full catalog of workflow and API tools, OAuth, read-only mode, and project scoping. No code to maintain. |
Custom server with @neon/tools (this guide) | Embed Neon tools in your own runtime | Subset catalog, project injection, custom names and descriptions, logging, and multi-tenant HTTP. |
In this tutorial, you'll build a minimal MCP server with five project and branch tools, run it over stdio, and connect it to Claude Code. You'll then customize it with project injection, custom names and descriptions, and logging. Finally, you'll serve the same catalog remotely over HTTP so multiple agents can call it with their own credentials. The same pattern scales when you add snapshots, endpoints, auth, storage, and functions that the @neon/tools package already exposes.
How credentials flow
Before you start, decide how your server will handle Neon credentials. There are two patterns:
Single credential, held by the server. You set NEON_API_KEY once, and every tool call runs against that account. This is the stdio pattern covered in the first part of this guide: one user, one agent, one key. It fits a personal coding agent or an internal tool where the operator owns the Neon account.
Per-request credential, brought by the client. The server holds no key at all. Each client sends its own token with every request, and tools execute against that client's account. This is the HTTP pattern covered in the final section. The token is the tenant boundary: your server never stores a Neon credential, and a client can only reach projects its token grants.
Prerequisites
Before you begin, make sure you have the following:
- Node.js: Version
20.19or later (version22or later recommended). Download from Node.js. - Neon account and project: A Neon account with at least one project. Sign up at Neon if you do not have one.
Generate a Neon API key
To allow programmatic access to Neon, you need a Neon API key. Your server uses it to call the Neon API and manage branches on demand.
-
In the Neon Console, switch to your organization, then go to Settings > API keys.
-
Click Create new and give the key a name (for example, "custom MCP server").

Use an organization key
Create an organization API key rather than a project-scoped key, so the server can manage branches across all projects in your organization.
-
Copy the generated API key.
To create keys with the CLI or API instead, see Manage API keys.
-
Select the tools you want to expose
You will expose five SDK methods as MCP tools:
SDK path you select MCP tool ID the model sees What it does projects.listlist_projectsLists projects with auto-pagination branches.listlist_branchesLists branches for a project branches.createAndConnectcreate_and_connect_branchesCreates a branch, waits until ready, returns a connection string branches.resetFromParentreset_from_parent_branchesResets a branch from its parent with an optional preserve copy branches.compareSchemacompare_schema_branchesDiffs schema for a database on a branch The complete selector list is exported as
toolIdsfrom@neon/tools. View thetoolIdssource for the full set of SDK paths you can expose. Each path publishes to the model as a snake-case tool ID:projects.listbecomeslist_projects,branches.createAndConnectbecomescreate_and_connect_branches, and so on.Scaffold the server project
Create a new directory and install dependencies:
mkdir neon-custom-mcp && cd neon-custom-mcp npm init -y npm install @neon/tools @modelcontextprotocol/server npm install -D typescript @types/node tsx npx tsc --initThe
@neon/toolspackage is the SDK adapter that builds a catalog of tools. The MCP server package publishes that catalog over stdio or HTTP.@neon/toolsuses Zod for input validation. TypeScript andtsxare for building and running the server.Update
tsconfig.jsonfor ESM and strict validation:tsconfig.json{ "compilerOptions": { "target": "ES2022", "module": "ES2022", "types": ["node"], "moduleResolution": "bundler", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "noEmit": true }, "include": ["src/**/*"] }Create a
.envfile in the project root and add your Neon API key copied from the Generate a Neon API key step:NEON_API_KEY="your_neon_api_key"Create the tool catalog
Create
src/tools.tsto select the five tools you want to expose:src/tools.tsimport { createNeonTools } from "@neon/tools"; const apiKey = process.env.NEON_API_KEY; if (!apiKey) throw new Error("NEON_API_KEY is required"); export const tools = createNeonTools({ apiKey, tools: [ "projects.list", "branches.list", "branches.createAndConnect", "branches.resetFromParent", "branches.compareSchema", ] as const, wait: { timeoutMs: 30_000 }, });The
createNeonTools()function builds a catalog with Zod schemas, input validation, and approval metadata. Thetoolsrecord is keyed by the SDK path you selected, sotools["projects.list"]maps directly to the client method. Each entry has anexecute()method that takes a flat input object and returns a promise with the result. The catalog has two behaviors worth knowing:- Flat inputs with auto-pagination: List tools take
limitand return the item array with pagination handled for you. - Readiness waits on writes: Write tools run with
waitForReadiness: true, so a branch create waits for its operations before it resolves. The default deadline is five minutes. Here it is capped at 30 seconds so it stays below typical host timeouts.
You can test the catalog with a script that lists the first five projects:
src/smoke.tsimport { tools } from "./tools.js"; const main = async () => { const listed = await tools["projects.list"].execute({ limit: 5 }); console.log(listed.data.map((p) => p.name)); } main().catch((err) => { console.error(err); process.exit(1); });Run it with:
npx tsx --env-file=.env src/smoke.tsYou should see an array of project names. If you get an error, check your
NEON_API_KEYin.env.- Flat inputs with auto-pagination: List tools take
Register tools with an MCP server
The MCP adapter publishes your selected catalog through
registerNeonTools().Create
src/index.tsto wire the catalog to an MCP server over stdio:src/index.tsimport { McpServer } from "@modelcontextprotocol/server"; import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; import { registerNeonTools } from "@neon/tools/mcp"; import { tools } from "./tools.js"; const server = new McpServer({ name: "neon-custom", version: "1.0.0" }); registerNeonTools(server, tools); const main = async () => { await server.connect(new StdioServerTransport()); }; main().catch((err) => { console.error(err); process.exit(1); });Using MCP 1.x?
This code uses the MCP 2.x SDK. If you're maintaining an older MCP 1.x server, import from
@neon/tools/mcp-v1instead. Your tool IDs andexecute()behavior stay the same; only the schema format changes.Connect your coding agent to the server
Point your client at the local server over stdio. Use an absolute path to
src/index.ts.Create
.mcp.jsonin your project root:.mcp.json{ "mcpServers": { "neon-custom": { "command": "npx", "args": ["tsx", "/absolute/path/to/neon-custom-mcp/src/index.ts"], "env": { "NEON_API_KEY": "your_neon_api_key" } } } }Replace
/absolute/path/to/neon-custom-mcp/src/index.tswith the absolute path to yoursrc/index.tsfile, andyour_neon_api_keywith your Neon API key.Run
claudein your project directory and select Use this MCP server when prompted. You should see the following output:$ claude ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── New MCP server found in this project: neon-custom MCP servers may execute code or access system resources. All tool calls require approval. Learn more in the MCP documentation. ❯ Use this MCP server Use this and all future MCP servers in this project Continue without using this MCP serverExit the session and run the following command to list the connected MCP servers:
$ claude mcp list neon-custom: npx tsx /absolute/path/to/neon-custom-mcp/src/index.ts - ✔ ConnectedYou should see
neon-customlisted as connected.Using other clients?
The same stdio command works for Cursor, Codex, Windsurf, Zed, and Cline. Any client that accepts
command,args, andenvfor a local MCP server can launch this file. Check your client's documentation for how to configure local MCP servers.Try branch workflows from prompts
Open a new agent session in your project directory and confirm that the server works by using the five tools you exposed. The agent will call the server over stdio, which calls the Neon API with your key.
Start with discovery:
List my Neon projects and then list branches for the first project.Then create an isolated branch for testing:
Create a branch named 'mcp-test' from the main branch. Return the connection string and branch ID.Because this is a write tool, your client may ask for approval first. The package marks every non-read operation as requiring approval, along with reads that return credentials. The protocol does not enforce it, so keep your client's approval setting on.
Next, compare schemas without writing SQL by hand:
Compare schema between the mcp-test branch and main.If you want to throw away test changes and start over:
Reset branch mcp-test from its parent. Preserve the current state under mcp-test-before-reset.Customize names, inputs, and logging
You can change how the catalog appears to the model without changing the underlying SDK. This is useful when you want to hide fields, rename tools, or add workflow-specific guidance.
Fix project context with injection
Tools take
project_idas an input. A host that already knows the project can inject it instead, so the agent never has to guess or pass it. This works in two ways depending on your credential model.With a server-held key, inject a fixed project to lock the server to it. This pairs a single credential with a single project, useful when the server exists to serve one codebase:
src/scoped-tools.tsimport { createNeonTools } from "@neon/tools"; export const scopedTools = createNeonTools({ apiKey: process.env.NEON_API_KEY!, tools: ["branches.list", "branches.createAndConnect"] as const, inject: { projectId: process.env.NEON_PROJECT_ID!, omitFromSchema: true, }, });With
omitFromSchema: true, the agent callslist_brancheswithout aproject_id, and your server fills it in. Without it, the field stays optional and a caller-supplied value takes precedence. An empty inject value fails closed rather than silently matching nothing.For the HTTP server, the server holds no key and each client brings its own. You can still inject a project ID per request: pass a getter as the
injectvalue and read the caller's identity from your own request context. See the project and branch injection docs for anAsyncLocalStorageexample.Offer a narrow variant
Filter the selector list when a workflow only needs exploration. You keep one codebase and publish different catalogs per use case.
const READONLY = process.env.READONLY === "true"; const toolNames = READONLY ? (["projects.list", "branches.list"] as const) : (["projects.list", "branches.list", "branches.createAndConnect"] as const);Keep stable names and add workflow hints
Use
namesto set the published ID anddescriptionsto add workflow-specific guidance. Keys can be SDK paths or published IDs.export const renamedTools = createNeonTools({ apiKey: process.env.NEON_API_KEY!, tools: ["projects.get", "branches.delete"] as const, names: { "projects.get": "describe_project" }, descriptions: { delete_branches: "Delete a Neon branch and all its data. Ask the user for branch ID confirmation first.", }, });The record stays keyed by SDK path (
renamedTools["projects.get"]), while MCP publishesdescribe_project.Add logging
Use
onExecuteto log tool use. You must callevent.execute()inside the wrapper, since that is what runs validation, injection, auth, and the API request.export const loggedTools = createNeonTools({ apiKey: process.env.NEON_API_KEY!, tools: ["projects.list"] as const, onExecute: async ({ id, execute }) => { console.log(`[neon] tool call: ${id}`); return execute(); }, });This package sends no analytics on its own. Add your own logger here if you need audit trails for internal use.
Serve the same catalog remotely over HTTP
The stdio server works when one client launches your server locally. Agent platforms usually need the opposite shape: one deployed server that many agents call over HTTP, each with their own credentials. Streamable HTTP in the MCP 2.x SDK handles this with a per-request factory, and
registerNeonTools()supports it without changing your catalog.The server no longer holds a Neon API key. Each client supplies its own as a bearer token, and
registerNeonTools()picks it up from the MCP request'sauthInfo. Your deployed server doesn't hold any Neon credentials of its own.Install dependencies
Install the Node.js transport adapter for MCP 2.x:
npm install @modelcontextprotocol/nodeBuild a per-request server factory
Replace
src/index.tswithsrc/http.ts. Instead of one long-livedMcpServer, the handler builds a fresh instance per request:src/http.tsimport { McpServer, createMcpHandler, type AuthInfo } from "@modelcontextprotocol/server"; import { toNodeHandler, localhostHostValidation, localhostOriginValidation } from "@modelcontextprotocol/node"; import { createServer, type IncomingMessage } from "node:http"; import { createNeonTools } from "@neon/tools"; import { registerNeonTools } from "@neon/tools/mcp"; const tools = createNeonTools({ tools: ["projects.list", "branches.list", "branches.createAndConnect"] as const, wait: { timeoutMs: 30_000 }, }); const handler = createMcpHandler(() => { const server = new McpServer({ name: "neon-custom", version: "1.0.0" }); registerNeonTools(server, tools); return server; }); const nodeHandler = toNodeHandler(handler); const validateHost = localhostHostValidation(); const validateOrigin = localhostOriginValidation(); createServer((req, res) => { if (!validateHost(req, res) || !validateOrigin(req, res)) return; const token = req.headers.authorization?.replace(/^Bearer /, ""); if (!token) { res.writeHead(401, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "missing bearer token" })); return; } // MCP 2.x expects auth info on the request object. Typecast to add it. const authenticatedReq = req as IncomingMessage & { auth?: AuthInfo }; authenticatedReq.auth = { token, clientId: "neon-custom", scopes: [] }; void nodeHandler(authenticatedReq, res); }).listen(3000, "127.0.0.1");Here,
createNeonTools()takes noapiKey. A credential is only needed when a tool executes, and that credential arrives per request. This example trusts any bearer token and passes it straight through to Neon, where an invalid token fails with an API error.Verify tokens in production
In a real deployment, verify the token yourself before setting
req.auth, for example by looking it up in your session store, so only your application's users can reach the handler.Test the remote server
Start the server and list tools with a raw HTTP call:
npx tsx src/http.tscurl -X POST http://127.0.0.1:3000/mcp \ -H "Authorization: Bearer $NEON_API_KEY" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"1.0.0"}}}'A successful initialize response advertises your server and protocol version.
Connect from Claude Code and opencode
Before deploying, confirm real MCP clients can drive the server the same way they will in production. Both Claude Code and opencode accept remote HTTP servers with a bearer-token header.
Add the server as a remote HTTP server, then check it connected:
claude mcp add --transport http neon-local http://127.0.0.1:3000/mcp \ --header "Authorization: Bearer $NEON_API_KEY" claude mcp listclaude mcp listshows a health status per server;✔ Connectedmeans the handshake and tool discovery succeeded. You can verify the server works by promptingList my Neon projectsand confirming the tool call runs.If either client fails to connect, check the response status: a
401means theAuthorizationheader wasn't passed, and a403means the Host or Origin guards rejected the request.Deploy it
The handler is stateless and scales horizontally. Deploy the same file anywhere Node runs: a container, a serverless platform, or a VPC service.
Secure the deployment
Keep the server behind TLS and mount the token verification in front of the handler; the handler itself validates neither tokens nor headers.
Conclusion
Reach for this pattern when the hosted server's fixed catalog doesn't fit and you're comfortable owning the auth layer yourself, for example a team exposing only the few operations its workflow needs, or a runtime that already has its own user model and needs Neon operations behind it. If you need Neon-issued tokens and per-user project access without building that layer, the hosted Neon MCP Server is the better fit.
From here you can add snapshots, endpoints, Data API config, Functions, Object Storage, or Managed Better Auth by extending the tools array. The complete selector list is exported as toolIds from @neon/tools (see the toolIds source), and adapter examples are in the @neon/tools README.
Resources
- @neon/tools on GitHub
- Neon MCP Server reference
- Neon Management SDK
- About branching
- Model Context Protocol
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.








