Model Context Protocol (MCP) for Developers / Start Here

Set up the course environment

Lesson 2 of 29. Open to read. No account needed.

What You Will Build

By the end of this lesson your computer has the one folder the course uses, a Python environment inside it with the MCP Python SDK and pytest at the versions every lesson was tested against, and the generated parts database. A check script confirms all of it in one run, and you will have seen the four ways installation most often goes wrong, with the message each one prints, so that you recognise them later.

The exercise is in three parts: a readiness check that uses only the Python you already have, the environment itself, and the check script and database. Installation is the only step in the course that needs the network.

The Bridge: the Terminal

The course assumes you can open a terminal and run commands; here are the few it relies on, so that nothing later is a surprise.

NeedmacOS and LinuxWindows PowerShell
Where am I?pwdpwd
What is here?lsls
Go into a foldercd foldercd folder
Make a foldermkdir -p foldermkdir folder
Your home folder~$HOME
Set a variable for this terminal onlyexport NAME=value$env:NAME = "value"
Stop a running programCtrl+CCtrl+C

A second terminal window or tab is a separate program with its own current folder and its own variables: activating the environment in one does not activate it in the other. That matters in the independent task.

Which Python

The course supports Python 3.12 to 3.15. The SDK's own metadata accepts 3.10 or later and its documentation says 3.11 or later (S01, S04), and one of its dependencies, the HTTP library httpx2, requires 3.11 (S79). The course starts at 3.12 because 3.11 now receives security fixes only (S80). 3.15 was released on 2026-10-09; the lessons were tested on 3.13 and the mechanisms were checked on 3.12 and 3.14, as the course records state. Check what you have. macOS and Linux:

python3 --version

Windows PowerShell:

py -3 --version

If the version is below 3.12, install a current Python from python.org or your package manager before continuing; the lesson's "When It Goes Wrong" table shows what an unsupported version produces if you try anyway.

Exercise: the Course Environment

Goal: create ~/mcp-practice with the course environment and the practice database, and prove it with the check script.

Starting state: a supported Python installed and a terminal open. No ~/mcp-practice folder exists yet.

Effects: creates ~/mcp-practice/ with .venv (about 70 MB of packages), data/inventory.db (a few hundred kilobytes) and the exercise folder course-environment. Installation downloads from the Python Package Index; nothing else leaves your machine.

Time: installation took between 62 and 498 seconds on the authoring machine depending on download speed; every other step takes seconds.

Part 1: readiness check

This part uses the Python you already have and checks the two abilities the course assumes: writing a function over a list of dictionaries, and reading a traceback.

  1. Create the folders. macOS and Linux:

    mkdir -p ~/mcp-practice/course-environment
    cd ~/mcp-practice/course-environment
    

    Windows PowerShell:

    mkdir $HOME\mcp-practice\course-environment
    cd $HOME\mcp-practice\course-environment
    
  2. Save this as readiness.py:

    """Readiness check: total the quantities in a list of dictionaries."""
    PARTS = [
        {"sku": "bolt-m4", "quantity": 120},
        {"sku": "nut-m4", "quantity": 80},
        {"sku": "washer-m4", "quantity": 0},
    ]
    
    
    def total_quantity(parts):
        total = 0
        for part in parts:
            total += part["quantitiy"]
        return total
    
    
    print("total:", total_quantity(PARTS))
    
  3. Run it with the Python you checked above (python3 on macOS and Linux, py -3 on Windows). It fails on purpose:

    python3 readiness.py
    

    Output (illustrative; the path is yours):

    Traceback (most recent call last):
      File "/Users/sam/mcp-practice/course-environment/readiness.py", line 15, in <module>
        print("total:", total_quantity(PARTS))
                        ~~~~~~~~~~~~~~^^^^^^^
      File "/Users/sam/mcp-practice/course-environment/readiness.py", line 12, in total_quantity
        total += part["quantitiy"]
                 ~~~~^^^^^^^^^^^^^
    KeyError: 'quantitiy'
    
  4. Read the traceback from the bottom: the error is a KeyError for the key 'quantitiy', raised at line 12 inside total_quantity, which was called from line 15. The dictionaries have a quantity key; the function asks for a misspelt one. Fix the spelling in your editor and rerun:

    total: 200
    

