How to use this course
1. Read one lesson at a time, in order. Each lesson has the same shape, so you always know what comes next.
2. Read "What it is", then "Why it matters".
3. Copy the TypeScript code, save it, and run it. Change one small thing and run it again. That is how you learn.
4. Do the "Try it yourself" task. It is small on purpose.
5. Answer the "Check" questions. Click a question to see the answer. If you got it wrong, read the lesson again.
6. Tick "Done" when you finish a lesson. Your progress is saved in this browser.
What is MCP, in plain words? MCP, or Model Context Protocol, is a standard way for an AI agent to talk to tools on a computer, like a plug that lets the agent use files, search, and other programs safely. The agent asks. The MCP server does the work on the computer and sends the answer back. The agent never touches your files directly.
Work in order: Module 1 explains why MCP exists. Module 2 builds your first server and agent. Module 3 teaches the agent to use tools well and ask for help. Module 4 makes errors helpful. Module 5 makes the agent faster, safer, and more predictable. Then try the extra practice capstone.
Setup — Node.js, MCP SDK, and running code
What you need
Node.js 20 or newer. That is all to start. The MCP examples also need the official MCP TypeScript SDK, which you install once with npm.
Step 1 — Check Node.js
Open a terminal and run:
node --versionYou should see v20 or newer, for example v24. If you see an older version, install a newer Node.js first.
Step 2 — Make a project folder
Make a folder for this course, for example mcp-course, and go into it in the terminal.
Step 3 — Make package.json
Save this as package.json in your project folder. It says: this project uses TypeScript, the MCP SDK, and Zod (for tool schemas).
{
"name": "mcp-course",
"version": "1.0.0",
"type": "module",
"scripts": {
"server": "node server.ts",
"agent": "node agent.ts"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0",
"zod": "^3.0.0"
}
}Step 4 — Make tsconfig.json
Save this as tsconfig.json in the same folder. It tells TypeScript: use modern JavaScript, and use ES modules.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}Step 5 — Install the SDK
Run this once, in your project folder:
npm installThis downloads the MCP SDK and Zod into a folder called node_modules. You only do this once per project.
How to run the code
- Copy the code from a lesson.
- Save it in a file, for example lesson.ts, in your project folder.
- In the terminal, run: node lesson.ts
- Read the output. Change one line, run it again, and see what changes.
One clear path: save every example as a .ts file and run it with node file.ts. Node 20 and newer can run TypeScript directly, as long as the code uses only simple types. All the code in this course follows that rule. MCP servers use stdio transport: they read requests as text and write answers as text. They run locally, with no server to deploy and no web address to open.
A server that is waiting for requests will look quiet. That is normal. It is waiting for the agent to connect. Run the agent in a second terminal to see it work.
No API key needed — the fake model
Every example in this course uses a small function called fakeLlm. It is not a real model. It reads keywords in the prompt and returns a fixed answer. That is enough to learn MCP, the loop, tools, and errors, and it works offline.
How to swap the fake model for a real OpenAI call — the short change. Only do this if you want to, and only after the course works with the fake model. Do not do it to follow the course.
// 1. Install once: npm install openai
// 2. Put your key in an environment variable, never in the code:
// export OPENAI_API_KEY=<redacted>
// 3. Replace fakeLlm with this real function:
import OpenAI from "openai";
const client = new OpenAI({ apiKey: <redacted>["OPENAI_API_KEY"] });
async function fakeLlm(prompt: string): Promise<string> {
const response = await client.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: prompt }] });
return response.choices[0].message.content ?? "";
}
// Note: the real call is async (it returns a Promise), so your run() functions
// would need `await` too. Learn the course first with the fake model, then swap.
Keep the same function name, fakeLlm, so all the other code keeps working. The real call is async, so your run() functions would need await too.
Try MCP here
Type a request, for example list my notes, add a note: buy milk, list my todos, or search notes for milk. The simulated MCP client below picks a tool from a simulated MCP server, shows the MCP request and response steps, and shows the final answer. No server, no key, no TypeScript needed for this box.
Press "Run the MCP agent" to see the MCP steps.
Try these: "list my notes", "add a note: buy milk", "list my todos", "add a todo: call bank", "search notes for milk", "hello".
Module 1 — Getting Started with Model Context Protocol (MCP) for AI Agents
What MCP is, why we need it, and how it lets an AI agent talk to a computer safely.
6 lessons in this module.
Video: Why Do We Need Model Context Protocol?
What it is
Model Context Protocol, or MCP, is a standard way for an AI agent to talk to tools on a computer. Think of it like a plug. Before MCP, every agent needed its own special connection to every tool: one way to read files, another way to search, another way to use a database. MCP gives them all one shared plug, so an agent can use many tools without learning a new connection each time.
Why it matters
Without a shared standard, every new tool means new custom code, and that code breaks easily. With MCP, you write a tool once as an MCP server, and any MCP agent can use it. That saves time and makes tools safer to share.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Before MCP: each tool needs its own custom code.
// With MCP: one shared way to list tools and call them.
// This lesson shows the idea in plain code, before we use the real MCP SDK.
type Tool = { name: string; description: string; run: () => string };
const tools: Tool[] = [
{ name: "list_notes", description: "List all notes.", run: () => "Notes: buy milk, call Ana" },
{ name: "list_todos", description: "List all to-dos.", run: () => "To-dos: finish report" },
];
// One shared way to use any tool: look it up by name, then run it.
function useTool(name: string): string {
const tool = tools.find((t) => t.name === name);
if (!tool) return "Error: no tool called " + name;
return tool.description + " Result: " + tool.run();
}
console.log(useTool("list_notes"));
console.log(useTool("list_todos"));
console.log(useTool("unknown_tool"));
Try it yourself
Add a third tool called 'search_notes' to the list, with a description and a run function that returns one note. Then call useTool('search_notes').
Check
What is MCP, in plain words?
A standard way for an AI agent to talk to tools on a computer, like one shared plug for many tools.
Why is one shared plug better than a custom connection for each tool?
You write a tool once, and any MCP agent can use it, instead of writing new custom code for every tool.
Video: Model Context Protocol & AI Problem Solving with Tools
What it is
An agent solves a problem in steps: understand the goal, pick a tool, use the tool, read the result, and repeat. MCP is the part that lets the agent use the tool. The model decides what to do. MCP carries the request to the tool and carries the result back. The model does the thinking; MCP does the talking to the computer.
Why it matters
If the agent cannot use tools, it can only talk. With MCP tools, it can act: read a file, add a note, search, or check a list. That is what turns a chatbot into an agent that gets work done.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Problem solving with tools: the model picks the tool, MCP-style code runs it.
// Step 1: ask the model. Step 2: run the tool it chose. Step 3: answer the user.
const notes: string[] = ["buy milk", "call Ana"];
function listNotes(): string { return notes.join(", "); }
function addNote(note: string): string { notes.push(note); return "Added note: " + note; }
function solve(userRequest: string): void {
const answer = fakeLlm(userRequest);
console.log("Model says:", answer);
if (answer.includes("list_notes")) console.log("Final answer: Your notes are: " + listNotes());
else if (answer.includes("add_note")) { addNote("buy milk"); console.log("Final answer: Added the note. Notes now: " + listNotes()); }
else console.log("Final answer: I will check that for you step by step.");
}
solve("list my notes");
solve("add a note: buy milk");
Try it yourself
Change the second call to 'add a note: call the bank' and run it. What does the notes list look like after?
Check
Who does the thinking, and who does the talking to the computer?
The model does the thinking. MCP does the talking to the computer and to the tools.
What can an agent do with tools that a chatbot alone cannot?
It can act: read files, add notes, search, and change things on the computer.
Video: MCP Allows AI to Communicate with the Computer
What it is
A computer has files, programs, and data. An AI model alone cannot touch them. MCP lets the model send a clear, safe request to a program on the computer, and get a clear answer back. For example: 'list the notes in my notes file' or 'add a to-do'. The MCP server is the program on the computer that receives the request, does the work, and returns the result.
Why it matters
This is the safe middle step. The model never touches your files directly. It asks the MCP server, and the server decides what is allowed. That keeps your computer safe while the agent still gets useful work done.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// The computer side: a small "server" object that owns the data.
// The agent side: only asks the server, it never touches the data itself.
const computer = {
notes: ["buy milk", "call Ana"],
listNotes(): string[] { return [...this.notes]; },
addNote(note: string): void { this.notes.push(note); },
};
// The agent talks to the computer only through these two requests.
function askComputer(request: string): string {
if (request === "list_notes") return "Notes: " + computer.listNotes().join(", ");
if (request.startsWith("add_note:")) { computer.addNote(request.slice(9).trim()); return "Note added."; }
return "Sorry, that request is not allowed.";
}
console.log(askComputer("list_notes"));
console.log(askComputer("add_note: buy bread"));
console.log(askComputer("list_notes"));
console.log(askComputer("delete everything"));
Try it yourself
Add a request called 'count_notes' that returns how many notes there are. Then call it.
Check
What does the MCP server do?
It receives a request from the agent, does the work on the computer, and returns the result.
Why should the model not touch your files directly?
So the server can decide what is allowed and keep your computer safe.
Reading: Next Module: Building MCP Servers and AI Agents
What it is
This is a short map of what comes next. In Module 2 you will build your first MCP server and your first MCP agent. A server offers tools. An agent (also called a client) connects to the server and uses those tools. After that, Module 3 teaches the agent to use tools well and to ask for help. Module 4 makes errors helpful. Module 5 makes the agent faster, safer, and more predictable.
Why it matters
A map helps you learn faster. You know why each lesson exists and how it connects to the next one, instead of learning tools one by one with no plan.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// A map of the course, as code: each module lists what you will build.
// Run this to see the plan in the terminal.
const plan: Record<string, string[]> = {
"Module 1": ["Understand MCP"],
"Module 2": ["Build an MCP server", "Build an MCP agent"],
"Module 3": ["Teach the agent to use tools and ask for help"],
"Module 4": ["Make errors helpful"],
"Module 5": ["Make the agent faster, safer, more predictable"],
};
for (const [module, steps] of Object.entries(plan)) {
console.log(module + ": " + steps.join(" -> "));
}
Try it yourself
Write down, in one sentence, what you most want to build with MCP by the end of this course.
Check
What will you build in Module 2?
Your first MCP server and your first MCP agent.
What is the job of Module 4?
To make errors helpful, so the agent can recover and keep working.
Reading: My AI Agent Tools
What it is
Your agent is only as useful as its tools. Good tools are small, clear, and do one thing well. 'List my notes' is a good tool. 'Do everything about my notes, files, and email' is a bad tool: it is too big, too vague, and the agent will not know when to use it. This lesson asks you to list the tools you already have in mind for your own agent, and to check each one: does it do one thing, and is its name clear?
Why it matters
Thinking about your own tools early stops you from building tools nobody needs. It also makes the later lessons easier, because you will build the tools you actually want.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// List the tools YOU want, in plain code. Each tool has a name and one clear job.
type ToolPlan = { name: string; job: string };
const myTools: ToolPlan[] = [
{ name: "list_notes", job: "List all my notes." },
{ name: "add_note", job: "Add one new note." },
{ name: "list_todos", job: "List all my to-dos." },
];
function checkTool(tool: ToolPlan): string {
if (tool.name.includes("_") && tool.job.split(" ").length <= 8) return tool.name + ": OK - one clear job.";
return tool.name + ": FIX - make the name clearer or the job smaller.";
}
for (const tool of myTools) console.log(checkTool(tool));
Try it yourself
Add one tool of your own to the list, for example a tool to search your notes. Run the check on it.
Check
What makes a good tool?
It does one thing well, and its name and job are clear.
Why list your own tools before building them?
So you build tools you actually need, and you spot vague tools early.
Reading: Learning More & Staying Connected
What it is
Learning does not stop at the last video. The MCP standard is new and it changes often, so the best habit is to keep reading the official MCP documentation and to try one small example after this course. Write down where you will look next: the official MCP docs, the TypeScript SDK page, and your own notes from this course.
Why it matters
A course gives you the start. The habit of reading the docs and trying small examples is what keeps your skills fresh when the tools change.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Keep a short list of places to learn more. Update it as you find new ones.
const learnMore: string[] = [
"Official MCP documentation: modelcontextprotocol.io",
"TypeScript SDK: @modelcontextprotocol/sdk on npm",
"Your notes from this course: keep them in one file",
];
for (const place of learnMore) console.log("- " + place);
console.log("Habit: after this course, try one small MCP example each week.");
Try it yourself
Add one more place to the list where you like to learn, for example a YouTube channel or a blog. Then run it.
Check
Why does MCP need you to keep learning after the course?
It is a new standard and it changes often, so the docs are the freshest source.
What is one good habit after finishing a course?
Try one small example each week, and keep your notes in one place.
Module 2 — AI Agent Loops & Model Context Protocol
How MCP fits inside the agent loop, what a server is, and your first server and agent.
8 lessons in this module.
Video: Model Context Protocol: Syntax, Semantics, Timing
What it is
Syntax is the shape of a message: what fields it has and in what order. Semantics is the meaning: what the message actually asks for. Timing is when it happens: what the agent asks first, and what it waits for. In MCP, a tool call has a clear syntax (tool name plus arguments), clear semantics (the description says what it does), and clear timing (the agent asks, waits for the result, then decides the next step).
Why it matters
If any of the three is unclear, the agent will fail. Bad syntax means the server cannot read the request. Bad meaning means the agent picks the wrong tool. Bad timing means the agent acts before it has the result it needs.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Syntax: the shape. Semantics: the meaning. Timing: the order.
// A tool call is one small object: a name, and arguments.
type ToolCall = { name: string; arguments: Record<string, string> };
const call: ToolCall = { name: "add_note", arguments: { note: "buy milk" } };
console.log("Syntax - tool call:", JSON.stringify(call));
// Semantics: the description tells the agent what the tool does.
// "Add one new note to the notes list." is clear. "Do notes stuff" is not.
const description = "Add one new note to the notes list.";
console.log("Semantics - description:", description);
// Timing: ask, wait for the result, then decide. Never skip the wait.
console.log("Timing - step 1: send the call. Step 2: wait. Step 3: read the result, then decide.");
Try it yourself
Write a tool call object for 'list_notes' with no arguments. Print it as JSON.
Check
What is syntax?
The shape of a message: what fields it has and in what order.
What is timing in an agent loop?
The order: ask, wait for the result, then decide the next step.
Video: Model Context Protocol & AI Agents
What it is
MCP and the agent loop fit together like this: the agent thinks, then it asks an MCP server to run a tool, then it reads the result and thinks again. MCP does not replace the loop. It gives the loop safe hands. The model still decides. MCP still carries out the action. This lesson connects the loop you learned in the earlier courses to the MCP servers you will build next.
Why it matters
This is the key picture for the whole course. Once you see the loop with MCP inside it, every later lesson is just one part of that picture getting better.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// The agent loop, with MCP inside it:
// think (model) -> call an MCP tool -> read the result -> think again.
const notes: string[] = ["buy milk", "call Ana"];
function mcpCall(tool: string, note = ""): string {
if (tool === "list_notes") return notes.join(", ");
if (tool === "add_note") { notes.push(note); return "Added: " + note; }
return "Unknown tool: " + tool;
}
function agentLoop(userRequest: string): void {
for (let step = 1; step <= 3; step++) {
const answer = fakeLlm(userRequest);
console.log("Step " + step + " - Model:", answer);
if (answer.includes("list_notes")) { console.log("MCP result:", mcpCall("list_notes")); console.log("Final answer: Your notes are: " + notes.join(", ")); return; }
if (answer.includes("add_note")) { console.log("MCP result:", mcpCall("add_note", "buy milk")); return; }
}
console.log("Final answer: Stopped after 3 steps.");
}
agentLoop("list my notes");
Try it yourself
Run the loop with the request 'add a note: buy milk' instead. What happens in step 1?
Check
What does MCP add to the agent loop?
Safe hands: it carries out the tool action the model chose, and brings the result back.
Does MCP replace the agent loop?
No. The loop stays. MCP sits inside the loop, as the way tools are called.
Video: What is an MCP Server?
What it is
An MCP server is a small program that offers tools, resources, and prompts to agents. Tools do things, like adding a note. Resources are data the agent can read, like a list of notes as a file. Prompts are ready-made instructions, like 'summarise my notes'. The server runs on your computer, usually over stdio (plain text in and out), and it only offers what you choose to offer. Nothing else is shared.
Why it matters
The server is the safe boundary. The agent cannot see your whole computer. It can only see the tools, resources, and prompts this server offers. That is how you stay in control.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A tiny MCP server, in plain code (no SDK yet - the real SDK version is next).
// It offers: 2 tools, 1 resource, 1 prompt. Nothing else.
const server = {
name: "notes-server",
tools: ["list_notes", "add_note"],
resources: ["notes://all"],
prompts: ["summarise-notes"],
describe(): string {
return this.name + " offers tools: " + this.tools.join(", ")
+ ". Resources: " + this.resources.join(", ")
+ ". Prompts: " + this.prompts.join(", ") + ".";
},
};
console.log(server.describe());
console.log("An agent can only use what the server offers. It cannot see anything else.");
Try it yourself
Add a third tool, 'search_notes', to the server's tool list. Print the description again.
Check
What three things can an MCP server offer?
Tools (do things), resources (data to read), and prompts (ready-made instructions).
Why is the server a safe boundary?
The agent can only use what the server offers. It cannot see the rest of your computer.
Video: Tool Specifications
What it is
A tool specification is the full description of a tool: its name, what it does, what arguments it needs, and what it returns. In MCP, the specification uses a schema, a small form that says each argument's name, type, and whether it is required. For example, add_note needs one argument, 'note', a string, required. The agent reads this specification to know how to call the tool correctly.
Why it matters
A clear specification is a contract. The server promises: if you call me like this, I will answer like that. The agent trusts the contract, and the server checks every call against it before doing any work.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A tool specification: name, description, and a schema for the arguments.
// The schema says: 'note' is a string, and it is required.
type ToolSpec = {
name: string;
description: string;
inputSchema: { type: string; properties: Record<string, { type: string; description: string }>; required: string[] };
};
const addNoteSpec: ToolSpec = {
name: "add_note",
description: "Add one new note to the notes list.",
inputSchema: {
type: "object",
properties: { note: { type: "string", description: "The text of the note to add." } },
required: ["note"],
},
};
console.log(JSON.stringify(addNoteSpec, null, 2));
// Check a call against the specification before running it.
function checkCall(args: Record<string, unknown>): string {
if (typeof args["note"] !== "string" || (args["note"] as string).trim() === "") return "Error: 'note' is required and must be a non-empty string.";
return "OK: call matches the specification.";
}
console.log(checkCall({ note: "buy milk" }));
console.log(checkCall({}));
console.log(checkCall({ note: "" }));
Try it yourself
Write a specification for 'list_notes' (no arguments needed). Print it as JSON.
Check
What does a tool specification contain?
The tool name, a description, and a schema saying what arguments it needs and what type they are.
Why check a call against the specification first?
So bad calls are stopped early, before the server does any work.
Video: Agents Talking to Tools vs. Tools with AI
What it is
There are two different ideas that sound alike. 'Agents talking to tools' means the agent calls a tool, and the tool just does its job, with no AI inside it. 'Tools with AI' means the tool itself contains AI, for example a tool that summarises text. In MCP, most tools are simple and have no AI inside. The AI lives in the agent, not in the tool. Keep tools simple, and keep the thinking in one place.
Why it matters
If every tool has its own AI, the system becomes hard to test, slow, and expensive. If tools stay simple, you can test each tool on its own, and the agent stays in charge of the thinking.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Agent talking to a tool: the tool is simple, the model does the thinking.
function listNotesTool(): string { return "buy milk, call Ana"; }
// Tool with AI: the tool itself calls the model. Use this only when you need it.
function summariseTool(text: string): string {
return fakeLlm("Summarise this: " + text);
}
console.log("Simple tool (no AI inside):", listNotesTool());
console.log("Tool with AI (use sparingly):", summariseTool("buy milk, call Ana, finish report"));
console.log("Rule: keep tools simple. Keep the thinking in the agent.");
Try it yourself
Write one sentence for each idea: 'agents talking to tools' and 'tools with AI'. What is the difference?
Check
Where should the thinking live?
In the agent, not in the tool.
Why keep tools simple?
So each tool is easy to test, fast, and cheap, and the agent stays in charge.
Reading: Course Code
What it is
The course code is the starting point for every hands-on lesson. It is a small TypeScript project with a package.json, a tsconfig.json, and two folders: one for the server and one for the agent. You will copy it, install it once, and then build on it lesson by lesson. Do not try to memorise it. Run it, break one small thing, fix it, and run it again.
Why it matters
Having one shared starting project means you do not waste time setting up again for each lesson. You start from working code, and each lesson changes one small part.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// The course project layout, as code. Keep this shape for every lesson.
// my-mcp-course/
// package.json (lists the MCP SDK)
// tsconfig.json (TypeScript settings)
// server.ts (your MCP server)
// agent.ts (your MCP agent / client)
const projectFiles: string[] = ["package.json", "tsconfig.json", "server.ts", "agent.ts"];
for (const file of projectFiles) console.log("- " + file);
console.log("Setup: npm install, then node server.ts and node agent.ts. See the Setup section.");
Try it yourself
Make the four files listed above in a folder on your computer (you can copy them from the Setup section). Run 'node --version' to check Node.js.
Check
What is the course code for?
A shared starting project, so every lesson starts from working code.
What are the two main files?
server.ts (the MCP server) and agent.ts (the MCP agent / client).
Hands-on: Building Your First MCP Server
What it is
Now you build it for real, with the official MCP TypeScript SDK. A server has a name and a version, it registers tools, and it connects over stdio, which means it reads requests as text and writes answers as text. No web server, no deployment. This server offers two tools: list_notes and add_note. It keeps the notes in memory, in a simple list.
Why it matters
This is the first real MCP server you own. Once it works, any MCP agent can use it, not just the agent in this course. That is the power of the standard.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// server.ts - your first MCP server. Save as server.ts.
// Setup first: npm install @modelcontextprotocol/sdk zod
// Run with: node server.ts (it waits for requests on stdio, so it will look quiet - that is normal)
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const notes: string[] = ["buy milk", "call Ana"];
const server = new McpServer({ name: "notes-server", version: "1.0.0" });
server.registerTool("list_notes",
{ title: "List notes", description: "List all notes.", inputSchema: {} },
async () => ({ content: [{ type: "text", text: notes.join("\n") || "No notes yet." }] }));
server.registerTool("add_note",
{ title: "Add note", description: "Add one new note to the notes list.",
inputSchema: { note: z.string().describe("The text of the note to add.") } },
async ({ note }) => {
const clean = note.trim();
if (!clean) return { content: [{ type: "text", text: "Error: the note must not be empty." }], isError: true };
notes.push(clean);
return { content: [{ type: "text", text: "Added note: " + clean }] };
});
await server.connect(new StdioServerTransport());
console.error("notes-server is running on stdio.");
Try it yourself
Run the server, then add a third tool called 'count_notes' that returns how many notes there are. Keep the same pattern as list_notes.
Check
What does registerTool do?
It adds one tool to the server, with a name, a description, an input schema, and the code that runs when it is called.
What is stdio transport?
The server reads requests as text and writes answers as text. No web server, no deployment.
Hands-on: Building Your First MCP AI Agent
What it is
An MCP agent, also called a client, connects to a server and uses its tools. It starts the server as a small program, asks the server what tools it offers, asks the model which tool to use, calls that tool through MCP, reads the result, and answers the user. This agent uses the fake model, so it runs offline. The MCP part is real: it really connects to your server from the last lesson.
Why it matters
This completes the pair: server and agent. You now have both sides of MCP working together, and you can see the full request and answer flow.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// agent.ts - your first MCP agent. Save as agent.ts, in the same folder as server.ts.
// Setup first: npm install @modelcontextprotocol/sdk
// Run with: node agent.ts "list my notes"
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
return "I will check that for you step by step.";
}
const userRequest = process.argv[2] || "list my notes";
const client = new Client({ name: "notes-agent", version: "1.0.0" });
await client.connect(new StdioClientTransport({ command: "node", args: ["server.ts"] }));
const tools = await client.listTools();
console.log("Server offers:", tools.tools.map((t) => t.name).join(", "));
const answer = fakeLlm(userRequest);
console.log("Model says:", answer);
if (answer.includes("list_notes")) {
const result = await client.callTool({ name: "list_notes", arguments: {} });
console.log("MCP result:", JSON.stringify(result.content));
console.log("Final answer: Here are your notes.");
} else if (answer.includes("add_note")) {
const result = await client.callTool({ name: "add_note", arguments: { note: "buy milk" } });
console.log("MCP result:", JSON.stringify(result.content));
console.log("Final answer: Note added.");
} else {
console.log("Final answer: I will check that for you step by step.");
}
await client.close();
Try it yourself
Run the agent with 'list my notes', then with 'add a note: buy milk'. What does the server offer in each run?
Check
What does the client do first?
It connects to the server and asks what tools the server offers.
What does callTool do?
It sends a tool call to the server through MCP and returns the server's result.
Module 3 — Building AI Agents with Model Context Protocol
How to teach agents to use tools, ask for help, and find guidance in the workspace.
6 lessons in this module.
Video: Resources
What it is
Resources are data the agent can read through MCP, without calling a tool. A resource has a name, like notes://all, and it returns text, like the full list of notes. Tools do things. Resources show things. Use a resource when the agent just needs to read data, and a tool when it needs to change something or do an action.
Why it matters
Reading data through resources is simpler and safer than using a tool for it. The agent can read the notes before it decides what to do, and the server controls exactly which data is visible.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// server.ts - add a resource to your server from Module 2.
// A resource is read-only data. The agent reads it, it does not change anything.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const notes: string[] = ["buy milk", "call Ana"];
const server = new McpServer({ name: "notes-server", version: "1.0.0" });
server.registerResource("all-notes",
"notes://all",
{ title: "All notes", description: "The full list of notes, as text.", mimeType: "text/plain" },
async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: notes.join("\n") }] }));
await server.connect(new StdioServerTransport());
console.error("notes-server is running on stdio.");
Try it yourself
Add a second resource called 'todo-list' at 'todos://all' that returns your to-do list as text.
Check
What is a resource?
Data the agent can read through MCP, like a file it can open but not change.
When should you use a resource instead of a tool?
When the agent only needs to read data, not change anything or do an action.
Hands-on: Teaching Agents to Use Tools
What it is
An agent does not use a tool well just because the tool exists. It needs three things: a clear tool name, a clear description of when to use it, and examples of good calls. Teach it in the prompt: list the tools, say when each one fits, and show one example call for each. Then the model can choose correctly.
Why it matters
Good teaching in the prompt is the cheapest way to make an agent better. It costs nothing extra, and it stops the most common mistake: the agent picking the wrong tool.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Teach the agent in the prompt: list the tools, when to use each, and one example.
// The fake model reads keywords, so the teaching shows as clear rules in the code.
function buildPrompt(userRequest: string): string {
return [
"You are a notes assistant. Use these tools:",
"- list_notes: use when the user asks to see or list notes. Example: list my notes.",
"- add_note: use when the user asks to add or save a note. Example: add a note: buy milk.",
"Answer with ACTION: <tool name>.",
"User request: " + userRequest,
].join("\n");
}
console.log(buildPrompt("list my notes"));
console.log("---");
console.log("Model:", fakeLlm(buildPrompt("list my notes")));
console.log("---");
console.log(buildPrompt("add a note: buy milk"));
Try it yourself
Add a third tool to the teaching list: search_notes, with when to use it and one example. Then run it.
Check
What three things does the agent need to use a tool well?
A clear name, a clear description of when to use it, and an example of a good call.
Why teach tools in the prompt?
It is the cheapest fix for the most common mistake: picking the wrong tool.
Hands-on: Teaching Agents to Seek Help
What it is
An agent should ask for help when it is not sure, instead of guessing. Help can be a question to the user, or a request to a guidance resource on the server. Teach the agent a simple rule: if the tool you need is unclear, or the arguments are missing, stop and ask. Guessing looks fast, but it creates wrong notes, wrong lists, and work the user has to undo.
Why it matters
Asking for help is a strength, not a failure. It keeps the agent safe, and it teaches the user what the agent can and cannot do.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Seek help: if the request is unclear, ask a question instead of guessing.
function solve(userRequest: string): string {
const lower = userRequest.toLowerCase();
if (lower.includes("list") && lower.includes("note")) return "ACTION: list_notes";
if (lower.includes("add") && lower.includes("note")) {
// The note text is missing - ask for help instead of guessing.
if (!lower.includes(":")) return "HELP NEEDED: What is the text of the note? Please tell me the note to add.";
return "ACTION: add_note | NOTE: buy milk";
}
return "HELP NEEDED: I am not sure what you want. Do you want to list notes, add a note, or search notes?";
}
console.log(solve("list my notes"));
console.log(solve("add a note"));
console.log(solve("do something with my stuff"));
Try it yourself
Change the last request to 'add a note: call the bank'. What does the agent do now?
Check
When should an agent ask for help?
When the tool is unclear, or the arguments it needs are missing.
Why is asking better than guessing?
Guessing creates wrong work the user has to undo. Asking keeps the agent safe.
Hands-on: Helping Agents Find Guidance
What it is
Guidance is short, useful text the server offers the agent, like a help page. For example, a resource called guidance://notes that says: 'Notes are short, one idea each. Keep them under 10 words.' The agent reads the guidance before it acts, so its work matches how you want it done. Put guidance on the server, not only in the prompt, so every agent that uses the server gets the same guidance.
Why it matters
Guidance on the server means every agent behaves the same way, even if different people wrote the agents. It also means you can update the guidance in one place.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// server.ts - add a guidance resource to your server.
// Guidance is a short help text the agent reads before it acts.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({ name: "notes-server", version: "1.0.0" });
server.registerResource("notes-guidance",
"guidance://notes",
{ title: "Notes guidance", description: "How to write good notes.", mimeType: "text/plain" },
async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain",
text: "Notes are short, one idea each. Keep each note under 10 words. Start with a verb when it is a task, for example: 'Call Ana'." }] }));
await server.connect(new StdioServerTransport());
console.error("notes-server is running on stdio.");
Try it yourself
Add a second guidance resource, 'guidance://todos', that says how to write a good to-do. Keep it under 3 sentences.
Check
What is guidance?
Short, useful text the server offers the agent, like a help page for how to do the work well.
Why put guidance on the server, not only in the prompt?
So every agent that uses the server gets the same guidance, and you can update it in one place.
Hands-on: Helping AI Agents on the Fly
What it is
On the fly means in the middle of the work, not before it starts. Sometimes the agent learns something new while it is working: a tool fails, a note is longer than expected, or the user adds a new rule. The agent should be able to read fresh guidance at that moment, not only at the start. Give the server a resource the agent can read again at any step, and teach the agent to re-read it when something is unclear.
Why it matters
Work changes while it is happening. An agent that can get fresh help in the middle of a task recovers faster than one that only had help at the start.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// On the fly: the agent re-reads guidance in the middle of the loop, when it gets stuck.
function readGuidance(): string {
return "Guidance: notes are short, one idea each, under 10 words.";
}
function solve(userRequest: string): void {
const answer = fakeLlm(userRequest);
console.log("Model:", answer);
if (answer.includes("I will check")) {
console.log("Agent is unsure. Reading fresh guidance on the fly...");
console.log(readGuidance());
console.log("Agent: now I know how to proceed. I will list the notes.");
} else {
console.log("Agent: I know what to do. No extra guidance needed.");
}
}
solve("list my notes");
solve("do something with my stuff");
Try it yourself
Change the guidance text to add one new rule, for example 'Always show the date'. Run it again and read the new guidance.
Check
What does 'on the fly' mean?
In the middle of the work, not only before it starts.
When should the agent re-read guidance?
When it gets stuck, or when something in the work is unclear.
Hands-on: Helping AI Agents Discover Workspace-related Guidance
What it is
A workspace is the folder where your work lives: your notes, your to-dos, your files. Workspace guidance tells the agent how this workspace works: where the notes live, what the file names mean, and what rules to follow here. The agent should be able to discover this guidance on its own, by listing the resources the server offers, instead of you telling it everything in advance.
Why it matters
Every workspace is a little different. If the agent can discover the rules of this workspace, it works well in a new workspace without you rewriting the agent.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// agent.ts - discover guidance: list the resources the server offers, then read the workspace one.
// The agent does not need to know the resource names in advance. It asks the server.
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const client = new Client({ name: "notes-agent", version: "1.0.0" });
await client.connect(new StdioClientTransport({ command: "node", args: ["server.ts"] }));
const resources = await client.listResources();
console.log("Resources this server offers:");
for (const r of resources.resources) console.log("- " + r.uri + " : " + r.name);
const workspace = resources.resources.find((r) => r.uri.includes("workspace"));
if (workspace) {
const data = await client.readResource({ uri: workspace.uri });
console.log("Workspace guidance:", JSON.stringify(data.contents));
} else {
console.log("No workspace guidance found. The agent will ask the user for the rules.");
}
await client.close();
Try it yourself
Add a workspace guidance resource to your server (see the last lesson), then run this agent and check that it finds it.
Check
What is workspace guidance?
Text that tells the agent how this workspace works: where things live, and what rules to follow here.
How does the agent discover it?
By listing the resources the server offers, then reading the workspace one, instead of being told in advance.
Module 4 — Robust Error Handling Techniques for AI Agents
How to design errors that help the agent recover, instead of getting stuck.
5 lessons in this module.
Hands-on: Responses are More than Data
What it is
A tool result is not just data. It also carries meaning: did it work, what happened, and what should the agent do next? A good response says: 'Added note: buy milk. You now have 3 notes.' A bad response says only: 'OK'. The agent cannot learn from 'OK'. Give the agent a result it can act on: the outcome, the new state, and the next useful step.
Why it matters
Agents learn from results. If the result is thin, the agent has to guess what happened. If the result is rich, the agent can decide its next step with confidence.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A rich response: outcome + new state + next step. Not just "OK".
type RichResult = { ok: boolean; message: string; totalNotes: number; nextStep: string };
function addNoteRich(note: string, notes: string[]): RichResult {
notes.push(note);
return {
ok: true,
message: "Added note: " + note + ".",
totalNotes: notes.length,
nextStep: "You can now list the notes to check the new list.",
};
}
const notes: string[] = ["buy milk", "call Ana"];
console.log(addNoteRich("buy bread", notes));
console.log("Bad response for comparison: { ok: true } - the agent learns nothing from this.");
Try it yourself
Change the rich response to include the full notes list as well. Print it and read what the agent would learn.
Check
What makes a tool response rich?
It says the outcome, the new state, and the next useful step, not just 'OK'.
Why does the agent need more than data?
So it can decide its next step with confidence, instead of guessing what happened.
Hands-on: Designing Errors to Help AI Agents
What it is
An error is a message that helps the agent fix the problem. A good error says what went wrong, why, and what to try instead. For example: 'Error: the note is empty. A note must have text. Try again with a note like: buy milk.' A bad error says only: 'Error 400'. The agent cannot fix 'Error 400'. Design errors as help, not as punishment.
Why it matters
Errors will happen. The question is whether the agent can recover in one step, or whether it gets stuck. Helpful errors are the difference.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A helpful error: what went wrong, why, and what to try instead.
type ErrorHelp = { error: string; why: string; tryInstead: string };
function addNoteSafe(note: string, notes: string[]): string | ErrorHelp {
const clean = note.trim();
if (!clean) return { error: "The note is empty.", why: "A note must have text to be useful.", tryInstead: "Try again with a note like: buy milk." };
if (clean.length > 100) return { error: "The note is too long.", why: "Notes must be under 100 characters.", tryInstead: "Shorten the note to under 100 characters and try again." };
notes.push(clean);
return "Added note: " + clean;
}
const notes: string[] = ["buy milk"];
console.log(addNoteSafe("", notes));
console.log(addNoteSafe("buy milk", notes));
console.log(addNoteSafe("x".repeat(101), notes));
Try it yourself
Add a third error: if the note already exists, say so and suggest adding a different note.
Check
What does a helpful error contain?
What went wrong, why it went wrong, and what to try instead.
Why is 'Error 400' a bad error for an agent?
It says nothing the agent can act on, so the agent cannot fix the problem.
Hands-on: Errors in Complex Workflows
What it is
A workflow is several steps in a row: list the notes, add a note, then list them again to check. If step 2 fails, what should happen to step 3? The agent needs a plan: stop, report what worked and what failed, and do not pretend the whole workflow worked. Keep a simple record of each step, so the agent can say: 'Step 1 worked, step 2 failed because the note was empty, step 3 was skipped.'
Why it matters
In a long workflow, a silent failure is worse than a loud one. A clear record lets the agent and the user see exactly where it stopped, and what is still safe to do.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// A workflow with a step record: each step says if it worked, and why.
// If one step fails, the workflow stops and reports, instead of pretending it worked.
type StepResult = { step: string; ok: boolean; detail: string };
function runWorkflow(): void {
const notes: string[] = ["buy milk"];
const record: StepResult[] = [];
record.push({ step: "list_notes", ok: true, detail: "Found 1 note." });
const noteToAdd = "";
if (noteToAdd.trim() === "") {
record.push({ step: "add_note", ok: false, detail: "Failed: the note is empty. Try again with text." });
console.log("Workflow stopped. Report:");
for (const r of record) console.log("- " + r.step + ": " + (r.ok ? "OK" : "FAILED") + " - " + r.detail);
console.log("Step 3 (list again) was skipped. Nothing was pretended to work.");
return;
}
notes.push(noteToAdd);
record.push({ step: "add_note", ok: true, detail: "Added note." });
console.log("Workflow finished. All steps OK.");
}
runWorkflow();
Try it yourself
Change the note to 'buy bread' and run the workflow again. What does the record look like now?
Check
What should the agent do if step 2 of a workflow fails?
Stop, report what worked and what failed, and skip the later steps. Do not pretend it worked.
Why keep a record of each step?
So the agent and the user can see exactly where it stopped, and what is still safe to do.
Hands-on: Minimizing AI Agent Cognitive Burden from Error Recovery
What it is
Cognitive burden means how much the agent has to think about at once. When an error happens, do not give the agent the whole history of the task and ask it to work out what went wrong. Give it a short, clear summary: what failed, what the last good state was, and the one best next step. Less to think about means fewer mistakes.
Why it matters
The model has a limit on how much it can hold in mind. Short, clear error summaries keep the agent focused, and recovery becomes one small step instead of a new puzzle.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Minimise burden: give the agent a short summary, not the whole history.
type ErrorSummary = { whatFailed: string; lastGoodState: string; bestNextStep: string };
function summariseError(): ErrorSummary {
return {
whatFailed: "add_note failed: the note was empty.",
lastGoodState: "Notes list is unchanged: buy milk, call Ana.",
bestNextStep: "Ask the user for the note text, then call add_note once.",
};
}
const summary = summariseError();
console.log("Error summary for the agent:");
console.log("- What failed: " + summary.whatFailed);
console.log("- Last good state: " + summary.lastGoodState);
console.log("- Best next step: " + summary.bestNextStep);
console.log("The agent does NOT need the full history. This short summary is enough.");
Try it yourself
Write a short error summary for a different failure: 'search_notes found nothing'. What is the best next step?
Check
What is cognitive burden?
How much the agent has to think about at once.
What should an error summary contain?
What failed, what the last good state was, and the one best next step.
Hands-on: Helping AI Agents Find Alternative Paths to Fix Errors
What it is
When the first plan fails, the agent needs a second plan. Teach it alternatives in advance: if add_note fails because the note is empty, ask the user. If search finds nothing, try a shorter search word. If a tool is not available, try a different tool that does almost the same job. List the alternatives in the tool description or in the guidance, so the agent does not have to invent them under stress.
Why it matters
An agent with a second plan recovers on its own. An agent with only one plan stops and waits for the user, even for small problems it could have fixed.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Alternative paths: if plan A fails, try plan B, then plan C.
// List the alternatives in the code, so the agent does not have to invent them.
function addNoteWithAlternatives(note: string, notes: string[]): string {
const clean = note.trim();
if (clean) { notes.push(clean); return "Plan A worked: added note: " + clean; }
// Plan B: the note is empty, so ask the user instead of guessing.
return "Plan A failed: the note is empty. Plan B: ask the user 'What is the text of the note?' and try again.";
}
function searchWithAlternatives(query: string, notes: string[]): string {
const found = notes.filter((n) => n.toLowerCase().includes(query.toLowerCase()));
if (found.length > 0) return "Found: " + found.join(", ");
// Plan B: try a shorter word. Plan C: list all notes.
return "Nothing found for '" + query + "'. Plan B: try a shorter word. Plan C: list all notes to see what exists.";
}
const notes: string[] = ["buy milk", "call Ana"];
console.log(addNoteWithAlternatives("", notes));
console.log(searchWithAlternatives("xyz", notes));
console.log(searchWithAlternatives("milk", notes));
Try it yourself
Add a Plan B for 'list_notes' when there are no notes: what should the agent say or do instead?
Check
What is an alternative path?
A second plan to try when the first plan fails.
Why list alternatives in advance?
So the agent can recover on its own, instead of stopping and waiting for the user.
Module 5 — Faster, More Predictable, More Capable AI Agents
Prompts, identity, security, and how to make agents faster, cheaper, and more predictable.
9 lessons in this module.
Video: Prompts and MCP
What it is
Prompts in MCP are ready-made instructions that the server offers. For example, a prompt called 'summarise-notes' tells the agent: 'Summarise the notes in short bullet points.' The agent can ask the server for that prompt, fill in the details, and then use it. Prompts live on the server, so every agent gets the same good instructions, and you can update them in one place.
Why it matters
Good prompts are hard to write. If each agent writes its own, the results will be different every time. Shared prompts on the server make the results consistent.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// server.ts - add a prompt to your server.
// A prompt is a ready-made instruction, with small blanks the agent fills in.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "notes-server", version: "1.0.0" });
server.registerPrompt("summarise-notes",
{ title: "Summarise notes", description: "Summarise the notes in short bullet points.",
argsSchema: { count: z.string().describe("How many notes to summarise, for example '3'.") } },
async ({ count }) => ({ messages: [{ role: "user",
content: { type: "text", text: "Summarise the latest " + count + " notes in short bullet points. Keep each point under 10 words." } }] }));
await server.connect(new StdioServerTransport());
console.error("notes-server is running on stdio.");
Try it yourself
Add a second prompt called 'plan-day' that asks the agent to turn the to-dos into a short plan for today.
Check
What is a prompt in MCP?
A ready-made instruction the server offers, with small blanks the agent fills in.
Why keep prompts on the server?
So every agent gets the same good instructions, and you can update them in one place.
Video: AI Agents, MCP, & Identity
What it is
Identity means: who is asking? An agent acts for a person, and the server needs to know which person, so it can show only that person's notes and not someone else's. In MCP, identity travels with the request: the agent says who it works for, and the server checks that the agent is allowed to see or change that data. For this course, keep it simple: one user, one workspace, and the server only serves that workspace.
Why it matters
Identity is what makes MCP safe for real use. Without it, any agent could read anyone's data. With it, each agent only sees its own user's work.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Identity, kept simple: one user, one workspace.
// The server only serves this workspace, and the agent says who it works for.
type Identity = { user: string; workspace: string };
const identity: Identity = { user: "Oswaldo", workspace: "my-notes" };
function checkIdentity(id: Identity): string {
if (id.user === "Oswaldo" && id.workspace === "my-notes") return "OK: " + id.user + " may use the " + id.workspace + " workspace.";
return "Denied: this agent may not use that workspace.";
}
console.log(checkIdentity(identity));
console.log(checkIdentity({ user: "Someone else", workspace: "my-notes" }));
console.log("Rule: the server checks identity before it does any work.");
Try it yourself
Change the workspace to 'work-notes' and run the check. What happens, and why?
Check
What is identity in MCP?
Knowing who the agent works for, so the server can show only that person's data.
Why check identity before doing any work?
So an agent cannot read or change someone else's data.
Video: Security
What it is
Security in MCP means three simple rules. One: only offer what is needed. If the agent does not need to delete notes, do not offer a delete tool. Two: check every call. The server checks the tool name, the arguments, and the identity before it acts. Three: never put secrets in the code. API keys live in environment variables, not in the file you share. Follow these three rules, and your MCP server is already much safer than most.
Why it matters
MCP servers run on your computer and can change your files. That power needs clear limits. Small limits, checked every time, are what keep a useful tool from becoming a dangerous one.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Security: three simple rules, as code.
// Rule 1: only offer what is needed. Rule 2: check every call. Rule 3: no secrets in code.
const allowedTools: string[] = ["list_notes", "add_note", "search_notes"];
function checkCall(tool: string, args: Record<string, unknown>): string {
if (!allowedTools.includes(tool)) return "Denied: tool '" + tool + "' is not offered by this server.";
if (tool === "add_note" && typeof args["note"] !== "string") return "Denied: add_note needs a 'note' string.";
return "OK: call is allowed.";
}
console.log(checkCall("list_notes", {}));
console.log(checkCall("delete_all_notes", {}));
console.log(checkCall("add_note", { note: 123 }));
console.log("Rule 3: API keys live in environment variables, never in the code. Example: <redacted>['OPENAI_API_KEY']");
Try it yourself
Add a tool called 'delete_note' to the allowed list, then remove it again. Which version is safer, and why?
Check
What are the three security rules?
Only offer what is needed, check every call, and never put secrets in the code.
Why not offer a delete tool if the agent does not need it?
Every tool you offer is a door. Fewer doors means fewer ways for things to go wrong.
Video: Wrapping Up
What it is
You now have the full picture: MCP is a shared plug, a server offers tools, resources, and prompts, and an agent connects to the server and uses them in a loop. You also know how to teach the agent, how to make errors helpful, and how to make the agent faster and safer. The final assessment below checks the whole course, not just one lesson. After that, build the practice project and keep going.
Why it matters
A good ending is a check, not just a goodbye. It shows you what you know, and what to practise once more before moving on.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Wrapping up: the whole course in one small program.
// Agent -> MCP client -> MCP server -> tools -> answer.
const notes: string[] = ["buy milk", "call Ana"];
console.log("1. User: list my notes");
console.log("2. Agent thinks:", fakeLlm("list my notes"));
console.log("3. MCP client calls tool: list_notes");
console.log("4. MCP server returns:", notes.join(", "));
console.log("5. Agent answers: Your notes are: " + notes.join(", "));
console.log("You now know both sides: the server and the agent. Well done.");
Try it yourself
Write down, in three sentences, what MCP is, what a server does, and what an agent does. Compare it with the Module 1 lesson.
Check
What are the two sides of MCP?
The server, which offers tools, resources, and prompts, and the agent (client), which uses them.
What should you do after this lesson?
Do the Final Assessment, then build the practice project.
Assignment: Final Assessment
What it is
This is the final check for the whole course. It is not a test you must pass in one go. Work through the checklist below, and for each item, show yourself that it works: run the server, run the agent, and read the output. If an item does not work, go back to that module and try it again. Tick each item only when you can show it working.
Why it matters
A final assessment that you can show working is worth more than a score. It proves you can build a server, an agent, and a loop that works together, not just that you remember the words.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Final Assessment: a self-check you can run.
// For each item, run the code it points to and tick it only when it works.
const assessment: string[] = [
"1. I can explain MCP in plain words.",
"2. My MCP server runs and offers list_notes and add_note.",
"3. My MCP agent connects to the server and lists the tools.",
"4. My agent uses a tool and reads the result in a loop.",
"5. My server offers a resource and a prompt.",
"6. My errors tell the agent what went wrong and what to try instead.",
"7. I can explain identity and the three security rules.",
"8. I built the workspace practice project (see the capstone).",
];
for (const item of assessment) console.log("[ ] " + item);
console.log("Tick each item in the Final checklist section of this page when you can show it working.");
Try it yourself
Go through the checklist in the Final checklist section. Tick the items you can already show working, and note the ones to practise again.
Check
How should you do the Final Assessment?
Work through each item, run the code it points to, and tick it only when you can show it working.
What does the assessment prove?
That you can build a server, an agent, and a loop that work together.
Hands-on: Managing AI Agent Cognitive Load
What it is
Cognitive load is how much the agent has to hold in mind at once. To keep it low, give the agent fewer tools at a time, shorter prompts, and short results. Do not list 20 tools when the task needs 3. Do not send the whole notes history when only the last 5 notes matter. Small, focused inputs make the agent faster and more accurate.
Why it matters
A model that is overloaded makes mistakes, even on easy tasks. Managing load is not about making the agent less smart. It is about giving it only what it needs for this step.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Manage load: only the tools and data this step needs.
// Bad: send all 20 tools and all notes. Good: send 3 tools and the last 5 notes.
const allTools: string[] = ["list_notes", "add_note", "search_notes", "delete_note", "edit_note", "share_note"];
const notes: string[] = ["buy milk", "call Ana", "finish report", "buy bread", "call bank", "plan trip", "buy eggs"];
function toolsForTask(task: string): string[] {
if (task.includes("list")) return ["list_notes"];
if (task.includes("add")) return ["add_note"];
return ["list_notes", "add_note", "search_notes"];
}
function recentNotes(count: number): string[] { return notes.slice(-count); }
console.log("Tools for 'list my notes':", toolsForTask("list my notes"));
console.log("Recent notes (last 3):", recentNotes(3));
console.log("Load kept low: 1 tool and 3 notes, not 6 tools and 7 notes.");
Try it yourself
Change the task to 'add a note' and run it. How many tools does the agent get now?
Check
What is cognitive load?
How much the agent has to hold in mind at once.
How do you keep it low?
Give the agent fewer tools, shorter prompts, and only the data this step needs.
Hands-on: Predictability, Lower Cost, Speed: Scripted Orchestration for AI Agents
What it is
Scripted orchestration means writing the steps down in advance, instead of letting the model decide every step. For example: step 1, list the notes. Step 2, add a note. Step 3, list the notes again to check. The model still does the thinking inside each step, but the order is fixed. Fixed order means fewer model calls, lower cost, faster answers, and the same result every time.
Why it matters
Free choice is flexible, but it is slow and unpredictable. A script is fast and predictable. Use a script when the steps are known, and let the model choose only when the steps are truly unknown.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Scripted orchestration: the steps are fixed. The model only fills in the details.
// Fewer model calls = lower cost, faster, and the same result every time.
const notes: string[] = ["buy milk", "call Ana"];
function scriptedAddNote(note: string): void {
console.log("Step 1 (scripted): list notes -> " + notes.join(", "));
notes.push(note);
console.log("Step 2 (scripted): add note -> Added: " + note);
console.log("Step 3 (scripted): list notes again -> " + notes.join(", "));
console.log("Done. The order was fixed, so only one model call was needed.");
}
console.log("Model (one call):", fakeLlm("add a note: buy bread"));
scriptedAddNote("buy bread");
Try it yourself
Write a script for a different task: search for 'milk', then add a note if it is not found. Keep the steps fixed.
Check
What is scripted orchestration?
Writing the steps down in advance, in a fixed order, instead of letting the model decide every step.
Why is it cheaper and faster?
Fewer model calls, and the same result every time, because the order is fixed.
Hands-on: Self-Prompting: Adding Reasoning to Tools
What it is
Self-prompting means the tool itself asks the model a small question before it answers. For example, a search tool first asks: 'Which word in this request is the search word?' Then it searches with that word. The tool does a little thinking, so the agent does not have to do all of it. Keep the tool's question small and clear, so it helps instead of adding confusion.
Why it matters
A little reasoning inside the tool can fix the most common tool mistakes, like searching with the wrong word. It is a small step, but it makes the tool much more reliable.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// Self-prompting: the tool asks the model a small question before it acts.
// The tool asks: "Which word is the search word?" Then it searches with that word.
function searchNotesWithReasoning(userRequest: string, notes: string[]): string {
const reasoning = fakeLlm("Which word in this request is the search word? Request: " + userRequest);
console.log("Tool reasoning - model says:", reasoning);
const query = userRequest.toLowerCase().includes("milk") ? "milk" : "Ana";
const found = notes.filter((n) => n.toLowerCase().includes(query));
return found.length > 0 ? "Found: " + found.join(", ") : "Nothing found for '" + query + "'.";
}
const notes: string[] = ["buy milk", "call Ana"];
console.log(searchNotesWithReasoning("find my note about milk", notes));
console.log(searchNotesWithReasoning("find my note about Ana", notes));
Try it yourself
Change the request to 'find my note about bread' and run it. What does the tool search for?
Check
What is self-prompting?
The tool asks the model a small question before it acts, so it can do its job better.
Why keep the tool's question small?
So it helps the agent instead of adding confusion.
Hands-on: AI Agent Tool Design for Common Errors
What it is
Some errors happen again and again: an empty note, a missing argument, a search with no result. Design your tools for those common errors in advance. Make the empty note impossible by checking first. Make the missing argument clear by naming it in the error. Make 'no result' helpful by suggesting a shorter search. A tool designed for common errors fails less, and recovers faster when it does fail.
Why it matters
You cannot prevent every error, but you can prevent the ones you already know will happen. That is the best return on design time in this whole course.
Note: Swap note: to use a real model, replace fakeLlm with a real call. See the Setup section for the short change. No key is needed to follow this course.
// Design for common errors, in advance.
// Common error 1: empty note. Common error 2: missing argument. Common error 3: no search result.
function addNoteDesigned(note: unknown, notes: string[]): string {
if (typeof note !== "string" || note.trim() === "") return "Error: the note is empty. Try again with a note like: buy milk.";
notes.push(note.trim());
return "Added note: " + note.trim() + ". Total notes: " + notes.length;
}
function searchNotesDesigned(query: unknown, notes: string[]): string {
if (typeof query !== "string" || query.trim() === "") return "Error: the search needs a word. Try again with a word like: milk.";
const found = notes.filter((n) => n.toLowerCase().includes(query.toLowerCase()));
if (found.length === 0) return "No notes found for '" + query + "'. Try a shorter word, or list all notes to see what exists.";
return "Found: " + found.join(", ");
}
const notes: string[] = ["buy milk", "call Ana"];
console.log(addNoteDesigned("", notes));
console.log(searchNotesDesigned("", notes));
console.log(searchNotesDesigned("xyz", notes));
console.log(searchNotesDesigned("milk", notes));
Try it yourself
Add a fourth common error to the design: what if the note is already in the list? What should the tool say?
Check
What are three common errors to design for?
An empty note, a missing argument, and a search with no result.
Why design for errors you already know will happen?
Because preventing known errors is the best return on design time, and recovery becomes faster.
Extra practice: Workspace MCP Server + Agent
This is extra practice, not a curriculum lesson. It is a complete MCP server and agent for a small workspace: files, notes, and a to-do list. It reuses the server, agent loop, guidance, and error handling from this course. Save the first part as server.ts and the second part as agent.ts, in the same folder. Run the agent with node agent.ts "list my notes".
// A small simulated model. It does NOT call the internet.
// It reads keywords in the prompt and returns a fixed, clear answer.
// This lets every example in this course run offline, with no API key.
function fakeLlm(prompt: string): string {
const text = prompt.toLowerCase();
if (text.includes("list") && text.includes("note")) return "ACTION: list_notes";
if (text.includes("add") && text.includes("note")) return "ACTION: add_note | NOTE: buy milk";
if (text.includes("list") && text.includes("todo")) return "ACTION: list_todos";
if (text.includes("add") && text.includes("todo")) return "ACTION: add_todo | TODO: call Ana";
if (text.includes("search")) return "ACTION: search_notes | QUERY: milk";
if (text.includes("hello") || text.includes("hi")) return "Hello! I am your agent. How can I help?";
return "I will check that for you step by step.";
}
// CAPSTONE (extra practice): a complete MCP workspace server + agent.
// Workspace: files, notes, and a to-do list. It reuses the server, agent loop,
// guidance, and error handling from this course.
// Files: server.ts (the MCP server) and agent.ts (the MCP agent).
// Setup: npm install @modelcontextprotocol/sdk zod
// Run the agent with: node agent.ts "list my notes"
// ---------- server.ts ----------
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const notes: string[] = ["buy milk", "call Ana"];
const todos: string[] = ["finish report", "call bank"];
const server = new McpServer({ name: "workspace-server", version: "1.0.0" });
server.registerTool("list_notes",
{ title: "List notes", description: "List all notes.", inputSchema: {} },
async () => ({ content: [{ type: "text", text: notes.join("\n") || "No notes yet." }] }));
server.registerTool("add_note",
{ title: "Add note", description: "Add one new note. The note must not be empty.",
inputSchema: { note: z.string().describe("The text of the note to add.") } },
async ({ note }) => {
const clean = note.trim();
if (!clean) return { content: [{ type: "text", text: "Error: the note is empty. A note must have text. Try again with a note like: buy milk." }], isError: true };
if (notes.includes(clean)) return { content: [{ type: "text", text: "That note already exists: " + clean + ". Try a different note." }] };
notes.push(clean);
return { content: [{ type: "text", text: "Added note: " + clean + ". Total notes: " + notes.length }] };
});
server.registerTool("search_notes",
{ title: "Search notes", description: "Search notes for one word.",
inputSchema: { query: z.string().describe("One word to search for.") } },
async ({ query }) => {
const found = notes.filter((n) => n.toLowerCase().includes(query.toLowerCase()));
if (found.length === 0) return { content: [{ type: "text", text: "No notes found for '" + query + "'. Try a shorter word, or list all notes." }] };
return { content: [{ type: "text", text: "Found: " + found.join(", ") }] };
});
server.registerTool("list_todos",
{ title: "List to-dos", description: "List all to-dos.", inputSchema: {} },
async () => ({ content: [{ type: "text", text: todos.join("\n") || "No to-dos yet." }] }));
server.registerTool("add_todo",
{ title: "Add to-do", description: "Add one new to-do. It must not be empty.",
inputSchema: { todo: z.string().describe("The text of the to-do to add.") } },
async ({ todo }) => {
const clean = todo.trim();
if (!clean) return { content: [{ type: "text", text: "Error: the to-do is empty. Try again with a to-do like: call bank." }], isError: true };
todos.push(clean);
return { content: [{ type: "text", text: "Added to-do: " + clean + ". Total to-dos: " + todos.length }] };
});
server.registerResource("workspace-guidance",
"guidance://workspace",
{ title: "Workspace guidance", description: "How this workspace works.", mimeType: "text/plain" },
async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain",
text: "Workspace rules: notes are short, one idea each, under 10 words. To-dos start with a verb. If a tool fails, read the error, fix the one problem, and try once more." }] }));
server.registerPrompt("summarise-notes",
{ title: "Summarise notes", description: "Summarise the notes in short bullet points.",
argsSchema: { count: z.string().describe("How many notes to summarise.") } },
async ({ count }) => ({ messages: [{ role: "user",
content: { type: "text", text: "Summarise the latest " + count + " notes in short bullet points." } }] }));
await server.connect(new StdioServerTransport());
console.error("workspace-server is running on stdio.");
// ---------- agent.ts ----------
// Save as agent.ts, in the same folder as server.ts. Run: node agent.ts "list my notes"
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const userRequest = process.argv[2] || "list my notes";
const client = new Client({ name: "workspace-agent", version: "1.0.0" });
await client.connect(new StdioClientTransport({ command: "node", args: ["server.ts"] }));
const tools = await client.listTools();
console.log("Server offers:", tools.tools.map((t) => t.name).join(", "));
const answer = fakeLlm(userRequest);
console.log("Model says:", answer);
if (answer.includes("list_notes")) {
const result = await client.callTool({ name: "list_notes", arguments: {} });
console.log("MCP result:", JSON.stringify(result.content));
} else if (answer.includes("add_note")) {
const result = await client.callTool({ name: "add_note", arguments: { note: "buy milk" } });
console.log("MCP result:", JSON.stringify(result.content));
} else if (answer.includes("list_todos")) {
const result = await client.callTool({ name: "list_todos", arguments: {} });
console.log("MCP result:", JSON.stringify(result.content));
} else if (answer.includes("search_notes")) {
const result = await client.callTool({ name: "search_notes", arguments: { query: "milk" } });
console.log("MCP result:", JSON.stringify(result.content));
} else {
console.log("Help: try 'list my notes', 'add a note', 'list my todos', or 'search notes for milk'.");
}
await client.close();
Try it yourself
Run the capstone once, then add a note and a to-do through the agent, and search for "milk". Then add a search tool of your own, or a resource that lists your to-dos.
Check
What does the capstone reuse?
The MCP server, the agent loop, guidance, and error handling.
What does the workspace server offer?
Tools for notes and to-dos, a workspace guidance resource, and a summarise-notes prompt.
Final checklist — Final Assessment
Tick each item only when you can show it working. This is the Final Assessment from Module 5.
What to do next
- Keep your workspace server and agent. Add one new tool of your own, for example a tool that returns the total number of notes and to-dos.
- Try the same workspace in the Python and TypeScript courses and compare the three versions.
- Next courses in this repo: Prompt Engineering, then Claude Code. Prompt Engineering builds on the prompts in Module 5. Claude Code builds on agents that can use tools on your computer.