Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Custom Claude MCP Server in Node.js to Query a Local SQLite Database

Stop copy-pasting database schemas. Learn how to build a secure, local Model Context Protocol (MCP) server in Node.js to give Claude direct, read-only access to your SQLite databases.

Updated 11/3/2026

We have all been there. You have a local SQLite database packed with application logs, user behaviour metrics, or side-project inventory, and you want to use an LLM to analyse it. Until recently, your options were miserable: either copy-paste raw CSV exports into the chat bar like a caveman, or build a bloated, bespoke Express API with complex authentication layers just to let an agent run a couple of read-only queries.

Enter Anthropic’s Model Context Protocol (MCP). Instead of wrapping your data in endless web-server boilerplate, MCP allows you to build a lightweight, standardised local server that exposes data, files, and tools directly to Claude via a secure local protocol.

In this guide, we are going to build a custom MCP server from scratch using Node.js and TypeScript. By the end, Claude Desktop will be able to read your local SQLite schemas, write SQL queries, and execute them locally to answer complex prompts. Let's get building.

Why Build an MCP Server Instead of a Traditional API?

Traditional LLM tool use (or function calling) requires a host of cloud-based APIs, authentication keys, and webhooks. It is a massive headache for local development, and it is a security nightmare if you are dealing with sensitive, local data.

MCP flips this architecture on its head. It runs locally over standard input/output (stdio). When you configure Claude Desktop to use your custom server, Claude spawns your Node.js script as a background process. Your local machine handles the database execution; the LLM simply decides what to ask for and how to interpret the results.

You’ll want Claude to understand exactly what makes your relational data tick without hand-feeding it raw CSV exports, and MCP is the cleanest way to do it.

Which AI should I use for this?

Tickd is independent and not affiliated with any AI company.

Prerequisites

Before we write a single line of code, ensure you have the following installed on your machine: - Node.js (v18 or higher) - npm or pnpm - Claude Desktop (currently required to test MCP locally)

Step 1: Initialize Your Project

Create a new directory for your MCP server and initialise a clean Node.js project. We will use TypeScript because robust type safety makes working with the MCP SDK a breeze.

`bash mkdir claude-sqlite-mcp cd claude-sqlite-mcp npm init -y `

Next, install the required dependencies. We need the official Anthropic MCP SDK and the SQLite driver:

`bash npm install @modelcontextprotocol/sdk sqlite3 npm install --save-dev typescript @types/node @types/sqlite3 tsx `

Initialise your TypeScript configuration:

`bash npx tsc --init `

Open tsconfig.json and ensure your target is set to ES2022 and module resolution is set to NodeNext to support modern ES imports:

`json { "compilerOptions": { "target": "es2022", "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "strict": true, "outDir": "./dist" } } `

Now, add a quick test SQLite database to work with. Create a file named setup_db.js and run it to spin up a basic database filled with fictional product inventory:

`javascript import sqlite3 from 'sqlite3'; const db = new sqlite3.Database('inventory.db');

db.serialize(() => { db.run("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, stock INTEGER, price REAL)"); const stmt = db.prepare("INSERT INTO products (name, stock, price) VALUES (?, ?, ?)"); stmt.run("Vintage Mechanical Keyboard", 14, 120.00); stmt.run("Ergonomic Split Mouse", 45, 89.99); stmt.run("4K Ultra-Wide Monitor", 8, 450.00); stmt.finalize(); }); db.close(); `

Run node setup_db.js to generate your inventory.db file.

Step 2: Write the MCP Server

Now we will build the core MCP server in src/index.ts. We need to register two essential tools that Claude can call: 1. get_db_schema: Returns the schema of our SQLite tables so Claude knows what queries are valid. 2. run_read_query: Runs a SELECT query and returns the rows.

Create src/index.ts and drop in the following code:

`typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import sqlite3 from "sqlite3"; import { open } from "sqlite"; import path from "path";

// Open our SQLite database in read-only mode for safety const dbPath = path.resolve(process.cwd(), "inventory.db"); const dbPromise = open({ filename: dbPath, driver: sqlite3.Database, mode: sqlite3.OPEN_READONLY });

const server = new Server( { name: "sqlite-mcp-server", version: "1.0.0", }, { capabilities: { tools: {}, }, } );

// Register tools so Claude knows what it can do server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "get_db_schema", description: "Retrieve the database schema, including table names and columns.", inputSchema: { type: "object", properties: {}, }, }, { name: "run_read_query", description: "Run a safe read-only SQL SELECT query on the database.", inputSchema: { type: "object", properties: { sql: { type: "string", description: "The SELECT query to run." }, }, required: ["sql"], }, }, ], }; });

// Handle execution requests from Claude server.setRequestHandler(CallToolRequestSchema, async (request) => { const db = await dbPromise; const { name, arguments: args } = request.params;

if (name === "get_db_schema") { const tables = await db.all( "SELECT name, sql FROM sqlite_master WHERE type='table'" ); return { content: [{ type: "text", text: JSON.stringify(tables, null, 2) }], }; }

if (name === "run_read_query") { const sql = args?.sql as string; // Crude but essential security check if (!sql.toLowerCase().trim().startsWith("select")) { return { content: [ { type: "text", text: "Error: Only read-only SELECT queries are allowed.", }, ], isError: true, }; }

try { const rows = await db.all(sql); return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }], }; } catch (err: any) { return { content: [{ type: "text", text: Database error: ${err.message} }], isError: true, }; } }

throw new Error(Unknown tool: ${name}); });

// Connect the server to stdio transport const transport = new StdioServerTransport(); await server.connect(transport); console.error("SQLite MCP server running on stdio"); `

Step 3: Register the Server with Claude Desktop

Claude Desktop loads local MCP servers by parsing a configuration file. To register our server, we need to modify our local claude_desktop_config.json file.

Depending on your operating system, this file is located at: - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json - Windows: %APPDATA%\Claude\claude_desktop_config.json

Open that file (create it if it does not exist) and add your server configuration. Make sure to replace the paths with the absolute paths of your actual setup:

`json { "mcpServers": { "local-sqlite": { "command": "npx", "args": [ "tsx", "/absolute/path/to/claude-sqlite-mcp/src/index.ts" ], "cwd": "/absolute/path/to/claude-sqlite-mcp" } } } `

Tip: Always use absolute paths for both the executable command and the working directory (cwd). Claude runs this in its own system sandbox, and relative paths will break quietly.

Step 4: Test Your New Database Ally

Restart Claude Desktop. If the configuration is correct, you should see a small hammer icon in the bottom right corner of your input box, indicating that Claude has discovered your local MCP server.

Now, test Claude's reasoning capabilities by running a query that forces it to use both of your tools sequentially:

> "Check the database schema to see what products we have, then find the average price of our products that have fewer than 15 items in stock."

Watch the Claude UI carefully. You will see Claude execute two sequential steps: 1. It will call get_db_schema to learn the layout of the products table. 2. It will generate and run a target SQL query (SELECT AVG(price) FROM products WHERE stock < 15;) using run_read_query. 3. It will return the correct mathematical average directly to your chat interface.

Best Practices & Security

While running things locally is inherently safer than exposing open endpoints to the public web, you are still giving an agent the ability to execute code against your local database.

  1. Enforce Read-Only Mode: Ensure your SQL connection is strictly read-only. In SQLite, passing sqlite3.OPEN_READONLY prevents Claude from dropping tables if it misunderstands your prompt.
  2. Sanitise Inputs: Even local scripts should be protected against basic injection errors. Keep query validation simple and robust.
  3. Isolate Your Directories: Do not run your MCP servers with global permissions that allow Claude to traverse directories outside of your immediate database folder.

If you run into issues with Claude failing to run your script, or if the connection drops silently, head over to our Claude platform hub on /platforms/claude/articles to troubleshoot local environment setups, paths, and Node.js permissions.

claudemcpnodejssqlitetutorials

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.