If reading the traceback or fixing the function was hard, work through an introductory Python course before continuing: every later lesson relies on both.

Part 2: the environment

A virtual environment is a folder holding its own Python interpreter and its own installed packages, separate from everything else on the machine (S89). Activating it makes python and pip in that terminal mean the ones inside it, so the course's versions cannot collide with other projects, and removing the course later is deleting one folder.

  1. Create it. macOS and Linux:

    python3 -m venv ~/mcp-practice/.venv
    source ~/mcp-practice/.venv/bin/activate
    

    Windows PowerShell:

    py -3 -m venv $HOME\mcp-practice\.venv
    & $HOME\mcp-practice\.venv\Scripts\Activate.ps1
    

    The prompt gains a (.venv) prefix. If PowerShell refuses to run the activation script, allow local scripts for your user once, then activate again (S89):

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    
  2. Install the two pinned libraries. The same command on every platform (the quotes keep the shell from reading the square brackets):

    python -m pip install "mcp[cli]==2.3.0" pytest==9.1.1
    

    mcp is the MCP Python SDK, released on 2026-10-02 as the latest 2.x (S01); the cli extra adds the mcp command. pytest is the test runner the testing lesson uses (S77). Pinning both to exact versions means your output matches the lessons; pip resolves 40 packages in all. The last lines (illustrative; the list and wrapping vary) end with:

    Successfully installed ... mcp-2.3.0 mcp-types-2.3.0 ... pydantic-2.14.1 ... pytest-9.1.1 ...
    
  3. Confirm that nothing conflicts:

    python -m pip check
    
    No broken requirements found.
    

