Build an MCP Server and Client

A working lending-library server and client in a few dozen lines, then the habits that make it safe to share.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

An MCP server is an ordinary program that registers tools, resources and prompts; an SDK handles the protocol. In this tutorial you build one in Python, connect a client over two transports, write an automated test, inspect it from the command line and see the TypeScript equivalent.

What you will learn: setup, server code, client code, testing, MCP Inspector, common faults and what to add before others rely on it.
Prerequisites: What Is MCP? Hosts, Clients, Servers and Capabilities, a terminal and basic Python. Node.js is needed for Inspector and the TypeScript section.

Beginner Your first server and client

Set up

The examples use version 2 of the official Python SDK and were run before publication with release 2.3.0. Version 2 changed names from version 1, so older tutorials will not match.

mkdir library-mcp
cd library-mcp
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install "mcp>=2,<3"
client.pystdio or HTTP
server.pyMCP SDK handles messages
Library dataAn in-memory dictionary
Two tools: search and reserve. One resource: lending rules. One prompt: recommendation.

Build the server in Python

Save this as server.py.

"""A small MCP server. Tested with the official Python SDK, version 2."""
import sys

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

BOOKS = {
    "B1": {"title": "Designing Agents", "available": True},
    "B2": {"title": "Testing in Practice", "available": False},
}

mcp = MCPServer("library")


@mcp.tool()
def search_books(query: str) -> list[dict]:
    """Find books whose title contains the query. Returns id, title, availability."""
    q = query.strip().lower()
    if not q:
        raise ToolError("query must not be empty")
    return [{"id": key, **book} for key, book in BOOKS.items()
            if q in book["title"].lower()]


@mcp.tool()
def reserve_book(book_id: str) -> str:
    """Reserve one available book by its id. Changes library records."""
    book = BOOKS.get(book_id)
    if book is None:
        raise ToolError(f"no book with id {book_id}")
    if not book["available"]:
        raise ToolError(f"{book_id} is already on loan")
    book["available"] = False
    print(f"reserved {book_id}", file=sys.stderr)   # never print() to stdout
    return f"Reserved {book['title']}"


@mcp.resource("library://rules")
def rules() -> str:
    """The lending rules."""
    return "Loans last 21 days. One renewal is allowed."


@mcp.prompt()
def recommend(topic: str) -> str:
    """Ask for a reading recommendation."""
    return f"Search the library for books about {topic} and recommend one."


if __name__ == "__main__":
    transport = "streamable-http" if "--http" in sys.argv else "stdio"
    mcp.run(transport)

Read it from the top

PieceWhat it does
MCPServer("library")Creates the server and names it
@mcp.tool()Registers a function as a tool; the docstring becomes its description
Type hintsGenerate the input and output schemas and are used to check arguments
ToolErrorReturns an expected failure with your message for the model
@mcp.resource(...)Publishes readable data at a URI
@mcp.prompt()Publishes a reusable prompt template
mcp.run(transport)Serves over standard input and output, or HTTP
Two mistakes that cost an afternoon
  • Printing to standard output in a stdio server corrupts the message stream. Send logs to standard error.
  • Raising an ordinary exception hides your text from the model in SDK version 2: the caller only learns that the tool failed, and the traceback stays on the server. Use ToolError for messages meant to be read.

Build the client

A real host connects your server to a model. A small client lets you exercise it without one. Save this as client.py in the same folder.

"""A minimal MCP client. Pass a URL to use HTTP; otherwise it starts server.py."""
import asyncio
import sys

from mcp import Client, StdioServerParameters


async def main(target):
    async with Client(target) as client:
        tools = await client.list_tools()
        print("tools:", [t.name for t in tools.tools])

        found = await client.call_tool("search_books", {"query": "agents"})
        print("search:", found.structured_content)

        first = await client.call_tool("reserve_book", {"book_id": "B1"})
        print("reserve:", first.is_error, first.content[0].text)

        again = await client.call_tool("reserve_book", {"book_id": "B1"})
        print("again:", again.is_error, again.content[0].text)

        rules = await client.read_resource("library://rules")
        print("rules:", rules.contents[0].text)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        target = sys.argv[1]                                  # an HTTP URL
    else:
        target = StdioServerParameters(command=sys.executable, args=["server.py"])
    asyncio.run(main(target))

