Tutorials

How to Configure Model Context Protocol Servers

A technical walkthrough on building and securing custom Model Context Protocol servers for local development workflows.

AM
Alfian Majid
//9 min read
How to Configure Model Context Protocol Servers

Model Context Protocol has fundamentally shifted how we wire external tools into local language models. Instead of writing custom API wrappers for every new utility, Anthropic's open standard provides a clean, JSON-RPC-based transport layer that lets Claude Code, Cursor Agent, and local chat clients talk directly to your filesystem, databases, and custom scripts. If you are tired of copy-pasting terminal output into chat windows, building your own MCP server is the single best workflow upgrade you can make this week.

Understanding the MCP Architecture and Transport Layer

Before writing any code, you need to understand how the client and server communicate. MCP uses a client-server architecture where the host application (like Claude Code or a compatible IDE) acts as the client. Your script acts as the server, communicating over standard input and standard output (stdio) or Server-Sent Events (SSE). For local development, stdio transport is the default choice because it avoids network port conflicts and handles process lifecycle management automatically.

When you invoke a prompt or tool in your editor, the client serializes a JSON-RPC request and pipes it to your server process. Your server processes the payload, executes local system calls, queries a database, or reads a log file, and returns a structured JSON-RPC response. This separation means your LLM never touches your database credentials directly. Instead, your secure local server acts as an intermediary, executing queries with predefined parameters and returning only sanitized results.

To build this, we will use Python 3.12 and the official mcp package. Our end goal is a fully functional custom server that exposes a local SQLite database to your AI coding assistant, allowing it to inspect table schemas, run read-only queries, and analyze production performance metrics without leaving your editor interface.

Setting Up Your Local Development Environment

Let us set up the environment. You will need Python 3.12 or higher installed on your machine. I run this on macOS Sonoma and Ubuntu 24.04 LTS without issues, but Windows users running via WSL2 will also find this workflow clean. Open your terminal and create a dedicated directory for your MCP project.

mkdir mcp-sqlite-server
cd mcp-sqlite-server
python3.12 -m venv venv
source venv/bin/activate
pip install mcp sqlite-utils

Verify your installation by running pip list. You should see mcp version 1.0 or higher along with its async dependencies like pydantic and anyio. Next, create a sample SQLite database containing a few records so our server has something to inspect. Run the following inline Python script to generate a test database file named app.db in your project root.