Part 3: the check script and the database

  1. Save this as check_setup.py:

    """Check the course environment: interpreter, versions, protocol constant and practice folders."""
    import sqlite3
    import sys
    from importlib.metadata import version
    from pathlib import Path
    
    import mcp.types
    
    PRACTICE = Path.home() / "mcp-practice"
    problems = []
    
    print("interpreter:", sys.executable)
    print("python:", sys.version.split()[0])
    if Path(sys.prefix).resolve() == (PRACTICE / ".venv").resolve():
        print("environment: the course environment (~/mcp-practice/.venv)")
    else:
        problems.append("not running inside ~/mcp-practice/.venv; activate it or use its python")
        print("environment: NOT the course environment")
    for name in ("mcp", "mcp-types", "pydantic", "httpx2", "pytest"):
        print(f"{name}: {version(name)}")
    print("protocol:", mcp.types.LATEST_PROTOCOL_VERSION)
    
    db = PRACTICE / "data" / "inventory.db"
    if db.exists():
        conn = sqlite3.connect(db)
        counts = [conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] for table in ("bins", "parts", "movements")]
        conn.close()
        print(f"data/inventory.db: {counts[0]} bins, {counts[1]} parts, {counts[2]} movements")
    else:
        problems.append("data/inventory.db is missing; run make_inventory.py")
        print("data/inventory.db: missing")
    
    print("practice folder:", PRACTICE)
    for entry in sorted(PRACTICE.iterdir()) if PRACTICE.exists() else []:
        print("  ", entry.name + ("/" if entry.is_dir() else ""))
    
    if problems:
        print("PROBLEMS:", *problems, sep="\n  ")
        sys.exit(1)
    print("setup check passed")
    
  2. Run it. It is expected to fail at this point, because the database does not exist yet:

    python check_setup.py
    

    Output (illustrative; the interpreter path is yours):

    interpreter: /Users/sam/mcp-practice/.venv/bin/python
    python: 3.13.0
    environment: the course environment (~/mcp-practice/.venv)
    mcp: 2.3.0
    mcp-types: 2.3.0
    pydantic: 2.14.1
    httpx2: 2.16.0
    pytest: 9.1.1
    protocol: 2026-07-28
    data/inventory.db: missing
    practice folder: /Users/sam/mcp-practice
       .venv/
       course-environment/
    PROBLEMS:
      data/inventory.db is missing; run make_inventory.py
    
  3. Create the shared data folder and save this as make_inventory.py:

    """Generate the course's workshop parts inventory database.
    
    Standard library only and deterministic: the same file every time.
    
        python make_inventory.py ~/mcp-practice/data/inventory.db
    """
    from __future__ import annotations
    
    import random
    import sqlite3
    import sys
    from datetime import datetime, timedelta, timezone
    
    BINS = [("A1", "Rack A, shelf 1"), ("A2", "Rack A, shelf 2"), ("B1", "Rack B, shelf 1"), ("B2", "Rack B, shelf 2"), ("C1", "Cabinet C, drawer 1"), ("C2", "Cabinet C, drawer 2")]
    FAMILIES = [("bolt", "Hex bolt", "each"), ("nut", "Hex nut", "each"), ("washer", "Flat washer", "each"), ("bearing", "Ball bearing", "each"), ("belt", "Drive belt", "each"), ("filter", "Oil filter", "each"), ("cable", "Control cable", "metre"), ("fuse", "Blade fuse", "each")]
    SIZES = ["m4", "m5", "m6", "m8", "m10"]
    
    
    def build(path: str) -> dict[str, int]:
        rng = random.Random(7)
        conn = sqlite3.connect(path)
        conn.executescript(
            "DROP TABLE IF EXISTS movements; DROP TABLE IF EXISTS parts; DROP TABLE IF EXISTS bins;"
            "CREATE TABLE bins(id TEXT PRIMARY KEY, location TEXT NOT NULL);"
            "CREATE TABLE parts(sku TEXT PRIMARY KEY, name TEXT NOT NULL, bin_id TEXT NOT NULL REFERENCES bins(id), quantity INTEGER NOT NULL CHECK(quantity >= 0), reorder_level INTEGER NOT NULL, unit TEXT NOT NULL);"
            "CREATE TABLE movements(id INTEGER PRIMARY KEY AUTOINCREMENT, sku TEXT NOT NULL REFERENCES parts(sku), delta INTEGER NOT NULL, reason TEXT NOT NULL, at TEXT NOT NULL);"
        )
        conn.executemany("INSERT INTO bins VALUES (?, ?)", BINS)
        parts = []
        for family, label, unit in FAMILIES:
            for size in SIZES:
                sku = f"{family}-{size}"
                quantity = 0 if rng.random() < 0.1 else rng.randint(1, 150)
                parts.append((sku, f"{label} {size.upper()}", rng.choice(BINS)[0], quantity, rng.choice([10, 20, 25, 40]), unit))
        conn.executemany("INSERT INTO parts VALUES (?, ?, ?, ?, ?, ?)", parts)
        start = datetime(2026, 9, 1, 9, 0, tzinfo=timezone.utc)
        movements = []
        for i in range(120):
            sku = rng.choice(parts)[0]
            delta = rng.choice([-5, -3, -2, -1, 1, 2, 5, 10, 20])
            movements.append((sku, delta, "issued" if delta < 0 else "received", (start + timedelta(hours=6 * i)).isoformat()))
        conn.executemany("INSERT INTO movements(sku, delta, reason, at) VALUES (?, ?, ?, ?)", movements)
        conn.commit()
        counts = {t: conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] for t in ("bins", "parts", "movements")}
        counts["below_reorder"] = conn.execute("SELECT COUNT(*) FROM parts WHERE quantity < reorder_level").fetchone()[0]
        counts["zero_stock"] = conn.execute("SELECT COUNT(*) FROM parts WHERE quantity = 0").fetchone()[0]
        conn.close()
        return counts
    
    
    if __name__ == "__main__":
        out = sys.argv[1] if len(sys.argv) > 1 else "inventory.db"
        counts = build(out)
        print(f"wrote {out}: {counts['bins']} bins, {counts['parts']} parts, {counts['movements']} movements "
              f"({counts['zero_stock']} parts at zero stock, {counts['below_reorder']} below their reorder level)")
    
  4. Generate the database. macOS and Linux:

    mkdir -p ~/mcp-practice/data
    python make_inventory.py ~/mcp-practice/data/inventory.db
    

    Windows PowerShell:

    mkdir $HOME\mcp-practice\data
    python make_inventory.py $HOME\mcp-practice\data\inventory.db
    

    Output (the path is yours; the counts are fixed):

    wrote /Users/sam/mcp-practice/data/inventory.db: 6 bins, 40 parts, 120 movements (9 parts at zero stock, 15 below their reorder level)
    
  5. Run the check again, and the SDK's own command:

    python check_setup.py
    mcp version
    
    interpreter: /Users/sam/mcp-practice/.venv/bin/python
    python: 3.13.0
    environment: the course environment (~/mcp-practice/.venv)
    mcp: 2.3.0
    mcp-types: 2.3.0
    pydantic: 2.14.1
    httpx2: 2.16.0
    pytest: 9.1.1
    protocol: 2026-07-28
    data/inventory.db: 6 bins, 40 parts, 120 movements
    practice folder: /Users/sam/mcp-practice
       .venv/
       course-environment/
       data/
    setup check passed
    MCP version 2.3.0
    

