MCP: Write a Server and Connect It
After reading this section, you will have written your own MCP server that myagent can connect to, discover its tools, and call them. Along the way, you'll also figure out exactly what problem MCP solves.
First, the Problem: Rewriting Everything for Every Tool You Connect
In the previous chapter, we wrote our tools in agent.py. But if you want Claude Code, Cursor, and your own Agent to all be able to search the company's notes, you'd have to write it three times, each in a different format.
MCP (Model Context Protocol) was created to solve exactly this: write a tool once, package it as an MCP server, and every program that supports MCP can use it directly. The official analogy: MCP is like a USB-C port for AI applications.
Three Roles
Look it upIn MCP…
Click one to see.
A server can provide three kinds of things: Tools (functions the model decides when to call), Resources (data read by the application), and Prompts (prompt templates the user picks). This section only uses Tools. The message format is JSON-RPC 2.0; a single tool call on the wire looks like this (from the spec):
{ "jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": { "name": "get_weather", "arguments": { "location": "New York" } } }1. Write an MCP Server
mcp_servers/notes_server.py (in myagent.zip):
import json
from pathlib import Path
from mcp.server import MCPServer
NOTES = Path(__file__).with_name("notes.json")
mcp = MCPServer("notes")
def _load():
return json.loads(NOTES.read_text(encoding="utf-8")) if NOTES.exists() else []
@mcp.tool()
def add_note(text: str) -> str:
"""记下一条笔记。"""
notes = _load() + [text]
NOTES.write_text(json.dumps(notes, ensure_ascii=False), encoding="utf-8")
return f"已记下,共 {len(notes)} 条。"
@mcp.tool()
def search_notes(keyword: str) -> list[str]:
"""按关键词查找笔记,返回所有包含这个词的笔记。"""
return [n for n in _load() if keyword in n]
if __name__ == "__main__":
mcp.run()Unlike the previous chapter, where we hand-wrote the JSON Schema, here the type annotations are the schema: text: str tells the SDK the parameter is a string, and the function's docstring is the tool description. mcp.run() takes no arguments, meaning it communicates with the client over stdio (standard input/output).
FastMCP from many online tutorials no longer works in the new version
Starting from 2.x, the official Python SDK renamed FastMCP to MCPServer, and the old import path was directly removed. If you follow older tutorials and write from mcp.server.fastmcp import FastMCP, you'll get ModuleNotFoundError: No module named 'mcp.server.fastmcp', and the error message will suggest using from mcp.server.mcpserver import MCPServer instead. We're using mcp 2.3.0 (released 2026-10-02). If you still want to run old code, install mcp<2.
2. Have the Agent Connect to It
In MCP SDK 2.x, there is a single Client class on the client side. Give it a StdioServerParameters, and it will start the server as a subprocess and connect via stdio:
async def connect_mcp(command, stack):
from mcp import Client
from mcp.client.stdio import StdioServerParameters
parts = shlex.split(command)
mcp_client = await stack.enter_async_context(Client(StdioServerParameters(command=parts[0], args=parts[1:])))
listed = await mcp_client.list_tools()
tools = [{"type": "function", "function": {"name": t.name, "description": t.description or "",
"parameters": t.input_schema}} for t in listed.tools]
return mcp_client, toolsThe key step: convert the tools listed by the MCP server (names, descriptions, input schemas) into the tools format the model understands, and hand them to the model together with the local tools. When the model requests a call, if it's not a local tool, forward it to MCP:
r = await mcp_client.call_tool(name, args)
result = "\n".join(getattr(c, "text", str(c)) for c in r.content)Run it:
python agent.py --mcp "python mcp_servers/notes_server.py" "记一条笔记:周五下午三点和设计组评审消息通知的交互稿"
python agent.py --mcp "python mcp_servers/notes_server.py" "我记过哪些和设计组有关的事?"You should see (actual output on my machine with qwen3:8b):
Connected to MCP server, new tools added: add_note, search_notes
[1] add_note({"text": "Review the interaction mockups for message notifications with the design team on Friday at 3 p.m."})
Agent: Note recorded: Review the interaction mockups for message notifications with the design team on Friday at 3 p.m.Connected to MCP server, new tools added: add_note, search_notes
[1] search_notes({"keyword": "design team"})
Agent: Found the following notes related to the design team:
- Review the interaction mockups for message notifications with the design team on Friday at 3 p.m.Not a single line of myagent's code has anything to do with notes; all the tools come from the MCP server. The same notes_server.py can also be configured for other MCP-supporting programs such as Claude Code.
A common pitfall: a server subprocess started via stdio does not inherit all of your environment variables—only a few like HOME and PATH. If the server needs an API Key, you must pass it explicitly in StdioServerParameters(env={...}).
3. What Changed in the New Spec
MCP's version numbers are dates, indicating the last backward-incompatible change. The current version is 2026-07-28, and the previous one was 2025-11-25. This version has major changes:
- The protocol became stateless: the
initializehandshake was removed, each request carries its own version and capability information; a mandatoryserver/discoverwas added. - Streamable HTTP no longer has session IDs.
- Roots, Sampling, and Logging are now marked as deprecated.
So tutorials online that talk about "first do the initialize handshake" are describing the old version. When writing code with the SDK, you basically won't notice these changes—the SDK handles them for you.
MCP is now one of the projects under the Agentic AI Foundation (AAIF) of the Linux Foundation.
4. Security: MCP Tools Are Someone Else's Code
The spec is very clear on this: a tool is equivalent to executing arbitrary code, and the host must obtain the user's explicit consent before calling any tool; tool descriptions should be treated as untrusted unless they come from a trusted server. Only connect MCP servers you trust. For simplicity, our myagent doesn't add confirmation for MCP tools; the final chapter will cover how to add it.
Quiz timeWhat core problem does MCP solve?
Check Yourself
- I wrote notes_server.py and had myagent connect to it via
--mcp - I know FastMCP was renamed to MCPServer in SDK 2.x
- I can name the biggest change in the 2026-07-28 spec
Next section: Differences Between MCP, Function Calling, A2A, and Skills.