Run python client.py. The client starts the server as a subprocess and prints (the server's own log line goes to standard error and is not shown here):

tools: ['search_books', 'reserve_book']
search: {'result': [{'id': 'B1', 'title': 'Designing Agents', 'available': True}]}
reserve: False Reserved Designing Agents
again: True Error executing tool reserve_book: B1 is already on loan
rules: Loans last 21 days. One renewal is allowed.

The first reservation succeeds. The second returns an error result, flagged True, with the reason. The connection stays healthy, and a model could now suggest another book.

What the client is doing

The client code is short because the SDK does the protocol work, but each line stands for an exchange you can reason about.

Client lineWhat happensWhat a host would add
async with Client(target)Opens the transport and settles which protocol revision to useConsent to start a program or connect to an address
list_tools()Fetches names, descriptions and schemasChoosing which tools the model is offered
call_tool(...)Sends a name and arguments; receives a resultPolicy checks and approval before sending
read_resource(...)Reads data by its URIDeciding whether it belongs in the context

Always check is_error before treating content as a successful answer. A failed call still returns readable text, and code that ignores the flag will happily pass an error message along as if it were data.

Adding a model

To turn this client into a small agent, pass the listed tools to your model API, converting each name, description and input schema to that API's tool format. When the model requests a tool, call call_tool, return the result to the model and repeat until it answers. Add a step limit and an approval prompt before reserve_book. The loop itself is the one in The Agent Loop: Observe, Reason, Plan, Act, Reflect; only the source of the tools has changed.

Intermediate HTTP, testing and inspection

Serve over HTTP

Start the server in one terminal:

python server.py --http

Then connect from another by passing the address:

python client.py http://127.0.0.1:8000/mcp

You should see the same five lines against a freshly started server. Only the target changed; the client calls are identical. State now lives as long as the server process, so running the client twice will report the book as already on loan the first time too.

Local only for now

This server has no authentication. Keep it bound to your own machine. Before it listens on a network, add authorization, check the Origin header and put it behind encrypted connections: see MCP Deployment and Production Readiness.

Test the server automatically

The SDK's client also accepts the server object itself and talks to it in the same process. No subprocess, no ports, fast tests. Save as test_server.py.

import asyncio

from mcp import Client

from server import mcp


async def check():
    async with Client(mcp) as client:                # in-process, no network
        names = {t.name for t in (await client.list_tools()).tools}
        assert names == {"search_books", "reserve_book"}
        bad = await client.call_tool("reserve_book", {"book_id": "B9"})
        assert bad.is_error and "no book" in bad.content[0].text
        wrong = await client.call_tool("search_books", {"query": 5})
        assert wrong.is_error
    print("server tests passed")


asyncio.run(check())

Running it prints:

server tests passed

It checks that exactly the expected tools exist, that an unknown id produces a helpful error and that a wrong argument type is refused. Extend it with every bug you find. A test for the tool list is worth keeping: it catches an accidental new tool before a host exposes it.

Inspect and debug

MCP Inspector is the project's tool for exploring a server. Run without extra flags, it opens a browser interface. It also has a command-line mode, which is handy in scripts. These commands were run with version 2.17.0; activate your virtual environment first and use python or python3 as your system requires.

npx -y @modelcontextprotocol/inspector@2.17.0 --cli python server.py --method tools/list

npx -y @modelcontextprotocol/inspector@2.17.0 --cli python server.py \
  --method tools/call --tool-name search_books --tool-arg query=agents

The line breaks with \ are for Unix-like shells; on Windows, put the command on one line. Inspector starts your server, so you are running that code and Inspector's package on your machine. Pin versions and only inspect servers you trust.

SymptomLikely causeWhat to check
Connection closes at onceThe server crashed on startRun it directly and read the error
"Invalid message" or parse errorsSomething printed to standard outputRedirect all logging to standard error
Works in a terminal, not in a hostDifferent working directory or environmentUse full paths; set environment values in the host configuration
Tool missing from the listDecorator absent or old process still runningRestart the server and the connection
Arguments rejectedType hints differ from what is sentCompare with the listed input schema
HTTP request refusedWrong path, host check or version mismatchUse the /mcp path and read the server log
Model never calls the toolVague descriptionSay when to use it and what it returns

Connect it to a real host

Desktop assistants and code editors that support MCP usually let you register a local server with a command and arguments. The file name and location differ by product, so follow that product's documentation. Many use a block shaped like this:

{
  "mcpServers": {
    "library": {
      "command": "/full/path/to/.venv/bin/python",
      "args": ["/full/path/to/server.py"]
    }
  }
}

Use full paths, because the host will not start in your project folder. Then ask the assistant a question that needs the library and confirm which tool it calls and what it asks you to approve.

Expert TypeScript and production habits

The same idea in TypeScript

The TypeScript SDK version 2 uses separate packages; it replaces the single package used by version 1. Install the server package and a schema library:

npm init -y
npm install @modelcontextprotocol/server zod

Save as server.mjs:

// A small MCP server with the TypeScript SDK, version 2
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

const books = new Map([["B1", { title: "Designing Agents", available: true }]]);

function createServer() {
  const server = new McpServer({ name: "library", version: "1.0.0" });

  server.registerTool(
    "reserve_book",
    {
      description: "Reserve one available book by its id. Changes records.",
      inputSchema: z.object({ book_id: z.string() }),
    },
    async ({ book_id }) => {
      const book = books.get(book_id);
      if (!book || !book.available) {
        const text = `${book_id} is not available`;
        return { content: [{ type: "text", text }], isError: true };
      }
      book.available = false;
      console.error(`reserved ${book_id}`); // never console.log on stdio
      return { content: [{ type: "text", text: `Reserved ${book.title}` }] };
    },
  );
  return server;
}

serveStdio(createServer);

This version was run with Node.js 22 and server package 2.4.0. The first reservation returns "Reserved Designing Agents", the second returns an error result saying the book is not available, and sending a number as book_id produces an input validation error before your handler runs. The factory function builds a fresh server instance for each connection that needs one, so keep lasting data outside it, as the books map is here.

Those results were produced with a Python client driving the TypeScript server. Yours can do the same: change the command to node and the argument to server.mjs, and remove the calls to tools and resources it does not offer. That interchangeability is the point of a protocol.

Improve the design before sharing

AreaTutorial versionShared version
DataDictionary in memoryDatabase with transactions, so two callers cannot reserve one book
IdentityNoneAuthorized user on every request
PermissionsAnyone may reserveChecked per user and per record
InputsType checksLength, format and range limits
ResultsAll matchesPaged and size-limited
RetriesNot consideredIdempotency key for changes
OperationsA log lineStructured logs, metrics, timeouts, health checks

Notice the race in reserve_book: it checks availability and then changes it. In a single process running this synchronous function it is unlikely to bite, but with a real database or several instances it will. Use one atomic update, such as "set unavailable where id matches and still available", and treat zero changed rows as already on loan.

Mind the changing tool

search_books only reads. reserve_book changes records. Hosts can treat them differently if you make the difference obvious in names and descriptions, and you may add the protocol's tool annotations as hints. Hints are not security: the server must still enforce its rules, and a host should not trust annotations from a server it does not trust.

Resources and prompts from the client side

The tutorial client reads one resource but does not list or fetch the prompt. A host would normally list prompts, show them to the user as commands and fetch the chosen one with its arguments. The returned messages then start or extend the conversation. Try it: add a call that lists prompts, then fetch recommend with a topic and print the message text. Check the SDK documentation for the exact method names in the release you pinned, and add the same calls to your test so a later change cannot remove the prompt unnoticed.

Limits worth setting early

A server cannot know how a host will use it, so protect it from heavy or careless use. Cap query length, number of results and the size of any returned text. Give outbound calls a timeout shorter than the host is likely to wait, so your server can report a clear failure instead of leaving the caller guessing. Where a request would be costly, reject it with advice on narrowing it. These limits are easier to introduce before anyone depends on unlimited behavior.

Exercises

  1. Add return_book, with a clear error when the book was not on loan, and a test for it.
  2. Add a resource template that returns one book by id.
  3. Limit search results to ten and report how many more exist.
  4. Replace the dictionary with SQLite and make reservation atomic.
  5. Connect the server to a host and record which requests it asks you to approve.

Ready to share?

  • Dependencies are pinned to tested versions
  • Nothing writes to standard output in stdio mode
  • Expected failures return clear tool errors without secrets
  • Tests cover the tool list, success, failure and bad input
  • Changing tools check permission and survive retries
  • Remote access requires authorization and encryption
  • A short document says what the server can read and change

Frequently asked questions

Why does my old tutorial use a different class name?

It was written for version 1 of the SDK. Pin the major version your code was written for, and read the migration notes before upgrading.

Do I need to handle protocol versions myself?

Normally the SDK negotiates them, including falling back for older peers. Test with the hosts you intend to support.

stdio or HTTP?

stdio for a tool one person runs locally; HTTP for a shared service. The tool code can stay the same.

Can a tool call a model?

It can call a model API like any program, with its own key and costs. Be clear to users about where their data goes.

References and further reading

Next steps