Your AI assistant has never heard of yesterday’s security flaw, and it cannot check whether anyone is attacking it yet. An MCP server closes that gap by giving the assistant a few well-defined tools, here a lookup for the EPSS score and KEV status of a CVE. This tutorial shows how to build an MCP server in Python with the official MCP Python SDK 2.3.0: a simple MCP server in a little over 100 lines of code that exposes data and tools to an AI model. I tested it three ways: in memory, over stdio and over HTTP. So you do not step into the same traps I did, the notes below cover what is different in SDK 2 compared with most older tutorials.
What MCP is and what an MCP server offers
The Model Context Protocol (MCP) is an open standard for how an application built around a large language model (LLM), the host, talks to external programs. Large language models (LLMs) cannot reach your data on their own, so MCP lets you build your own MCP server that exposes data and tools in a uniform way. Claude Code, Cursor and VS Code are hosts. A host contains an MCP client, and the external programs are MCP servers. A server can offer three things. Tools are actions the model picks and calls on its own. Resources are readable data the application fetches. Prompts are message templates a person invokes by name, for example through a slash command. How this fits together with memory, skills and hooks is covered in MCP, Memory, Skills, and Hooks.
Is that not just function calling? Not quite. Function calling is a feature of a model API: you send tool descriptions with every request. MCP adds a protocol on top, so you build a tool once and any host can plug it in. The host then translates MCP tools into tool calls to the model. For you that means one server instead of one integration per vendor. The SDK we use is the official Python SDK on GitHub. The same package also contains the client we use to test the tools in a moment.
What changed in SDK 2
Since pip install mcp installs version 2.x, many tutorials no longer work. The biggest change: the class FastMCP is now MCPServer, and the old import path mcp.server.fastmcp was not deprecated but removed. Copy an example with from mcp.server.fastmcp import FastMCP and you get an import error right away. SDK 2 also ships a first-class Client for testing servers from Python and supports the protocol revision of July 28, 2026. The page What’s new in v2 lists everything. According to the maintainers, the 1.x line keeps getting critical fixes and security patches if you cannot migrate a project yet. The SDK requires Python 3.11 or newer.
Set up the Python project with uv
To create an MCP server you first need a Python project. I use uv because the documentation does, and because it keeps host configurations short. A plain venv with pip works just as well:
mkdir cve-radar && cd cve-radar
uv init --bare
uv add "mcp[cli]" httpx
The cli extra brings the mcp command (mcp dev, mcp run, mcp install). One catch: you have to add httpx yourself, because SDK 2 depends on its own library called httpx2 and does not install httpx. In a fresh environment with only mcp[cli], my import httpx failed with ModuleNotFoundError.
Build an MCP server in Python: the code
The MCP server is called CVE-Radar. It has two tools, one resource and one prompt. The tool epss_score queries the public API of the FIRST forum, and kev_status checks the Known Exploited Vulnerabilities (KEV) catalog from the US agency CISA, the list of flaws that are being exploited in the wild. Save the code as server.py:
import re
from functools import lru_cache
import httpx
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from pydantic import BaseModel, Field
mcp = MCPServer("CVE-Radar")
EPSS_URL = "https://api.first.org/data/v1/epss"
KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
CVE_RE = re.compile(r"^CVE-\d{4}-\d{4,}$")
class EpssResult(BaseModel):
cve: str
epss: float = Field(description="Probability of exploitation within 30 days, 0 to 1")
percentile: float = Field(description="Rank among all scored CVEs, 0 to 1")
date: str = Field(description="Date of the score (YYYY-MM-DD)")
class KevResult(BaseModel):
cve: str
in_kev: bool
date_added: str | None = None
due_date: str | None = None
name: str | None = None
def check_cve(cve_id: str) -> str:
cve_id = cve_id.strip().upper()
if not CVE_RE.match(cve_id):
raise ToolError(f"{cve_id!r} is not a valid CVE ID. Expected something like CVE-2021-44228.")
return cve_id
@mcp.tool()
async def epss_score(cve_id: str) -> EpssResult:
"""EPSS probability and percentile for a CVE (source: FIRST)."""
cve_id = check_cve(cve_id)
async with httpx.AsyncClient(timeout=15) as http:
r = await http.get(EPSS_URL, params={"cve": cve_id})
r.raise_for_status()
data = r.json()["data"]
if not data:
raise ToolError(f"No EPSS score for {cve_id}. The CVE is either brand new or does not exist.")
row = data[0]
return EpssResult(
cve=cve_id,
epss=float(row["epss"]),
percentile=float(row["percentile"]),
date=row["date"],
)
@lru_cache(maxsize=1)
def kev_catalog() -> dict[str, dict]:
r = httpx.get(KEV_URL, timeout=30, follow_redirects=True)
r.raise_for_status()
return {v["cveID"]: v for v in r.json()["vulnerabilities"]}
@mcp.tool()
def kev_status(cve_id: str) -> KevResult:
"""Checks whether a CVE is in the CISA Known Exploited Vulnerabilities (KEV) catalog."""
cve_id = check_cve(cve_id)
entry = kev_catalog().get(cve_id)
if entry is None:
return KevResult(cve=cve_id, in_kev=False)
return KevResult(
cve=cve_id,
in_kev=True,
date_added=entry["dateAdded"],
due_date=entry["dueDate"],
name=entry["vulnerabilityName"],
)
@mcp.resource("cve://{cve_id}/links")
def cve_links(cve_id: str) -> str:
"""Reference links for a CVE, one URL per line."""
cve_id = check_cve(cve_id)
return "\n".join([
f"https://nvd.nist.gov/vuln/detail/{cve_id}",
f"https://www.cve.org/CVERecord?id={cve_id}",
f"{EPSS_URL}?cve={cve_id}",
])
@mcp.prompt()
def triage(cve_id: str) -> str:
"""Template for a quick patch decision."""
return (
f"Check {cve_id} with the tools epss_score and kev_status. "
"Decide in three sentences whether it must be patched this week, "
"and quote the numbers you rely on."
)
if __name__ == "__main__":
mcp.run()
A few spots deserve a closer look. The SDK builds the input schema from type annotations: cve_id: str is the schema, and you write no JSON Schema by hand. The docstring becomes the description the model reads when it decides whether to use the tool, so write it for the model, not for yourself. The return types EpssResult and KevResult are Pydantic models and turn into the output schema. The client gets a structured object, and the model gets the same data as JSON text.
The most important part is error handling. If a tool raises a ToolError, the model sees the message, notices the typo and calls the tool again with a corrected value. If it raises any other exception, for example a ValueError, that counts as a crash. The model only learns that the call failed and never sees your message. My first draft raised a ValueError, and the client received nothing but Error executing tool kev_status with no reason. Never return an error message as a normal value either, because then the call looks successful. The SDK documentation has a page on handling errors.
Two small notes: lru_cache loads the KEV catalog once per process and keeps it until the server restarts. And epss_score is async while kev_status is not. The SDK accepts both, and synchronous functions run in a thread.
Testing the MCP server without a process or a port
The SDK’s client connects straight to the server object, with no subprocess and no transport. That is the fastest way to try a tool. Save this as test_inmemory.py:
import anyio
from mcp import Client
from server import mcp
async def main() -> None:
async with Client(mcp) as client:
tools = await client.list_tools()
print([t.name for t in tools.tools])
r = await client.call_tool("epss_score", {"cve_id": "CVE-2021-44228"})
print(r.structured_content)
r = await client.call_tool("kev_status", {"cve_id": "not-a-cve"})
print(r.is_error, r.content[0].text)
anyio.run(main)
Running uv run python test_inmemory.py printed this on my machine (an example, the values change daily):
['epss_score', 'kev_status']
{'cve': 'CVE-2021-44228', 'epss': 0.99999, 'percentile': 1.0, 'date': '2026-12-01'}
True Error executing tool kev_status: 'NOT-A-CVE' is not a valid CVE ID. Expected something like CVE-2021-44228.
The third line shows the difference from a crash: thanks to ToolError, the reason is in the result and is_error is True. The same check belongs in your project as a test. This test_server.py needs no network and passed with uv run --with pytest pytest (2 passed):
import pytest
from mcp import Client
from server import mcp
@pytest.mark.anyio
async def test_invalid_cve_id() -> None:
async with Client(mcp) as client:
result = await client.call_tool("kev_status", {"cve_id": "not-a-cve"})
assert result.is_error
assert "not a valid CVE ID" in result.content[0].text
@pytest.mark.anyio
async def test_resource_links() -> None:
async with Client(mcp) as client:
res = await client.read_resource("cve://CVE-2021-44228/links")
assert "nvd.nist.gov" in res.contents[0].text
Use the resource and the prompt from a client
Tools get most of the attention, but resources and prompts live on the same server and are used differently. A resource is a readable source with a URI. Ours has a template, cve://{cve_id}/links, and returns three links for any CVE. A prompt is a template a person picks, and it is then sent to the model as a message. You can check both with the client:
import anyio
from mcp import Client
from server import mcp
async def main() -> None:
async with Client(mcp) as client:
templates = await client.list_resource_templates()
print([t.uri_template for t in templates.resource_templates])
res = await client.read_resource("cve://CVE-2021-44228/links")
print(res.contents[0].text.splitlines()[0])
prompt = await client.get_prompt("triage", {"cve_id": "CVE-2021-44228"})
print(prompt.messages[0].content.text)
anyio.run(main)
The output: first the template ['cve://{cve_id}/links'], then the first line https://nvd.nist.gov/vuln/detail/CVE-2021-44228, and finally the finished prompt text. In a host, the prompt typically shows up as a command you call with the CVE number. The model then calls epss_score and kev_status by itself, because the text names both tools.
Run it over stdio and check it with a client
Hosts such as Claude Code or Cursor start the server as a child process and talk to it over its standard input and output. mcp.run() with no arguments starts exactly this stdio server. To start the server and check it, a client can take the same route and launch server.py itself:
import sys
import anyio
from mcp import Client, StdioServerParameters
async def main() -> None:
params = StdioServerParameters(command=sys.executable, args=["server.py"])
async with Client(params) as client:
print(client.server_info)
r = await client.call_tool("kev_status", {"cve_id": "CVE-2021-44228"})
print(r.structured_content["in_kev"])
anyio.run(main)
The output began with name='CVE-Radar' ... and ended in True, because Log4Shell is in the KEV catalog. One trap with stdio: standard output belongs to the protocol. A print() in the server or in a tool writes text into the protocol stream. When I added print("server starting") as a test, the client reported a Pydantic error (“Invalid JSON”) even though the call still went through. Send debug output to sys.stderr or use logging.
Run the server over HTTP
For anything that does not run on your own machine you need Streamable HTTP. To run the server this way, you change no code, only the command:
uv run mcp run server.py --transport streamable-http
The server then listens on http://127.0.0.1:8000/mcp. A client connects with the URL:
import anyio
from mcp import Client
async def main() -> None:
async with Client("http://127.0.0.1:8000/mcp") as client:
r = await client.call_tool("epss_score", {"cve_id": "CVE-2021-44228"})
print(r.structured_content)
anyio.run(main)
This returned the same EPSS value as the first test. If you want to set port or path in code, pass them to mcp.run(transport="streamable-http", port=3001). One thing matters for operations: by default the server listens only on 127.0.0.1 and checks no credentials. Anyone who puts it on a network needs authentication for all clients, as the SDK’s authorization chapter describes. Can you run an MCP server in production? Yes, as long as access, timeouts and failure cases are handled. A server that fetches third-party data should also never treat that content as an instruction to the model.
Connect it to Claude Code, Cursor or VS Code
A host only needs the start command. According to the SDK documentation it looks like this for Claude Code, extended with --with httpx because our server needs the library:
claude mcp add cve-radar -- uv run --with "mcp[cli]" --with httpx mcp run /absolute/path/to/server.py
For Cursor you create a .cursor/mcp.json in your project, and for VS Code (Visual Studio Code) a .vscode/mcp.json. Both take the same command and args, with VS Code using the key servers and an entry "type": "stdio" instead of mcpServers. For Claude Desktop, uv run mcp install server.py writes the entry into the configuration. The tool for trying MCP tools interactively is the MCP Inspector, which uv run mcp dev server.py starts.
To be upfront: the host commands come from the documentation, and I did not launch the Inspector. What I did test is the identical start command, uv run --with "mcp[cli]" --with httpx mcp run server.py, driven by the stdio client. It called kev_status without errors. That leaves only the host-specific settings when you plug it into a real host.
Common mistakes at a glance
If the import fails with ModuleNotFoundError: mcp.server.fastmcp, the example dates from the v1 era: use MCPServer from mcp.server. If httpx is missing, add it to the project or to the uv run call. If the host cannot find the server, an absolute path to uv and to server.py usually helps, because hosts start with a very short PATH. And if the model never uses a tool, the docstring is almost always at fault: it does not say when the tool is useful.
Frequently asked questions
Can I create an MCP server with an MCP SDK other than Python? Yes. The protocol is language-independent, and there are SDKs for other languages. This tutorial sticks to the Python MCP SDK because it is the one I tested.
Is there an official SDK for Python? Yes, the MCP Python SDK in the repository modelcontextprotocol/python-sdk. It contains server and client, supports stdio, Streamable HTTP and SSE, and is MIT licensed.
Can I run an MCP server in the cloud? Yes. With the HTTP transport the same code runs behind a URL, and hosts connect to it instead of launching a local command. The SDK has its own chapters on deployment and authorization.
Do I need uv? No. A virtual environment with pip install "mcp[cli]" httpx is enough. With uv only the host start commands get shorter, because uv run --with resolves the dependencies without a prepared environment.
Where to go from here
You can build a lot on this skeleton: use the tool to check the status of a flaw in a report your scanner produced. How to generate that report and sort findings by EPSS and KEV is covered in our tutorial Create an SBOM with Syft and Grype. How to give a coding agent lasting rules for tools like this is in AGENTS.md vs CLAUDE.md vs Cursor Rules. And for the next level, the SDK’s Get started guide continues with context, progress reporting and elicitation.