Success: the check prints a Python version from 3.12 to 3.15, the five library versions shown, protocol: 2026-07-28, the database counts and setup check passed; pip check found nothing broken; the generator printed 6 bins, 40 parts and 120 movements. The interpreter path and the home folder differ from the output above.

What Each Check Line Proves

The diagram follows the script's lines in order.

A flow of the setup steps and the check lines that prove each one: create the environment, proving interpreter path inside .venv; install the pins, proving mcp 2.3.0, mcp-types 2.3.0, pydantic 2.14.1, httpx2 2.16.0 and pytest 9.1.1; the SDK's constant, proving protocol 2026-07-28; generate the database, proving 6 bins, 40 parts and 120 movements; and the final line setup check passed.

Each line of the check script answers one question about the environment.

  • interpreter is sys.executable, the Python running the script. The next line compares sys.prefix, the root of the running installation, with ~/mcp-practice/.venv; when they match, the environment is active and python means the course's interpreter. Any other path means the terminal is using a different Python, the most common cause of "it worked yesterday".
  • The five versions come from the installed package metadata through importlib.metadata.version. mcp-types holds the protocol's message types and is versioned with the SDK; pydantic validates every message and derives tool schemas; httpx2 is the HTTP client the later transport lessons use. The exact pins are what the lessons' outputs were captured with.
  • protocol prints mcp.types.LATEST_PROTOCOL_VERSION, the specification revision the SDK speaks by default. The next lessons explain what that date means on the wire.
  • data/inventory.db opens the generated SQLite database with the standard library's sqlite3 module (S91) and counts the rows in its three tables. The generator is deterministic: the same seed, the same 40 parts, the same movements, so your data matches the lessons' outputs exactly.
  • practice folder lists what is under ~/mcp-practice so you can see the layout the first lesson described.

The generator itself is worth a glance now and a closer read in the lifespan lesson, which queries its tables: bins has six locations; parts has one row per part code (family-size, such as bolt-m4) with its bin, quantity, reorder level and unit; movements has 120 dated receipts and issues. Running it again rewrites the file identically.

When It Goes Wrong

Four failures account for most setup problems. The first and third messages are recorded from this environment; the second and fourth are illustrative because they depend on your machine.