python3 -c "
import sqlite3
conn = sqlite3.connect('app.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
cursor.execute('INSERT OR IGNORE INTO users VALUES (1, 'Alice Smith', '[email protected]')')
cursor.execute('INSERT OR IGNORE INTO users VALUES (2, 'Bob Jones', '[email protected]')')
conn.commit()
conn.close()
"

With your virtual environment active and your test database populated, you are ready to write the server implementation. Keep your terminal open as we will test the server lifecycle directly using stdio streams.

Writing the Custom Server Implementation

Create a file named server.py in your project directory. We will use the high-level FastMCP interface provided by the SDK, which abstracts away the raw JSON-RPC boilerplate and lets you define tools using simple Python type hints and docstrings. The LLM reads these docstrings to understand when and how to call your tools.

from mcp.server.fastmcp import FastMCP
import sqlite3
import json

# Initialize FastMCP server instance
mcp = FastMCP('SQLite Inspector')

DB_PATH = 'app.db'

def get_connection():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

@mcp.tool()
def list_tables() -> str:
    """List all tables present in the SQLite database."""
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = [row['name'] for row in cursor.fetchall()]
    conn.close()
    return json.dumps(tables)

@mcp.tool()
def run_query(query: str) -> str:
    """Execute a read-only SQL query on the database and return results as JSON."""
    if not query.strip().lower().startswith('select'):
        return json.dumps({'error': 'Only SELECT statements are permitted for safety.'})
    
    try:
        conn = get_connection()
        cursor = conn.cursor()
        cursor.execute(query)
        rows = [dict(row) for row in cursor.fetchall()]
        conn.close()
        return json.dumps(rows)
    except Exception as e:
        return json.dumps({'error': str(e)})

if __name__ == '__main__':
    mcp.run()

Notice how clean this is. The @mcp.tool() decorator automatically registers our Python functions as executable tools. The docstrings act as the system prompt descriptions for the AI model. If you write vague docstrings, your AI assistant will misuse your tools. Be explicit about parameters and expected outputs.

Connecting Your Server to Claude Code and Desktop Clients

Now that your server code is written, you need to configure your local AI client to spawn this process. For Claude Code and Claude Desktop, configuration happens inside a JSON file located at ~/Library/Application Support/Claude/claude_desktop_config.json on macOS or %APPDATA%\Claude\claude_desktop_config.json on Windows.

Open or create this configuration file and add your server under the mcpServers key. You must provide the absolute path to the Python executable inside your virtual environment so dependencies resolve correctly.

{
  "mcpServers": {
    "sqlite-inspector": {
      "command": "/Users/yourusername/mcp-sqlite-server/venv/bin/python",
      "args": [
        "/Users/yourusername/mcp-sqlite-server/server.py"
      ]
    }
  }
}

Save the configuration file and completely restart your Claude Desktop application or restart your terminal session running Claude Code. When the application boots, it reads this configuration, spawns your Python script as a background child process, and establishes the stdio pipe.

To verify the integration is active, open Claude Desktop and look for the plug icon or tool indicator in the prompt input area. You should see sqlite-inspector listed among the available toolsets. Try asking Claude: What tables are in my local database? Claude will inspect the available tools, select list_tables, execute it against your background process, and return the list of tables without you ever writing a SQL command manually.

How to Diagnose and Fix Common MCP Errors

Building local server processes means dealing with process lifecycles, path mismatches, and JSON serialization snags. When things break, they rarely fail gracefully with a friendly UI popup. Here are the three most common failure modes you will encounter and how to fix them from the terminal.

Error 1: Server Process Exits Immediately with Exit Code 1
This usually happens because your Python path in the configuration file is incorrect, or a required dependency is missing from the virtual environment. To diagnose this, run your server script directly from the terminal using the exact path specified in your config:

/Users/yourusername/mcp-sqlite-server/venv/bin/python /Users/yourusername/mcp-sqlite-server/server.py

If there is an import error or syntax issue, it will print immediately to your terminal rather than failing silently inside the client application.

Error 2: Tool Execution Timeout or No Response
If Claude invokes your tool and hangs indefinitely, your server is likely waiting for user input or printing debug statements directly to stdout. Because MCP uses stdout for JSON-RPC message framing, printing standard log statements with print() corrupts the transport stream. Remove all raw print() statements from your code and use standard logging configured to write to a separate log file instead.

Error 3: Pydantic Validation Error on Tool Arguments
If your AI client attempts to pass arguments that do not match your function type hints, FastMCP rejects the payload with a validation error. Ensure your type hints are strict. For example, if your function expects an integer ID, type hint it as user_id: int rather than leaving it untyped. If you allow raw strings, the model may pass malformed queries that crash your database connector.

Securing Your Local MCP Server for Production Workflows

Running local MCP servers gives you immense power, but it also opens up security attack surfaces if you are not careful. Because your AI assistant can execute code and query databases on your behalf, a prompt injection attack from a malicious website or untrusted README file could trick your assistant into running destructive database queries.

Always enforce strict guardrails inside your tool definitions. As shown in our run_query implementation, we explicitly checked that the query string begins with SELECT and blocked any statements containing DROP, DELETE, UPDATE, or ALTER. Never expose raw database admin credentials to an MCP server unless absolutely necessary. Scope database users to read-only permissions at the database engine level, rather than relying solely on application-level checks.

On top of that, be mindful of sensitive data leakage. If your MCP server reads local log files or configuration directories containing API keys, your AI assistant may inadvertently transmit those secrets to remote model providers during normal conversation context updates. Filter out sensitive environment variables and redact API tokens before returning string payloads from your custom tools.

What to Build Next in Your MCP Journey

Once you have mastered local database inspection, you can expand your MCP setup to handle much more complex developer workflows. Consider building a Git repository analyzer server that lets your AI assistant inspect uncommitted git diffs, run local test suites via subprocess, and report failing test outcomes directly into your chat buffer.

Another powerful pattern is building a browser automation server using Playwright that lets your assistant take screenshots of local web applications during frontend development. The Model Context Protocol turns your local machine into a modular toolkit. Start small with single-purpose servers, test your stdio streams thoroughly, and build out your custom automation stack piece by piece.

Bottom Line

Model Context Protocol is no longer an experimental toy. It is the definitive standard for connecting local developer environments to modern AI assistants. Stop wasting time copy-pasting terminal output and build a custom server this afternoon. Define your tools with strict type hints, secure your stdio transport, and let your AI work directly where your code lives.

Share this article

Alfian Majid
Alfian Majid/Founder & Editor-in-Chief

Solo developer and blogger from Indonesia. Runs CogitoDaily as a passion project - covering AI news, testing tools, and writing guides. Background in web development and game tech. When not writing about AI, you'll find me deep in anime or gaming.