AI Engineering: Agents and Applications › The Model Context Protocol › Day 298

Hands-on lab — Day 298: MCP Resources and Prompts

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/mcp_resources_prompts.py

Test

bash tests/run_tests.sh

File tree

examples/mcp_resources_prompts.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/mcp_resources_prompts.py
tests/run_tests.sh
tests/test_mcp_resources_prompts.py
troubleshooting.md

Lab README

Day 298 Lab: MCP Resources and Prompts

Lesson

  • Lesson title: MCP Resources and Prompts
  • Day number: 298 of 365
  • Lesson article: https://ai-roadmap-365.github.io/day-298-mcp-resources-and-prompts
  • Lab files: everything you need is in this directory — follow “How to run” below.
  • Browse the course locally: from the repository root, this lab also appears in the course website at /labs/day-298-mcp-resources-and-prompts when the site is running.

Purpose

Construct an MCP server subsystem in Python managing URI-addressable Resources with MIME types, live change notifications, and parameterized Prompt Templates.

Learning objectives

  • Architect URI-addressable MCP Resources using standard scheme conventions.
  • Implement MIME-type negotiation and payload streaming.
  • Design dynamic resource change notifications.
  • Create parameterized Prompt Templates returning multi-role message arrays.

Prerequisites

  • Python 3.10+ installed
  • pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, pytest

Free and open-source options

  • Python Standard Library, Pytest

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/mcp_resources_prompts.py: Starter implementation skeleton
  • examples/mcp_resources_prompts.py: Verified reference implementation
  • tests/test_mcp_resources_prompts.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/mcp_resources_prompts.py

What the commands do

  • Registers resources and prompts and evaluates reading, subscription, and template generation.

Expected output

Resources: {'resources': [{'uri': 'memo://active', 'name': 'Active Note', 'mimeType': 'text/plain'}]}
Prompts: {'prompts': [{'name': 'summarize', 'description': 'Summarize a document', 'arguments': [{'name': 'doc', 'required': True}]}]}

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • resources/list catalog output
  • resources/read payload retrieval and MIME typing
  • URI not found error handling
  • prompts/list discovery output
  • prompts/get parameter interpolation and message array formatting

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Verify resource URIs follow valid RFC 3986 format.

Security notes

Runs completely offline on local CPU.

Extension exercises

Implement dynamic URI pattern matching for templated resources.

Day number: 298 of 365

Expected output

FIELDS.md

# Measured Values
- `resources_count`: 1
- `prompts_count`: 1

examples-run.txt

Resources: {'resources': [{'uri': 'memo://active', 'name': 'Active Note', 'mimeType': 'text/plain'}]}
Prompts: {'prompts': [{'name': 'summarize', 'description': 'Summarize a document', 'arguments': [{'name': 'doc', 'required': True}]}]}

measured-values.txt

resources_count=1
prompts_count=1

run-output.txt

Resources: {'resources': [{'uri': 'memo://active', 'name': 'Active Note', 'mimeType': 'text/plain'}]}
Prompts: {'prompts': [{'name': 'summarize', 'description': 'Summarize a document', 'arguments': [{'name': 'doc', 'required': True}]}]}

starter-run.txt

An untouched starter fails the suite. Captured from a real run:


self = <examples.mcp_resources_prompts.MCPResourcePromptEngine object at 0x108ea2650>
method = 'invalid/method', params = None

    def handle_request(self, method: str, params: Optional[Dict[str, Any]]=None) -> Dict[str, Any]:
>       raise NotImplementedError('TASK 3: implement handle_request.')
E       NotImplementedError: TASK 3: implement handle_request.

examples/mcp_resources_prompts.py:24: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_mcp_resources_prompts.py::test_resources_list_and_read - No...
FAILED tests/test_mcp_resources_prompts.py::test_resource_not_found - NotImpl...
FAILED tests/test_mcp_resources_prompts.py::test_prompts_list_and_get - NotIm...
FAILED tests/test_mcp_resources_prompts.py::test_prompt_not_found - NotImplem...
FAILED tests/test_mcp_resources_prompts.py::test_unsupported_method - NotImpl...
============================== 5 failed in 0.04s ===============================

Implement each TASK in starter/, copy it over examples/, and the same
suite goes green.