SymptomCauseFix
ModuleNotFoundError: No module named 'mcp' and the check script's first line shows a path outside ~/mcp-practice/.venv (or environment: NOT the course environment)The terminal is using another Python: the environment is not activated in this terminal, or python3 was typed instead of python after activationActivate in this terminal, then use python
During installation, pip reports that no version of httpx2 satisfies the requirement and names the versions it ignored because they require a different Python versionPython 3.10 or older: httpx2 2.16.0 declares that it needs 3.11 or later (S79), and the course needs 3.12Install Python 3.12 to 3.15 and create the environment again with it
ModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed; see the migration guide at https://py.sdk.modelcontextprotocol.io/v2/migration/#fastmcp-renamed-to-mcpserver or pin 'mcp<2' to keep running v1 code.Code written for the 1.x SDK, which most older tutorials show. Version 2.0.0 (2026-07-28) renamed the server class and changed the client (S03, S32)Use the 2.x names the course teaches: from mcp.server import MCPServer
OSError: [Errno 48] Address already in use (macOS; Linux reports [Errno 98], Windows [WinError 10048]) when a later lesson starts an HTTP serverAnother process, often a server from an earlier run, still holds the portPress Ctrl+C in the terminal that is still running it; if none is, find the process with lsof -i :8000 (macOS, Linux) or Get-NetTCPConnection -LocalPort 8000 (Windows) and stop it

The SDK is a 2.x release, and much of what you will find online, including some of the project's own older pages, still shows FastMCP. The error message itself gives the mapping, and the course never uses the old names.

Your Turn: Prove the Environment Is per Terminal

  1. Open a second terminal window. Do not activate anything in it. Run the import that the check script starts with:

    python3 -c "import mcp"
    

    (py -3 -c "import mcp" on Windows.) Predict the result, then run it.

  2. In that same terminal, activate the environment and show where the package comes from:

    source ~/mcp-practice/.venv/bin/activate
    python -c "import mcp; print(mcp.__file__)"
    

    (& $HOME\mcp-practice\.venv\Scripts\Activate.ps1 on Windows.)

  3. Close the second terminal. Then, from the table above, match each of these four outputs to its cause without looking back: (a) the check script's interpreter line ends in /usr/bin/python3; (b) pip stops with a message about httpx2 and Python versions; (c) a script fails on from mcp.server.fastmcp import FastMCP; (d) a server exits with Address already in use.

Reset and Clean Up

Running the generator again rewrites the same database, and running the check again changes nothing, so both can be repeated freely. Keep .venv and data: every lesson uses them. Remove only this lesson's folder, after looking at what is there. macOS and Linux:

cd ~/mcp-practice
ls
rm -r course-environment
ls

Windows PowerShell:

cd $HOME\mcp-practice
ls
Remove-Item -Recurse course-environment
ls

Two entries remain: .venv and data. To rebuild the environment from scratch at any time, remove .venv and repeat Part 2.

Check Your Understanding

  1. After activation, python check_setup.py prints a path under ~/mcp-practice/.venv, but python3 check_setup.py in the same terminal fails with No module named 'mcp'. Why can both be true?
  2. Why does the course pin mcp to exactly 2.3.0 rather than installing the latest version?
  3. The generator's docstring says "deterministic". What would change in the lessons if it were not?

Answer and Reasoning

Your turn

  1. The import fails with ModuleNotFoundError: No module named 'mcp': the second terminal runs the system Python, which has no course packages. Activation changed only the first terminal.
  2. After activation the import succeeds and prints a path under ~/mcp-practice/.venv/ (on this machine .../.venv/lib/python3.13/site-packages/mcp/__init__.py; the Python version in the path is yours). The package comes from the environment.
  3. (a) wrong interpreter: the environment is not active in that terminal; (b) unsupported Python: httpx2 needs 3.11 or later and the course 3.12; (c) 1.x code on the 2.x SDK: use MCPServer from mcp.server; (d) a port still held by a process, usually a server from an earlier run.

Understanding check

  1. Activation puts the environment's folder first on the terminal's search path under the name python (and python3 as well on macOS and Linux, but not always on every setup), and python3 may still resolve to the system interpreter depending on how it was installed. The reliable rule is to use python after activation and to read the interpreter line of the check script when in doubt.
  2. Every output in the course was captured with 2.3.0, and the SDK's 2.x line changed names and behaviour from 1.x within months; a newer version could print different schemas, messages or defaults, and the lessons would no longer match. Pinning makes the course reproducible; a project of your own would choose its own range.
  3. The lessons print exact counts, part codes and quantities from the database (belt-m6: 7, 15 below their reorder level). With random data, no lesson could show expected output, and the exercise tests could not assert anything about it.

References

24 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy