
What MCP Is and How Messages Flow. The Model Context Protocol, usually shortened to MCP, is an open standard that lets AI applications connect to tools, data and prompts through one common interface. Before writing any code, this lecture builds the mental model that every later lecture relies on.
MCP has three roles. A host is the AI application the user works in, such as a desktop assistant or an editor. Inside the host, a client keeps a connection to one server. A server is a program that offers capabilities. Those capabilities come in three kinds: tools, which perform actions, resources, which provide data to read, and prompts, which are reusable templates.
Client and server talk using JSON-RPC, a simple format in which a request carries a method name, parameters and an identifier, and a response carries either a result or an error with the same identifier. Notifications are messages that expect no reply. We walk through a typical session. First comes initialization, in which both sides announce their protocol version and the features they support. Then the client lists what the server offers, and finally it calls a tool or reads a resource.
We also look at transports, which carry the messages. Standard input and output suit local servers started as child processes, while HTTP suits servers that run elsewhere.
By the end of this lecture you will be able to describe the roles, the message flow and the transports of MCP in your own words.
Setting Up a Python Environment for MCP. A dependable environment saves hours of confusion later, so this lecture sets one up carefully before we write any server code. The goal is a clean project that you can recreate on another machine.
We begin by checking the Python version, since the MCP Python SDK requires a reasonably recent release. Next we create a virtual environment, which keeps this project's packages separate from everything else on your computer, and we activate it. We then install the SDK with the command-line extras and confirm the installation by importing it and printing its version.
You will learn why a virtual environment matters. Without one, different projects fight over package versions, and a change made for one project can quietly break another. We also discuss recording dependencies in a requirements file or a project file, so that anyone can reproduce your setup with a single command.
We organize the project folder with a clear layout, a place for server files and a place for scripts that act as clients. We also talk briefly about editors, such as Visual Studio Code or PyCharm, and about selecting the right interpreter inside the editor, a step that trips up many beginners.
Finally, we run a tiny script to prove that everything works, which gives you a known good starting point.
By the end of this lecture you will have a working, reproducible Python environment ready for the rest of the course.
Your First Minimal MCP Server. This is the lecture in which you write a working MCP server. It is deliberately small, because the aim is to see every moving part clearly before adding features.
We use FastMCP, the high-level helper in the Python SDK that removes most of the boilerplate. The server begins with a single import and a single line that creates a named server object. The name is what clients display, so we discuss choosing one that makes sense to a person. We then add one very small tool, a function that greets someone by name, using a decorator that registers it with the server.
You will learn what the decorator does behind the scenes. It reads the function name, the type hints and the docstring, and uses them to publish the tool's name, description and input schema. This is why clear names and docstrings matter: they are what a model reads when it decides whether to use your tool.
Next we run the server. We explain what happens when a server starts over standard input and output, why it appears to wait silently and why printing ordinary text to standard output can corrupt the conversation. We also see how to stop it cleanly.
By the end of this lecture you will be able to write and start a minimal FastMCP server with one tool and explain how its description is generated.
Connecting a Client to Your Server. A server is only useful when a client talks to it. In this lecture you write a small Python client that starts your server, connects to it and exercises it, which lets you see the protocol working from the other side.
The client uses the SDK's session classes. We define the parameters that tell the client how to launch the server as a child process, open the standard input and output connection and create a client session on top of it. The first thing a session does is initialize, which is the handshake where both sides agree on a protocol version and exchange their capabilities.
After initialization, we ask the server to list its tools and print their names, descriptions and input schemas. Seeing the schema that the decorator generated makes the earlier lecture concrete. We then call the greeting tool with an argument and read the result, noticing that results arrive as a list of content items and not as a bare string.
You will learn why the asynchronous style is used. Connections involve waiting, and the SDK builds on Python's async features, so we explain the basic pattern of an async function and how to run it.
We finish by discussing common mistakes, such as a wrong path to the server file or an interpreter that lacks the SDK, and how to read the errors they produce.
By the end of this lecture you will be able to connect a Python client to a server, list its tools and call one successfully.
Defining Your First Tool with @mcp.tool. Tools are the heart of most MCP servers, because they are how a model takes action. This lecture focuses on writing a tool properly, not just getting one to run.
A tool is an ordinary Python function that you register with the decorator. We build a practical example, such as a function that adds numbers or converts a temperature, and walk through the pieces that matter. The function name becomes the tool name, so we choose one that states the action clearly. The docstring becomes the description, so we write it for a reader who has never seen the code, explaining what the tool does, what it expects and what it returns.
You will learn how to think about tool design. A good tool does one thing, has few parameters and returns a result that is easy to interpret. Tools that try to do many jobs confuse models and are harder to test. We discuss naming conventions, the value of predictable return types and why a tool should avoid hidden side effects.
We also discuss how a model decides to use a tool. It sees only the name, the description and the schema, so these are effectively your user interface. We compare a vague docstring with a precise one and consider how each might change the model's behavior.
Finally, we run the server and check the registration from a client.
By the end of this lecture you will be able to define a clear, well-described tool and verify that it is registered.
Typed Arguments and Input Schemas. Every tool tells clients what input it accepts, and that information comes from the type hints in your function. This lecture explains how Python types become machine-readable schemas and why you should take them seriously.
When you annotate a parameter as a string, an integer, a float or a boolean, the SDK converts that annotation into a JSON Schema, a standard way to describe data. Parameters with default values become optional, and parameters without defaults become required. We look at the generated schema for several functions and read it line by line, so that the connection between code and schema is obvious.
You will learn about richer types. Lists describe arrays, dictionaries describe objects, and optional types describe values that may be absent. Literal types restrict a value to a fixed set of choices, which is useful for things like units or sort orders. We also see how a data model class can describe a more complex argument with several named fields.
The schema matters in two ways. A model reads it to produce a valid call, and the server uses it to check incoming arguments. We compare calls that match the schema with calls that do not, and see how the failure is reported.
We also discuss writing helpful parameter descriptions and choosing defaults that are safe.
By the end of this lecture you will be able to use type hints to produce accurate input schemas and read them confidently.
Calling a Tool from the Client and Reading the Result. Defining a tool is only half of the story. This lecture shows the other half, in which a client calls the tool and interprets what comes back.
We extend the client script from earlier. After listing the tools, we call one by name and pass its arguments as a dictionary. The call returns a result object, and we examine it carefully. The main content is a list of items, each with a type such as text. We show how to pull out the text and convert it to a number or a structure when needed.
You will learn about the two ways a call can go wrong. A protocol-level problem, such as an unknown tool name, raises an error in the client. A problem inside the tool is different. The server reports it as a result that is flagged as an error, with a message that explains what happened. We practice both cases, check the error flag and print the message, so that your scripts handle them gracefully.
We also discuss designing the conversation between a model and a tool. A model reads the result as text, so results should be clear and compact. We compare a result that is a bare number with one that includes a short explanation, and discuss when each is better.
By the end of this lecture you will be able to call a tool from a client, interpret its result and handle both kinds of failure.
Argument Validation with Pydantic Constraints. Type hints say what kind of value a tool expects, but many tools need stricter rules. A percentage must lie between zero and one hundred, a name must not be empty and a code must follow a pattern. This lecture shows how to state such rules once and enforce them automatically.
The SDK uses Pydantic, a validation library, to check arguments. We use its Field helper to attach constraints to a parameter, such as minimum and maximum values, minimum and maximum lengths and regular expression patterns. We use the annotated form so that the constraint sits next to the type. These constraints also appear in the generated schema, which means a model can see the limits before it tries a call.
You will learn what happens when validation fails. The server rejects the call before your function runs and returns a clear message that names the offending parameter and the rule it broke. We try several bad inputs and read the messages, since a good message helps a model correct itself on the next attempt.
We also discuss where validation belongs. Declarative constraints handle simple rules well, while rules that involve several fields or outside information need extra code, which we meet later in the course.
Finally, we write tests that send valid and invalid values and confirm the outcome.
By the end of this lecture you will be able to enforce input rules declaratively and read the resulting errors.
Exposing a Static Resource. Tools perform actions, but a great deal of what an assistant needs is simply information. Resources are the part of MCP designed for that. This lecture introduces them by exposing a piece of fixed content.
A resource is read-only data identified by a URI. We create one with a decorator that takes the address, for example a custom scheme followed by a name, and attach a function that returns the content. The content might be a short text, such as a set of project guidelines or a configuration summary. We also set a name, a description and a media type, which help clients present the resource appropriately.
You will learn how resources differ from tools. A tool is something the model asks to run, while a resource is something the application or user chooses to load into context. This difference affects design. Resources should be focused and modest in size, because everything loaded takes up space in the model's context window.
We discuss choosing meaningful URIs, which are the stable names that clients rely on, and we talk about plain text versus structured formats such as JSON.
We also discuss caution. Content in a resource may be shown to a model, so it should never include secrets, and any text that came from outside should be treated as untrusted.
By the end of this lecture you will be able to publish a static resource with a clear address and description.
Listing Resources and Reading Contents. Publishing a resource is useful only if clients can find and read it. This lecture covers the client side of resources, using the Python session you already know.
First, the client asks the server to list its resources. Each entry carries a URI, a name, a description and a media type, and we print them in a tidy table. This discovery step matters because a client should never need to know addresses in advance. A server announces what it has, and the client reacts.
Next, the client reads one resource by its URI. The response contains a list of content items, each holding text or binary data along with its media type. We extract the text and display it, and we examine how binary content is represented. We practice reading a resource that exists and one that does not, and note how the error is reported.
You will learn how a host application might use resources. It could let the user pick one from a menu, attach several to a conversation or fetch them automatically when a task begins. We discuss the importance of keeping the amount of data modest and of telling users what is being loaded.
We also write a small automated check that lists the resources and confirms that the expected addresses are present.
By the end of this lecture you will be able to discover and read resources from a client reliably.
Dynamic Resources with URI Templates. Static resources cover fixed content, but many useful resources depend on a parameter, such as a note by identifier, a file by name or a record by number. Writing a separate resource for each would be impractical. URI templates solve the problem, and this lecture shows how to use them.
A URI template contains placeholders in curly braces, for example an address ending in a name placeholder. When you register a resource function with such a template, the SDK matches incoming addresses against the pattern, extracts the values and passes them to your function as arguments. The function then builds and returns the matching content.
We build a small example that serves greetings or notes by name, and walk through how a request for a particular address reaches the function. You will learn that the placeholder names must match the function's parameter names, and that the extracted values arrive as text, so any conversion to numbers is your job.
We discuss what should happen when a requested item does not exist. A clear error is better than an empty reply, and we practice raising one. We also discuss validation, because the value in an address comes from outside and must never be trusted blindly, especially when it is used to look up files or database rows.
Finally, we see how clients discover templates through a separate listing and how they fill them in.
By the end of this lecture you will be able to publish parameterized resources and handle missing items safely.
Reusable Prompt Templates. The third kind of MCP capability is the prompt. A prompt is a named, reusable template that a server offers so that users can start a task with well-crafted instructions instead of writing them from scratch each time. This lecture shows how to define and use them.
We register a prompt with a decorator. The function's parameters become the prompt's arguments, and the function returns the text, or a list of messages, that will be handed to the model. A typical example is a code review request that takes the code and a focus area, or a summary request that takes a document and a desired length. The function fills a template and returns it, so the wording lives on the server and can be improved in one place.
You will learn how prompts differ from tools and resources. Prompts are usually chosen by the user, often through a menu or a command, and they produce messages, not actions or data. We discuss writing templates that state the role, the task, the constraints and the expected format clearly.
On the client side, we list the available prompts, request one with arguments and inspect the messages that come back. We practice supplying a missing argument and observe the error.
We also discuss keeping prompts versioned and tested, and avoiding private details in their text.
By the end of this lecture you will be able to define a prompt template, retrieve it from a client and explain when to use one.
A Notes Store Server with In-Memory Storage. This lecture begins our move from toy examples to servers that manage real information. We build a notes server that lets a model add, list, read and delete short notes, keeping everything in memory.
The design starts with the data. We keep notes in a Python dictionary, with a numeric identifier as the key and a small record containing a title, the text and a timestamp. A counter supplies new identifiers. We then expose tools for each operation. An add tool accepts a title and text and returns the new identifier, a list tool returns a compact summary of all notes, a read tool returns one note and a delete tool removes one.
You will learn good habits for tools that change state. Each tool should state clearly what it did, for example by returning the identifier and a confirmation. Errors, such as an unknown identifier, should explain the problem and suggest a next step. We use validation constraints to keep titles and text within reasonable lengths.
We also discuss the limits of memory storage. Everything disappears when the server stops, and a server handling several clients could face concurrent changes. This is acceptable for learning, and it sets up the next lecture, where storage becomes durable.
We test the server from a client script, adding, reading and deleting notes.
By the end of this lecture you will be able to build a stateful server with several cooperating tools.
Persisting Notes to a JSON File. A notes server that forgets everything on restart is of limited use. In this lecture we make the storage durable by saving notes to a JSON file, a simple format that is easy to inspect and debug.
We refactor the previous design so that storage is separated from the tools. A small storage class loads the file when needed, offers methods to add, read, list and delete notes and writes the changes back. The tools then call those methods and do nothing else. This separation makes the code easier to test and to change, for example if you later switch to a database.
You will learn the practical details of file handling. We create the file if it does not exist, handle an empty or damaged file with a clear message and choose a location that does not depend on the current directory. We also discuss writing safely. Writing to a temporary file and then replacing the original prevents a crash from leaving half-written data behind.
We cover text encoding, formatting the file so that humans can read it and keeping the identifiers consistent after deletions. We also discuss why a simple lock or a single-writer approach is sensible if more than one request may arrive at once.
We finish by stopping and restarting the server and confirming that the notes survive.
By the end of this lecture you will be able to persist server data safely to a JSON file and keep storage logic separate from tools.
A Safe File Browser with Path Validation. Letting a model read files is powerful, and it is also one of the easiest ways to create a security problem. In this lecture we build a file browser tool that can only reach files inside one approved folder, and we learn why that restriction takes care to enforce.
The central risk is path traversal. A caller might supply a path containing parent-directory segments, an absolute path or a symbolic link that leads outside the approved folder. A naive tool that joins the text to a base folder would happily follow it. We use a safer approach. We resolve the full real path of the requested item, resolve the real path of the base folder and confirm that the first is truly inside the second. Anything else is rejected with a plain error that reveals nothing about the rest of the file system.
We build two tools: one that lists a folder's contents and one that reads a text file. We add limits too, such as a maximum file size and a maximum number of entries, because unbounded output can overwhelm a model's context.
You will learn to test the protection with a set of deliberately awkward paths, using only your own harmless sample folder, and to confirm that each is refused.
By the end of this lecture you will be able to build a file tool that stays inside its boundary and explain why each check is needed.
Querying a SQLite Database from a Tool. Many real assistants need to answer questions from structured data. In this lecture we connect a tool to SQLite, the lightweight database that ships with Python, and learn how to do it safely.
We begin by creating a small sample database with a table of products, including names, categories and prices, filled with invented data. We then write tools that retrieve information, such as listing products in a category or finding one by identifier. Each tool opens a connection, runs a query and returns a compact, readable result.
The most important lesson is parameterized queries. Instead of building a command by pasting user text into a string, we write placeholders and pass the values separately, so the database treats them strictly as data. We compare the two approaches and see why only the second is safe. We also discuss opening the database in read-only mode where possible, which means that even a mistake cannot change anything.
We add practical limits, including a maximum number of rows returned and a clear message when nothing matches. We also discuss returning only the columns that are needed, closing connections reliably and handling a missing database file with a helpful error.
Finally, we test the tools from a client, including queries that match nothing and values that would be awkward in a carelessly built command.
By the end of this lecture you will be able to expose database queries through safe, narrow tools.
Async Tools: Writing Your First async def Tool. Tools that wait for something, such as a network response, should not block the whole server while they wait. Python's asynchronous features allow a server to handle other work in the meantime. This lecture shows how to write tools in that style.
We begin with a simple explanation of asynchronous code. A function declared with the async keyword can pause at an await point, letting other tasks run until the awaited operation finishes. We contrast this with an ordinary blocking function that holds everything up. We demonstrate the difference with a tool that simulates a slow operation using an asynchronous sleep.
You will learn how the SDK treats async tools. You register them with the same decorator, and the server runs them inside its event loop. The client does not need to know which style a tool uses. We write a tool that waits briefly and returns a result, then call several of them to see that they can overlap.
We also discuss common mistakes. Calling a blocking function inside an async tool defeats the purpose, forgetting to await a call produces a confusing object instead of a result and mixing styles carelessly can cause errors. We discuss when plain functions are perfectly fine.
Finally, we cover timeouts, which keep a slow operation from waiting forever.
By the end of this lecture you will be able to write, register and test async tools and explain when to use them.
Fetching JSON with httpx and a Mock Transport. Many useful tools call a web API. This lecture shows how to do that with httpx, a modern Python HTTP library, and how to test the code without depending on any real service, which keeps your learning free, fast and repeatable.
We start with a tool that sends a request and reads a JSON response. We use an asynchronous client, set a sensible timeout and check the status before using the body. We then parse the JSON and return a short, useful summary instead of dumping the entire payload into the model's context.
The key technique is the mock transport. httpx lets you supply a replacement transport that answers requests from a function you write, so no network traffic occurs. We write a handler that returns prepared responses for particular addresses and use it to run the tool. This makes the behavior predictable and lets us simulate success, empty results and errors on demand.
You will learn to design the tool so that the client can be swapped. We pass the client in, or create it through a small factory, so that tests can inject the mock. We discuss why this separation also makes real services easier to replace.
We also cover reading query parameters, headers and response fields, and returning only the fields the model needs.
By the end of this lecture you will be able to call a JSON API from a tool and test it entirely offline.
Keeping API Keys Out of Your Code. Real services often require a key, and how you handle it says a great deal about the quality of your engineering. This lecture explains how to keep secrets out of source code and out of places where they can leak.
The rule is simple: never write a key into a file that you commit, share or publish. Keys left in code end up in version control history, screenshots, logs and tutorials, and removing them afterward is difficult. Instead, we read the key from an environment variable when the server starts, and we fail early with a clear message if it is missing.
We practice setting environment variables in a terminal session and in a local settings file that is excluded from version control. We create a sample settings file that lists the variable names with placeholder values, so that colleagues know what to provide. We discuss loading such a file with a helper library and why the real file must appear in the ignore list.
You will learn about the other leaks to avoid. Do not print the key in log messages, do not include it in error text, and do not return it from a tool, since a model could repeat it. We show how to mask a key when you need to display it.
For this course, the exercises use a mock transport and a dummy key, so no paid service is needed.
By the end of this lecture you will be able to load and protect an API key using environment variables.
Turning HTTP Failures into Clear Tool Errors. Web calls fail in many ordinary ways. The service may be down, the network may be slow, the key may be wrong or the item may not exist. A tool that simply crashes with a stack trace helps nobody. This lecture teaches you to turn each failure into a clear, useful message.
We start by classifying the failures. A timeout or connection problem means the service could not be reached. A response with a client error code means the request was wrong, such as a missing item or a rejected key. A response with a server error code means the service itself is struggling. A malformed body means the reply could not be understood.
For each category, we write a response that tells the model what happened in plain language, whether trying again is sensible and what to do next. For example, a missing item suggests checking the identifier, while a temporary server problem suggests waiting. We raise a tool error with that message so that the server marks the result as an error.
You will learn what to leave out. Error text should not reveal keys, internal addresses or raw traces. We also add a small, bounded retry for temporary problems.
Using the mock transport from the previous lecture, we simulate every failure and write tests confirming the message for each.
By the end of this lecture you will be able to convert HTTP problems into safe and actionable tool errors.
Serving Over Streamable HTTP. Until now our servers have run as child processes that talk through standard input and output. That is perfect for local tools, but a server that several people or applications share needs to be reachable over a network. Streamable HTTP is the MCP transport designed for that, and this lecture shows how to use it.
With FastMCP, switching transports is a small change. Instead of starting the server in standard input and output mode, we start it with the HTTP transport and a host and port. The server then listens on an address, and clients connect to a path on it. We run it, watch it start and confirm from a terminal that it responds.
You will learn how the transport works. Clients send messages as HTTP requests, and the server can reply with a single response or stream several messages back over the same connection, which is useful for progress updates and long operations. We discuss sessions, in which the server identifies a client across requests.
We also discuss practical points. Binding to the local machine only is the safe default for development, and exposing a server more widely requires authentication, which we add later in the course. We talk about choosing ports, avoiding clashes and reading start-up messages.
Finally, we compare the two transports and decide which fits each situation.
By the end of this lecture you will be able to run a server over Streamable HTTP and explain when to choose it.
Connecting a Client Over HTTP. A server that listens on a network address needs a client that can reach it. In this lecture we write a Python client that connects to the HTTP server from the previous lecture and does everything our earlier client did.
The structure is familiar, but the connection step changes. Instead of launching a child process, the client opens a streamable HTTP connection to the server's address. It then creates a session on top of that connection, initializes it and uses it in the same way as before. This is one of the pleasant features of MCP: once the session exists, the code for listing tools, calling them and reading resources is identical, no matter which transport carried the messages.
We start the server in one terminal and the client in another, which clarifies that they are separate programs. We list the tools, call one and read a resource, confirming the results.
You will learn to handle the new failure modes that networks introduce. The server may not be running, the address may be wrong or the connection may drop. We write clear messages for each and add a timeout so the client does not wait forever.
We also look at the traffic by enabling verbose logging, which shows the requests and responses and makes later debugging easier.
By the end of this lecture you will be able to connect to a remote-style server, run the same operations and diagnose connection problems.
In-Memory Testing with a Client Session. Starting a server in one terminal and a client in another is fine for exploration, but it is a poor way to test. Tests should be fast, automatic and independent of ports or processes. This lecture shows how to test a server entirely in memory.
The SDK supports connecting a client session directly to a server object inside the same Python process. No child process starts and no network port opens. The client and server exchange messages through in-memory streams, so tests run in milliseconds and cannot collide with anything else on your machine.
We write a test helper that creates the connection, initializes the session and hands it to the test. We then write tests that list the tools and check their names, call a tool with valid input and verify the result, call it with invalid input and confirm the error and read resources and prompts. We use the standard test framework with its support for asynchronous tests.
You will learn how to structure tests so they stay readable. A shared fixture creates the session, each test focuses on one behavior and names describe what is being checked. We discuss testing the unhappy paths too, because that is where most real problems live.
We also discuss resetting any stored data between tests, so that one test cannot affect another.
By the end of this lecture you will be able to write fast, reliable, in-memory tests for your MCP servers.
Debugging with Logging and the MCP Inspector. Sooner or later a server will misbehave, and you will need to see what is happening inside it. This lecture introduces two tools for that purpose: careful logging and the MCP Inspector.
Logging comes with a special rule for servers that use standard input and output. That channel carries the protocol messages, so printing ordinary text to it corrupts the conversation. Instead, we configure Python's logging module to write to standard error or to a file. We choose sensible levels, write messages that say what happened and include useful details, such as the tool name and the time taken, without recording secrets.
The MCP Inspector is an interactive tool that connects to your server and shows its tools, resources and prompts in a browser. You can fill in arguments, call a tool and see the exact request and response. We start the server through the Inspector, list the capabilities and try calls, including some that fail, which is an excellent way to see how errors appear.
You will learn a general debugging routine. Reproduce the problem with the smallest input, check the logs, inspect the messages, then form a guess and test it. We also cover the most common problems, such as a wrong interpreter, a missing dependency, a bad path and output written to the wrong stream.
By the end of this lecture you will be able to diagnose server problems using logs and the Inspector.
Lifespan State: Shared Resources Across a Server's Life. Some resources should be created once when a server starts and cleaned up when it stops, such as a database connection, an HTTP client or a loaded configuration. Creating them inside every tool call wastes time and can leak resources. The lifespan feature handles this properly, and this lecture explains it.
A lifespan is an asynchronous context manager that you supply when creating the server. The code before its yield point runs at start-up, and the code after it runs at shutdown. Whatever you yield becomes the shared state available to the server. We build one that opens a database connection and an HTTP client at start-up, yields them in a small data object and closes them at shutdown.
You will learn why this pattern is better than global variables. Start-up and shutdown are explicit, failures during start-up stop the server cleanly and tests can substitute different resources easily. Typed state objects also give your editor something to check.
We discuss what belongs in lifespan state. Long-lived clients, connection pools, loaded models or indexes, caches and configuration are good candidates, while per-request data is not. We also discuss making shutdown reliable, using try and finally blocks so that cleanup always runs.
We run the server, confirm that resources are created once and observe the cleanup message when the server stops.
By the end of this lecture you will be able to manage shared resources through a lifespan function.
Reading Lifespan State Through the Context Object. Creating shared state is only useful if tools can reach it. This lecture shows how a tool receives the Context object, and how it uses that object to read the state created at start-up.
When a tool declares a parameter annotated with the context type, the SDK passes in a context for the current request. That parameter does not appear in the tool's input schema, because the model does not supply it. Through the context, the tool can reach the request's session and the lifespan state that the server created, for example the database connection or the HTTP client.
We rewrite earlier tools to use shared state. A query tool now takes the connection from the context instead of opening its own, and an API tool uses the shared client. We observe the improvement in speed and the tidier code.
You will learn about typing. The context is generic over the state type, so annotating it correctly lets your editor suggest the attributes and warn about mistakes. We also see how to build a context-friendly test, supplying a test state with an in-memory database.
We discuss care with shared resources. Because several requests may run at once, shared objects must be safe for that use, and tools must not change shared state carelessly.
Finally, we list what else the context offers, which sets up the next lectures on logging and progress.
By the end of this lecture you will be able to access lifespan state from tools through the context.
Sending Log Messages to the Client. A server sometimes needs to tell the client what it is doing, not through the final result but along the way. MCP supports this with log messages that travel over the protocol, and this lecture shows how to send and receive them.
Through the context object, a tool can send messages at several levels, such as debug, info, warning and error. Each message carries text and may carry structured data. These are different from the server's own log file. They are delivered to the client, which can show them to the user or record them. We add messages to a tool that processes several items, reporting what it is doing at each stage.
You will learn how the client receives them. The client can register a callback that is invoked for each message, and it can also request a minimum level, so that noisy debug output is not sent unless wanted. We write a client that prints messages with a level label as they arrive.
We discuss good practice. Messages should be useful and concise, should never include secrets or personal data and should not be sent in tight loops, since each one is a network message. We also compare these messages with ordinary logging and decide when to use each.
We finish by testing that the expected messages arrive in the right order.
By the end of this lecture you will be able to send and receive log messages through the protocol.
Reporting Progress During Long Operations. Some operations take long enough that a user wonders whether anything is happening. A tool that processes a large set of items, downloads a file or runs a sequence of steps should be able to say how far along it is. MCP provides progress notifications for exactly this purpose.
Through the context object, a tool reports progress by giving the amount completed, optionally the total and an optional message. We write a tool that handles a list of items one by one, pausing briefly to simulate work, and reports after each. A total allows a client to display a percentage, while a message can describe the current step.
On the client side, the call can include a progress callback. The client receives each update as it arrives and can draw a progress bar or print a line. We write a client that does so, and we run the combination to watch the progress move.
You will learn why progress works best with streaming transports, where updates can flow while the call is still running. We also discuss limits. Report at sensible intervals, not on every tiny step, keep the numbers consistent and make sure the final update matches completion.
We discuss related concerns, including timeouts, cancellation and what a tool should do if the client disconnects midway.
By the end of this lecture you will be able to report progress from long-running tools and display it in a client.
Returning Structured Output from Tools. So far, our tools have mostly returned text. Text is flexible, but programs and models often benefit from data with a predictable shape. This lecture covers structured output, in which a tool returns typed data that is described by a schema.
When a tool's return annotation is a data model, a typed dictionary or another structured type, the SDK can generate an output schema and return the result as structured content, alongside a text version for clients that need it. We define a model with named fields, such as a name, a score and a list of tags, return an instance from a tool and inspect what the client receives.
You will learn the benefits. Structured results are easier to process in code, since you read fields instead of parsing text. They are also easier to validate, because the server checks that the result matches the declared shape. A model can rely on the schema to know what it will get back.
We discuss design choices. Keep the structure flat where possible, name fields clearly and include units or explanations where the meaning could be ambiguous. Return only what is useful, because large structures consume context.
We also write client code that reads the structured content directly and tests that confirm the shape, including a case in which a tool returns something that does not match.
By the end of this lecture you will be able to design tools that return typed, validated structures.
Rejecting Bad Input with Custom Validators. Declarative constraints handle many rules, but some checks need more logic. A start date must precede an end date, a file name must not contain certain characters, or a code must pass a checksum. This lecture shows how to write custom validators that enforce such rules.
Pydantic offers validators, functions that run when a model is built and can inspect or transform values. We define an argument model with several fields and attach validators to individual fields and to the model as a whole. A field validator checks one value, for example that a name contains no control characters. A model validator checks relationships between fields, such as the date order.
You will learn how failures surface. A validator raises an error with a clear message, and the server returns it to the caller as an invalid-input result. We write messages that explain what was wrong and what would be acceptable, since a model can use that information to correct its next call.
We also discuss normalization. A validator can tidy input, such as trimming whitespace or converting to lowercase, so that the tool code receives consistent values. We caution against hidden changes that would surprise the caller.
Finally, we write tests with valid, invalid and borderline values, including empty strings and extremely long ones, to confirm that the rules hold.
By the end of this lecture you will be able to write custom validators that reject unsafe or inconsistent input clearly.
Loading Secrets from the Environment Safely. Earlier we kept an API key out of source code. This lecture widens the idea into a complete approach for configuration and secrets in a server, including how to organize settings, validate them at start-up and prevent accidental disclosure.
We begin by separating ordinary settings, such as a port, a base address or a timeout, from secrets, such as keys, tokens and passwords. Both come from the environment, but secrets deserve extra care. We build a small settings class that reads every value in one place, converts types, applies sensible defaults to ordinary settings and refuses to start if a required secret is missing. Failing early with a clear message is far better than failing later in the middle of a request.
You will learn to keep secrets contained. We store them in a dedicated type that hides its value when printed, so an accidental log line shows a placeholder, not the secret. We avoid placing secrets in tool arguments, results, error messages or resource contents, because anything a tool returns may reach a model and a user.
We discuss local development using a settings file that is excluded from version control, with a sample file listing names only. We also touch on production practices, such as secret managers, rotation and separate secrets for each environment.
We test that missing values are caught and that printed settings never reveal a secret.
By the end of this lecture you will be able to load, validate and protect configuration and secrets.
Protecting a Server with a Bearer Token Check. A server reachable over a network must not accept requests from anyone who happens to find its address. In this lecture we add a simple but effective protection: a bearer token that every request must present.
A bearer token is a secret string sent in the authorization header of each HTTP request. The server compares it with the expected value and refuses the request when it is missing or wrong. We implement the check as a layer in front of the MCP application, so that unauthorized requests are rejected before any tool code runs. The response uses the standard unauthorized status and a short message that reveals nothing useful.
You will learn several important details. Compare tokens using a constant-time comparison, which avoids leaking information through timing differences. Load the expected token from the environment, never from code. Do not log the token or echo it back. Always use encrypted connections in any real deployment, because a token sent in clear text can be read by anyone on the path.
On the client side, we supply the header when connecting and test three cases: a correct token, a wrong token and no token at all.
We also discuss the limits of this approach. A single shared token does not identify individual users or restrict what each may do, and fuller solutions use standard authorization flows, which we mention briefly.
By the end of this lecture you will be able to protect an HTTP server with a bearer token and test the protection.
Limiting Calls with a Sliding-Window Rate Limiter. Even legitimate clients can overwhelm a server, whether through a bug, a loop or an overeager model calling a tool repeatedly. A rate limiter protects your server, your costs and any service you call on its behalf. This lecture builds a sliding-window limiter from scratch.
The idea is simple. For each caller, we remember the times of recent requests. When a new request arrives, we discard the times that are older than the window, for example sixty seconds, count what remains and allow the request only if the count is below the limit. Because the window moves with time, it avoids the bursts at boundaries that fixed-window schemes allow.
We implement it as a small class using a double-ended queue per caller, and we make time injectable so that tests can control it without waiting. We apply it as a check at the start of a tool, or as a decorator that wraps several tools, and we return a clear error that states the limit and when the caller may try again.
You will learn to choose limits thoughtfully. Different tools deserve different limits, with expensive ones stricter. We also discuss identifying callers, which may rely on a token or a session, and cleaning up old entries so memory does not grow forever.
We write tests that exceed the limit, wait for the window to pass and confirm recovery.
By the end of this lecture you will be able to implement and test a sliding-window rate limiter.
Spawning a Server from a Python Client. This lecture begins the course's final stretch, in which we connect the servers we built to real clients and prepare them for others to use. We start with the most direct approach: a Python client that starts a server itself.
When a client uses the standard input and output transport, it is responsible for launching the server as a child process. We define the launch parameters, which name the command, its arguments and any environment variables to pass. We discuss using the same interpreter that runs the client, so that the server sees the same installed packages, and passing an absolute path to the server file so that the result does not depend on the current directory.
You will learn how the lifetime works. The server starts when the connection opens and ends when it closes, and we use context managers so that cleanup happens even when an error occurs. We explain what happens to the server's error output, which is useful for diagnosing start-up problems.
We also discuss passing configuration safely. Environment variables supplied in the launch parameters reach the server, which is how a client can provide a key or a data folder. We avoid placing real secrets in the client's source.
Finally, we handle failures such as a server that exits immediately, and we add a start-up timeout and a clear error message.
By the end of this lecture you will be able to launch and manage a server process from a Python client.
Calling Tools and Reading Results in a Client Script. With a connection in place, we can write a complete client script that does useful work. In this lecture we build one that discovers a server's tools, calls several of them in sequence and presents the results in a clean, human-friendly way.
The script begins by listing the tools and checking that the ones it needs exist, which makes failures obvious and early. It then calls the tools, passing arguments built from simple inputs such as command-line options. We write a small helper that wraps a call, checks the error flag, extracts the text or structured content and returns a Python value. Using the helper keeps the main script short and readable.
You will learn to handle results of different kinds. Text items are easy, structured content can be read as a dictionary and some results contain several items that must be combined. We also practice reading resources and prompts in the same script, so that it demonstrates all three capabilities.
We discuss robustness. Network and process problems can occur, so we catch the relevant exceptions, print helpful messages and exit with a meaningful status code. We add a summary at the end that shows what was called and whether each call succeeded.
We also discuss how this script resembles the work a host application does on behalf of a model, which clarifies the roles in the system.
By the end of this lecture you will be able to write a reliable client script that discovers and uses server capabilities.
Registering a Server with a Desktop AI Client. A server becomes truly valuable when a real AI application can use it. In this lecture we register a server with a desktop AI client, which lets a person ask questions in natural language while the assistant calls our tools behind the scenes.
Desktop clients that support MCP read a configuration file that lists servers. Each entry has a name, the command that starts the server, its arguments and any environment variables. We locate the configuration file for the operating system, add an entry for our server and explain each field. We emphasize using absolute paths and the full path to the right Python interpreter, since a desktop application does not inherit your terminal's environment.
You will learn to restart the client so that it reads the new configuration, to confirm that the server appears and to try the tools through a conversation. We discuss how the client asks permission before running a tool, and why that confirmation is a useful safeguard.
We cover troubleshooting. If the server does not appear, check that the configuration is valid JSON, that the paths are correct and that the server starts when you run the same command manually. Client logs usually show the reason.
We also discuss secrets in configuration files and the sensible habit of granting only the access that the server needs.
By the end of this lecture you will be able to register a server with a desktop AI client and troubleshoot common problems.
Packaging a Server with an Entry Point. A server that lives in a single file on your machine is hard to share. Packaging turns it into something others can install and run with one command. This lecture shows how to package a server using standard Python tools.
We begin with the project layout. Server code goes into a package directory, and a project file at the top describes the package: its name, version, description, required Python version and dependencies, including the MCP SDK. We discuss choosing version constraints that are neither too strict nor too loose.
The central feature is the entry point. In the project file, we declare a console script that names a function in the package. When the package is installed, the installer creates a command with that name. Running the command starts the server, so users no longer need to know where the files are or which interpreter to use. We write a small main function that parses options, such as a transport choice, and starts the server.
You will learn to build the package, install it into a fresh virtual environment and confirm that the command works. We also discuss including a short readme, a license and a version number, and why you should test the installed package, not only the source folder.
Finally, we update the desktop client configuration to use the new command.
By the end of this lecture you will be able to package a server with an entry point that others can install and run.
Composing Tools, Resources, and Prompts in One Server. The capstone begins here. Over the course we built tools, resources and prompts separately. In this lecture we combine them into one coherent assistant server with a clear purpose and a tidy structure.
We start by planning. We decide what the assistant will do, for example help a user manage notes, look up product data and fetch information from an API, and we list the capabilities we need in each category. Tools perform actions such as adding a note or querying the database. Resources expose read-only content such as a guide or a note by address. Prompts offer ready-made tasks such as a weekly summary request.
You will learn how to organize the code. Instead of one enormous file, we split it into modules for storage, tools, resources, prompts and configuration, and a main module that assembles them. We use the lifespan feature to create shared resources once, and we pass them to the tools through the context. We apply earlier lessons on validation, clear errors and safe file and database access.
We discuss naming and descriptions, because with many capabilities a model's choices depend on how clearly each one is described. We also review the whole server for overlap, gaps and risky operations.
We run it, inspect it with the Inspector and connect a client.
By the end of this lecture you will be able to assemble a multi-capability server with a clean architecture.
Wiring an External API Tool with a Mock Transport. The capstone assistant needs one capability that reaches beyond its own data: a tool that gets information from an external web API. In this lecture we add it, applying everything we learned about asynchronous calls, secrets and errors, and we keep the whole thing testable by using a mock transport.
We design the tool first. It takes a few validated arguments, such as a city name, and returns a concise, structured result, such as a short weather summary. We create the HTTP client once during the server's lifespan, with a timeout and a base address taken from configuration, and the tool obtains it through the context. The API key comes from the environment and is attached to each request without ever appearing in logs or results.
The mock transport is the key to testing. In the test setup, we create the client with a transport that returns prepared responses, so no network traffic occurs. We script a successful reply, an item that is not found, a rate-limit response and a server failure, and confirm that the tool turns each into the right result or a clear error.
You will learn to make the production and test configurations differ only in the transport, keeping the rest of the code identical.
We also add progress or log messages where they help and review the tool's description for clarity.
By the end of this lecture you will be able to integrate an external API tool and test it entirely offline.
Testing the Capstone with a Single Assert-Based Test Script. A project is not finished until you can show that it works, and ideally show it with one command. In this final lecture we write a single test script that exercises the whole capstone assistant from the outside, as a real client would.
The script connects to the server in memory and runs a sequence of checks using plain assert statements. It confirms that the expected tools, resources and prompts are listed. It adds, reads and deletes a note and checks each result. It queries the database and verifies the rows. It calls the external API tool, using the mock transport, and checks both success and failure cases. It requests a prompt with arguments and inspects the messages. It also confirms that invalid input is rejected and that the rate limiter and the token check behave as designed.
You will learn how to structure the script so that failures are easy to understand. Each check has a descriptive message, the script reports which step failed and the process exits with a nonzero status when anything goes wrong, which makes it suitable for automation.
We discuss resetting state between runs, using temporary files and databases and keeping the script fast. We also discuss what the script cannot prove, and what you would add next.
We finish by reviewing the course and suggesting directions for further projects.
By the end of this lecture you will be able to verify a complete MCP server with one repeatable test script.
This course contains the use of artificial intelligence.
Unlock the power of Model Context Protocol (MCP) and learn how to build intelligent, connected, and secure AI applications with MCP Server Development with Python: Hands-On Projects. This practical, project-based course takes you from understanding MCP fundamentals to developing, testing, securing, and packaging custom MCP servers using Python.
As Generative AI, Agentic AI, and Large Language Models (LLMs) continue to transform software development, connecting AI models with external tools, databases, APIs, and resources is becoming an essential technical skill. Model Context Protocol provides a standardized approach to connecting AI applications with external capabilities, enabling more powerful and interactive AI systems.
This course focuses on hands-on Python development, allowing you to learn by writing code, building projects, experimenting with server capabilities, and solving practical integration challenges.
Begin your journey by exploring MCP architecture, client-server communication, JSON-RPC, Python environment configuration, and the MCP Python SDK. Build your first MCP server using FastMCP and establish communication between MCP clients and servers.
Progress into MCP tool development, where you will create custom tools, define typed arguments, generate JSON schemas, validate inputs using Pydantic, and return structured responses. Discover how to expose static resources, dynamic resources, URI templates, and reusable prompt templates to AI applications.
Build practical MCP servers that interact with local data, including notes management systems, JSON file storage, secure file browsers, and SQLite databases. Develop skills in database integration, persistent storage, parameterized SQL queries, and secure file handling.
Explore API integration, REST APIs, asynchronous programming, Python asyncio, HTTPX, mock transports, API key management, JSON response processing, and robust error handling. Learn how to develop and test API-connected MCP tools without relying on paid external services.
Strengthen your development skills by working with stdio transport, Streamable HTTP, automated testing, server logging, debugging, and MCP Inspector. Discover advanced MCP capabilities such as server lifecycle management, lifespan state, context objects, progress reporting, and structured tool output.
Security is an essential part of modern AI application development. Learn practical approaches to MCP security, custom input validation, bearer token checks, secret management, rate limiting, path traversal protection, and secure server configuration.
You will also explore MCP client development, desktop AI client configuration, Python packaging, server distribution, and reusable integration patterns. These skills provide a foundation for AI agent development, AI automation, intelligent assistants, and enterprise AI integration.
Throughout the course, you will gain practical experience with:
Model Context Protocol (MCP)
Python Programming and FastMCP
Agentic AI and AI Agent Integration
Generative AI Application Development
MCP Tools, Resources, and Prompts
JSON-RPC and API Development
Asynchronous Python Programming
MCP Authentication and Security
Database and File System Integration
Software Testing and Debugging
LLM Tool Integration
AI Infrastructure Development
With 10 comprehensive modules and 40 practical lessons, this course is designed for Python developers, AI engineers, software developers, backend engineers, solution architects, automation specialists, and technology professionals exploring the rapidly evolving AI ecosystem.
Complete your learning journey by building a multi-tool MCP assistant server, combining tools, resources, prompts, API integration, structured responses, and automated end-to-end testing into a comprehensive capstone project.
Move beyond theoretical AI concepts and start developing the infrastructure that enables intelligent applications to interact with real-world systems.
Enroll today and begin your hands-on journey into MCP Server Development, Python, Agentic AI, and AI-powered software engineering.