test-output.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-298-mcp-resources-and-prompts
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_mcp_resources_prompts.py::test_resources_list_and_read PASSED [ 20%]
tests/test_mcp_resources_prompts.py::test_resource_not_found PASSED      [ 40%]
tests/test_mcp_resources_prompts.py::test_prompts_list_and_get PASSED    [ 60%]
tests/test_mcp_resources_prompts.py::test_prompt_not_found PASSED        [ 80%]
tests/test_mcp_resources_prompts.py::test_unsupported_method PASSED      [100%]

============================== 5 passed in 0.01s ===============================

test-run.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-298-mcp-resources-and-prompts
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_mcp_resources_prompts.py::test_resources_list_and_read PASSED [ 20%]
tests/test_mcp_resources_prompts.py::test_resource_not_found PASSED      [ 40%]
tests/test_mcp_resources_prompts.py::test_prompts_list_and_get PASSED    [ 60%]
tests/test_mcp_resources_prompts.py::test_prompt_not_found PASSED        [ 80%]
tests/test_mcp_resources_prompts.py::test_unsupported_method PASSED      [100%]

============================== 5 passed in 0.01s ===============================

Source files

examples/mcp_resources_prompts.py (3054 bytes)
from typing import Dict, Any, List, Optional, Callable

class MCPResourcePromptEngine:
    def __init__(self, server_name: str = "doc-server"):
        self.server_name = server_name
        self.resources: Dict[str, Dict[str, Any]] = {}
        self.prompts: Dict[str, Dict[str, Any]] = {}
        
    def register_resource(self, uri: str, name: str, mime_type: str, reader_fn: Callable[[], str]):
        self.resources[uri] = {
            "uri": uri,
            "name": name,
            "mimeType": mime_type,
            "reader": reader_fn
        }
        
    def register_prompt(self, name: str, description: str, arguments: List[Dict[str, Any]], template_fn: Callable[..., List[Dict[str, Any]]]):
        self.prompts[name] = {
            "name": name,
            "description": description,
            "arguments": arguments,
            "template": template_fn
        }
        
    def handle_request(self, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        params = params or {}
        
        if method == "resources/list":
            res_list = [
                {"uri": r["uri"], "name": r["name"], "mimeType": r["mimeType"]}
                for r in self.resources.values()
            ]
            return {"resources": res_list}
            
        elif method == "resources/read":
            uri = params.get("uri")
            if uri not in self.resources:
                raise ValueError(f"Resource URI not found: {uri}")
            r = self.resources[uri]
            text_content = r["reader"]()
            return {
                "contents": [
                    {"uri": uri, "mimeType": r["mimeType"], "text": text_content}
                ]
            }
            
        elif method == "prompts/list":
            p_list = [
                {"name": p["name"], "description": p["description"], "arguments": p["arguments"]}
                for p in self.prompts.values()
            ]
            return {"prompts": p_list}
            
        elif method == "prompts/get":
            name = params.get("name")
            if name not in self.prompts:
                raise ValueError(f"Prompt not found: {name}")
            p = self.prompts[name]
            args = params.get("arguments", {})
            messages = p["template"](**args)
            return {
                "description": p["description"],
                "messages": messages
            }
            
        raise ValueError(f"Unsupported method: {method}")

if __name__ == "__main__":
    engine = MCPResourcePromptEngine("doc-server")
    engine.register_resource("memo://active", "Active Note", "text/plain", lambda: "Deploying model v2")
    engine.register_prompt(
        "summarize",
        "Summarize a document",
        [{"name": "doc", "required": True}],
        lambda doc: [{"role": "user", "content": {"type": "text", "text": f"Summarize: {doc}"}}]
    )
    print("Resources:", engine.handle_request("resources/list"))
    print("Prompts:", engine.handle_request("prompts/list"))
metadata.yml (408 bytes)
lesson_id: D298
day: 298
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/mcp_resources_prompts.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (14 bytes)
pytest>=7.0.0
starter/mcp_resources_prompts.py (1630 bytes)
"""STARTER -- implement each TASK below, then run the tests.

Every function that raises NotImplementedError is yours to write. The
imports, constants and data structures are given; the logic is not.
Run `bash tests/run_tests.sh` to see which tasks are still outstanding.
"""

from typing import Dict, Any, List, Optional, Callable

class MCPResourcePromptEngine:

    def __init__(self, server_name: str='doc-server'):
        self.server_name = server_name
        self.resources: Dict[str, Dict[str, Any]] = {}
        self.prompts: Dict[str, Dict[str, Any]] = {}

    def register_resource(self, uri: str, name: str, mime_type: str, reader_fn: Callable[[], str]):
        raise NotImplementedError('TASK 1: implement register_resource.')

    def register_prompt(self, name: str, description: str, arguments: List[Dict[str, Any]], template_fn: Callable[..., List[Dict[str, Any]]]):
        raise NotImplementedError('TASK 2: implement register_prompt.')

    def handle_request(self, method: str, params: Optional[Dict[str, Any]]=None) -> Dict[str, Any]:
        raise NotImplementedError('TASK 3: implement handle_request.')
if __name__ == '__main__':
    engine = MCPResourcePromptEngine('doc-server')
    engine.register_resource('memo://active', 'Active Note', 'text/plain', lambda: 'Deploying model v2')
    engine.register_prompt('summarize', 'Summarize a document', [{'name': 'doc', 'required': True}], lambda doc: [{'role': 'user', 'content': {'type': 'text', 'text': f'Summarize: {doc}'}}])
    print('Resources:', engine.handle_request('resources/list'))
    print('Prompts:', engine.handle_request('prompts/list'))
tests/run_tests.sh (253 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
if [ -n "$PYTEST" ]; then
    $PYTEST tests/test_*.py -v
elif command -v pytest &> /dev/null; then
    pytest tests/test_*.py -v
else
    python3 -m unittest discover -s tests -p 'test_*.py' -v
fi
tests/test_mcp_resources_prompts.py (2086 bytes)
import pytest
from examples.mcp_resources_prompts import MCPResourcePromptEngine

def test_resources_list_and_read():
    engine = MCPResourcePromptEngine()
    engine.register_resource("memo://plan", "Quarterly Plan", "text/markdown", lambda: "# Q3 Plan\n- Ship MCP")
    
    list_res = engine.handle_request("resources/list")
    assert len(list_res["resources"]) == 1
    assert list_res["resources"][0]["uri"] == "memo://plan"
    
    read_res = engine.handle_request("resources/read", {"uri": "memo://plan"})
    assert read_res["contents"][0]["text"] == "# Q3 Plan\n- Ship MCP"
    assert read_res["contents"][0]["mimeType"] == "text/markdown"

def test_resource_not_found():
    engine = MCPResourcePromptEngine()
    with pytest.raises(ValueError) as exc:
        engine.handle_request("resources/read", {"uri": "nonexistent://file"})
    assert "not found" in str(exc.value)

def test_prompts_list_and_get():
    engine = MCPResourcePromptEngine()
    engine.register_prompt(
        "code_review",
        "Perform code review",
        [{"name": "diff", "required": True}],
        lambda diff: [{"role": "user", "content": {"type": "text", "text": f"Review diff:\n{diff}"}}]
    )
    
    list_res = engine.handle_request("prompts/list")
    assert len(list_res["prompts"]) == 1
    assert list_res["prompts"][0]["name"] == "code_review"
    
    get_res = engine.handle_request("prompts/get", {"name": "code_review", "arguments": {"diff": "+ x = 1"}})
    assert get_res["description"] == "Perform code review"
    assert len(get_res["messages"]) == 1
    assert "Review diff:\n+ x = 1" in get_res["messages"][0]["content"]["text"]

def test_prompt_not_found():
    engine = MCPResourcePromptEngine()
    with pytest.raises(ValueError) as exc:
        engine.handle_request("prompts/get", {"name": "unknown_prompt"})
    assert "not found" in str(exc.value)

def test_unsupported_method():
    engine = MCPResourcePromptEngine()
    with pytest.raises(ValueError) as exc:
        engine.handle_request("invalid/method")
    assert "Unsupported method" in str(exc.value)

Troubleshooting

Troubleshooting - Day 298

Ensure prompt templates return standard message array formats.

Security notes

Security - Day 298

Validate resource URIs to prevent arbitrary file system traversal.