What is MCP? A Comprehensive Guide to MCP (Masked Context Prediction)

This article is technical-oriented, suitable for technical personnel to read, and non-technical personnel can get a general understanding.
Recently, Cursor 0.45 version was updated to support the MCP Server, greatly enhancing the ability to collaborate Cursor, such as in the Composer can support the chain of thought, online real-time search, according to the context of the work to help generate the picture suitable for the needs of the software and so on.So, what is MCP (Model Context Protocol)? This article introduces the basic concepts of MCP, functional value, principle of work, what can be done, and how to develop and use it with related learning materials.
To dock the dream platform, you need to register for an account. An account can be free to call 88 times/day, which is enough to use!
Seamless integration with cursor, you mention your task requirements, cursor will automatically according to the context of your project, to help you generate a good cue word and call the tool to generate, greatly enhancing the efficiency of software development.
Want to know how to develop? Look here: the development of an MCP Server and Cursor integration, to give Cursor wings!
What is MCP (Model Context Protocol)?
Definition
MCP (Model Context Protocol), an open standard introduced by Anthropic at the end of November 2024, aims to unify the communication protocols between large language models (LLMs) and external data sources and tools. The main purpose of MCP is to solve the current problem of AI models not being able to give full play to their potential due to the limitations of data silos. MCP enables AI applications to securely access and manipulate local and remote data, providing an interface for AI applications to connect everything.
The Value of MCP
As a chestnut, in the past, it was a hassle to either copy and paste or upload and download in order for AI applications such as large language model to use our data.
Even the most powerful models are limited by data isolation, forming information silos. To make more powerful models, each new data source requires its own re-customized implementation, making it difficult to scale a truly interconnected system with many limitations.
Now, MCP can directly build a bridge between AI and data (including local data and Internet data), through the MCP server and MCP client, as long as everyone follows this set of protocols, you can realize the "Internet of Everything".
With MCP, you can integrate with data and file systems, development tools, Web and browser automation, productivity and communications, and various community ecosystems to realize powerful collaborative work capabilities, the value of which is immeasurable.
Difference between MCP and Function Calling
-
MCP (Model Context Protocol), Model Context Protocol
-
Function Calling
Both technologies are designed to enhance the ability of AI models to interact with external data, but MCP can not only enhance AI models, but also other application systems.
Data Security
This ideal "Internet of Everything" ecosystem looks fascinating.
But are you worried that the data exposed through the MCP Server will be leaked or illegally accessed? MCP also takes this headache into consideration.
MCP reduces the risk of data leakage by standardizing the data access interface, greatly reducing the likelihood of direct contact with sensitive data.
In addition, MCP has a built-in security mechanism to ensure that only authenticated requests can access specific resources, which is equivalent to adding another line of defense in data security. At the same time, the MCP protocol also supports a variety of encryption algorithms to ensure the security of data in the transmission process.
For example, MCP servers control the resources themselves and do not need to provide sensitive information such as API keys to LLM providers. In this way, even if the LLM provider is attacked, the attacker will not be able to access this sensitive information.
However, MCP is a set of protocols/standards that need to be built together in order for the ecosystem to flourish. Right now, it's just the testing phase, and everything has just begun, and of course, there will be more problems emerging.
How it Works
The MCP protocol utilizes a unique architectural design that divides the communication between the LLM and the resource into three main parts: the client, the server, and the resource.
The client is responsible for sending requests to the MCP server, and the server forwards these requests to the appropriate resources. This layered design allows the MCP protocol to better control access rights, ensuring that only authorized users can access specific resources.
Workflow
The following is the basic workflow of MCP:
-
Initialize connection: The client sends a connection request to the server to establish a communication channel.
-
Send request: The client constructs a request message according to the requirements and sends it to the server.
-
Process the request: the server receives the request, parses the request content and performs the corresponding operation (such as querying the database, reading files, etc.).
-
Return results: the server encapsulates the processing results into a response message and sends it back to the client.
-
Disconnect: After the task is completed, the client can actively close the connection or wait for the server to time out and close.
Core Architecture
MCP follows a client-server architecture, which includes the following core concepts:
-
MCP Hosts: The LLM application (e.g., Claude Desktop, IDE, or AI tool) that initiates the request.
-
MCP Clients: Within the host program, a 1:1 connection to the MCP server.
-
MCP Servers: Provide context, tool, and prompt information to MCP clients.
-
Local Resources: Resources on the local computer that can be securely accessed by the MCP server (e.g., files, databases).
-
Remote Resources: Remote resources that the MCP server can connect to (e.g., through an API).
MCP Client
The MCP client acts as a bridge between the LLM and the MCP server. The workflow of the MCP client is as follows:
-
The MCP client first obtains a list of available tools from the MCP server.
-
The MCP client first obtains the list of available tools from the MCP server and sends the user's query along with the tool description to the LLM via function calling.
-
The LLM decides whether tools are needed and which ones to use.
-
If a tool is required, the MCP client executes the corresponding tool call through the MCP server.
-
The result of the tool call is sent back to LLM.
-
The LLM generates a natural language response based on all the information.
-
The response is then presented to the user.
Claude Desktop and Cursor both support MCP Server access; they are used as MCP clients to connect to an MCP Server to sense and realize calls.
MCP Server
The MCP server is a key component in the MCP architecture and provides three main types of functionality:
-
Resources: File-like data that can be read by the client, such as API responses or file contents.
-
Tools: Functions that can be called by LLM (with user approval).
-
Prompts: pre-written templates to help the user accomplish specific tasks.
These features enable the MCP server to provide AI applications with rich contextual information and operational capabilities that enhance the utility and flexibility of LLM.
You can find a number of community-implemented MCP servers in the MCP Servers Repository and Awesome MCP Servers repositories. MCP servers written in TypeScript can be run with the npx command, and MCP servers written in Python can be run with the uvx command. MCP servers written in TypeScript can be run with the npx command, and MCP servers written in Python with the uvx command.
Communication Mechanisms
The MCP protocol supports two main communication mechanisms: local communication based on standard input and output, and remote communication based on SSE (Server-Sent Events).
Both mechanisms use JSON-RPC 2.0 format for messaging, ensuring standardized and scalable communication.
-
Local Communication: Transmits data via stdio and is suitable for communication between clients and servers running on the same machine.
-
Remote Communication: Using SSE combined with HTTP to realize real-time data transmission across networks, suitable for scenarios requiring access to remote resources or distributed deployment.
What can MCP do?
Introducing a variety of MCP Server capabilities can greatly extend the capabilities of some AI tools, such as Cursor and Claude, which we commonly use.
These official reference servers demonstrate the use of MCP core functionality and SDKs.
Data and File System
-
File System - Secure file operations with configurable access control
-
PostgreSQL - Read-only database access with schema checking
-
SQLite - Database interaction and business intelligence capabilities
-
Google Drive - File access and search capabilities for Google Drive
Development Tools
-
Git - Tools for reading, searching, and manipulating Git repositories
-
GitHub - Repository management, file manipulation and GitHub API integration
-
GitLab - GitLab API integration for project management
-
Sentry - Fetch and analyze issues from Sentry.io
Web and Browser Automation
-
Brave Search - Web and local search using Brave's search APIs
-
Fetch - Optimized web content acquisition and transformation for LLM use
-
Puppeteer - Browser automation and web crawling capabilities
Productivity and Communication
-
Slack - channel management and messaging capabilities
-
Google Maps - location services, routes, and location details
-
Memory - Knowledge graph-based persistent memory system
AI and specialized tools
-
EverArt - AI image generation using various models
-
Sequential Thinking - Dynamic problem solving through sequences of thought
-
AWS KB Retrieval - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime
Officially integrated tools
These MCP servers are maintained by companies for their platforms.
-
Axiom - Query and analyze log, trace, and event data using natural language
-
Browserbase - automate browser interactions in the cloud
-
Cloudflare - Deploy and manage resources on the Cloudflare Developer Platform
-
E2B - Execute code in a secure cloud sandbox
-
Neon - Interact with the Neon serverless Postgres platform
-
Obsidian Markdown Notes - Read and search Markdown notes in the Obsidian knowledge base
-
Qdrant - Implement semantic memory using the Qdrant vector search engine
-
Raygun - Access crash reports and monitoring data
-
Search1API - Unified API for search, crawlers and sitemaps
-
Tinybird - Interacting with the Tinybird serverless ClickHouse platform
Some of the community's tools
The growing ecosystem of community development servers extends the functionality of MCP with
-
Docker - Managing containers, images, volumes, and networks
-
Kubernetes - managing pods, deployments, and services
-
Linear - project management and issue tracking
-
Snowflake - Interacting with the Snowflake database
-
Spotify - control Spotify playback and manage playlists
-
Todoist - Task management integration
For more, check out the community server list: MCP Servers Repository.
How to Use and Develop the MCP Server?
Part of the list of tools currently supported (see here for more):
Claude Desktop Usage Example
To configure the MCP client, using Claude Desktop as an example, proceed as follows:
-
Install Claude Desktop: Ensure that you have installed the latest version of Claude Desktop on your macOS or Windows system.
-
Configure the MCP server: In the Claude Desktop configuration file, configure the entry Claude Desktop->Menu->Settings->Developer->Edit Config. >Edit Config:
Add the required MCP server information, for example:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
},
"git": {
"command": "uvx",
"args": ["mcp-server-git", "--repository", "path/to/git/repo"]
}
}
}
Here, @modelcontextprotocol/server-filesystem, mcp-server-git are some corresponding MCP Servers, which can be found by open source or developed by yourself.
After configuration, a hammer will appear in the bottom right corner of the topic's main interface. There are a few hammers to configure a few, and then if the conversation involves the use of the tool, Claude will automatically call the
Cursor Example of Use
Cursor tool integrated mcp server function for the development of increased efficiency is very obvious, the configuration of the entrance in: File -> Preferences -> Cursor Settings -> Features ->MCP Server->Add new MCP Server
After the configuration, you need to draw a picture of the place to give it on request. It will automatically sense the context of the generated prompt and call the tool to generate images.
Check the images generated.
Developing the MCP Server
MCP is just a protocol; as long as it conforms to this protocol, in theory, all languages can be developed. Here we show a simple MCP weather server built in python and connect it to the host program Claude for Desktop example:
In the following example, if it is troublesome to obtain the weather interface, you can ignore the specific implementation and just write a Hello World return. The main server.py implements the following functions in three steps:
-
Register service name: server = Server("weather")
-
Register the tool list description: @server.list_tools() annotated method, pay attention to the access specification requirements
-
Implement the specific tool method: @server.call_tool() annotated method, note the requirement of parameter specification.
Preliminaries
This quick start assumes that you are familiar with:
-
Python
-
LLM (e.g. Claude)
System Requirements
For Python, make sure you have Python 3.9 or later installed.
Configuring the Environment
First, let's install uv
and set up the Python project and environment:
curl -LsSf https://astral.sh/uv/install.sh | sh
Restart the terminal after installation to ensure that the uv
commands are recognized correctly.
Now, let's create and set up the project:
# Create a new directory for the project
uv init weather
cd weather
# Create a virtual environment and activate it
uv venv
# Test the command under Windows.\.venv\Scripts\activate
source .venv/bin/activate
# Install dependencies
uv add mcp httpx
# Delete template files, manually under Windows
rm hello.py
# Create our files, manually under Windows
mkdir -p src/weather
touch src/weather/__init__.py
touch src/weather/server.py
Add the following code to pyproject.toml
:
...rest of config
[build-system]
requires = [ "hatchling",]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/weather"]
[project.scripts]
weather = "weather:main"
__init__.py
:from . import server
import asyncio
def main():
"""Main entry point for the package."""
asyncio.run(server.main())
# Optional: expose other important items at the package level
__all__ = ['main', 'server']
Now let's start building the server.
Build the Server
1. Import the Package
Add the following to the top of server.py
:
from typing import Any
import asyncio
import httpx
from mcp.server.models import InitializationOptions
import mcp.types as types
from mcp.server import NotificationOptions, Server
import mcp.server.stdio
2. Setting Up the Instance
Then, initialize the server instance and the base URL for the NWS API:
# The mcp core protocol source code still has a bug in unicode encoding processing, so it needs to be manually specified as utf-8
stdin.reconfigure(encoding='utf-8')
stdout.reconfigure(encoding='utf-8')
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
server = Server("weather")
3. Implementing the tool list
We need to tell the client what tools are available.list_tools()
decorator registers this handler:
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
"""
List the available tools.
Each tool uses JSON Schema validation to specify its parameters.
"""
return [
types.Tool(
name="get-alerts",
description="Get weather alerts for a given state",
inputSchema={
"type": "object",
"properties": {
"state": {
"type": "string",
"description": "Two-letter state code(例如 CA、NY)",
},
},
"required": ["state"],
},
),
types.Tool(
name="get-forecast",
description="Get the weather forecast for a given location",
inputSchema={
"type": "object",
"properties": {
"latitude": {
"type": "number",
"description": "The latitude of the location",
},
"longitude": {
"type": "number",
"description": "The longitude of the location",
},
},
"required": ["latitude", "longitude"],
},
),
]
Two of our tools are defined here:get-alerts
and get-forecast
.
4. Helper Functions
Next, let's add helper functions for querying and formatting National Weather Service API data:
async def make_nws_request(client: httpx.AsyncClient, url: str) -> dict[str, Any] | None:
"""Send a request to the NWS API with appropriate error handling."""
headers = {
"User-Agent": USER_AGENT,
"Accept": "application/geo+json"
}
try:
response = await client.get(url, headers=headers, timeout=30.0)
response.raise_for_status()
return response.json()
except Exception:
return None
def format_alert(feature: dict) -> str:
"""Format the alert feature as a concise string."""
props = feature["properties"]
return (
f"Event: {props.get('event', 'unknown')}\n"
f"Area: {props.get('areaDesc', 'unknown')}\n"
f"severity: {props.get('severity', 'unknown')}\n"
f"status: {props.get('status', 'unknown')}\n"
f"title: {props.get('headline', 'untitled')}\n"
"---"
)
5. Implementing tool execution
The tool execution handler is responsible for actually executing the logic for each tool. Let's add it:
@server.call_tool()
async def handle_call_tool(
name: str, arguments: dict | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
"""
Handle the tool execution request.
The tool can get weather data and notify the client of changes.
"""
if not arguments:
raise ValueError("parameter missing")
if name == "get-alerts":
state = arguments.get("state")
if not state:
raise ValueError("state parameter missing")
# Convert state code to uppercase to ensure consistent formatting
state = state.upper()
if len(state) != 2:
raise ValueError("State code must be two letters (e.g. CA, NY)")
async with httpx.AsyncClient() as client:
alerts_url = f"{NWS_API_BASE}/alerts?area={state}"
alerts_data = await make_nws_request(client, alerts_url)
if not alerts_data:
return [types.TextContent(type="text", text="Failed to get alert data")]
features = alerts_data.get("features", [])
if not features:
return [types.TextContent(type="text", text=f"{state} has no active alerts")]
# Format each alert as a concise string
formatted_alerts = [format_alert(feature) for feature in features[:20]] # Only take the first 20 alerts
alerts_text = f"{state} Active alerts:\n\n" + "\n".join(formatted_alerts)
return [
types.TextContent(
type="text",
text=alerts_text
)
]
elif name == "get-forecast":
try:
latitude = float(arguments.get("latitude"))
longitude = float(arguments.get("longitude"))
except (TypeError, ValueError):
return [types.TextContent(
type="text",
text="Invalid coordinates. Please provide valid latitude and longitude numbers."
)]
# Basic coordinate validation
if not (-90 <= latitude <= 90) or not (-180 <= longitude <= 180):
return [types.TextContent(
type="text",
text="Invalid coordinates. Latitude must be between -90 and 90, and longitude must be between -180 and 180."
)]
async with httpx.AsyncClient() as client:
# Get the grid points first
lat_str = f"{latitude}"
lon_str = f"{longitude}"
points_url = f"{NWS_API_BASE}/points/{lat_str},{lon_str}"
points_data = await make_nws_request(client, points_url)
if not points_data:
return [types.TextContent(type="text", text=f"Failed to get grid point data for coordinates {latitude}, {longitude}. This location may not be supported by the NWS API (only US locations are supported).")]
# Extract forecast URL from response
properties = points_data.get("properties", {})
forecast_url = properties.get("forecast")
if not forecast_url:
return [types.TextContent(type="text", text="Failed to get forecast URL from grid point data")]
# Get forecast
forecast_data = await make_nws_request(client, forecast_url)
if not forecast_data:
return [types.TextContent(type="text", text="Failed to get forecast data")]
# Format forecast period
periods = forecast_data.get("properties", {}).get("periods", [])
if not periods:
return [types.TextContent(type="text", text="No forecast period available")]
# Format each period as a concise string
formatted_forecast = []
for period in periods:
forecast_text = (
f"{period.get('name', 'unknown')}:\n"
f"Temperature: {period.get('temperature', 'unknown')}°{period.get('temperatureUnit', 'F')}\n"
f"Wind: {period.get('windSpeed', 'unknown')} {period.get('windDirection', '')}\n"
f"{period.get('shortForecast', 'No forecast available')}\n"
"---"
)
formatted_forecast.append(forecast_text)
forecast_text = f"{latitude}, {longitude} forecast:\n\n" + "\n".join(formatted_forecast)
return [types.TextContent(
type="text",
text=forecast_text
)]
else:
raise ValueError(f"Unknown tool: {name}")
6. Running the server
Finally, implement the main function to run the server:
async def main():
# Run the server with standard input/output streams
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="weather",
server_version="0.1.0",
capabilities=server.get_capabilities(
notification_options=NotificationOptions(),
experimental_capabilities={},
),
),
)
# This is required if you want to connect to a custom client
if __name__ == "__main__":
asyncio.run(main())
Your server is done! Run uv run src/weather/server.py
to make sure everything is working.
Let's now test your server with an existing MCP host program, Claude for Desktop.
Test Your Server with Claude for Desktop
First, make sure you have Claude for Desktop installed.
Next, configure your MCP server in Claude for Desktop, as described in the "Claude Desktop Usage Examples" section.
Windows Configuration
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"C:\\ABSOLUTE\PATH\TO\PARENT\FOLDER\weather",
"run",
"weather"
]
}
}
}
MacOS/Linux Configuration
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
"run",
"weather"
]
}
}
}
This tells Claude for Desktop:
-
There's an MCP server named "weather".
-
Start it by running
uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather
Save the file and restart Claude for Desktop.
Now you can test your server by running the following command in Claude for Desktop:
-
What is the weather like in Sacramento?
-
What are the active weather warnings for Texas?
Behind the Scenes
When you ask a question:
-
The client sends your question to Claude.
-
Claude analyzes the available tools and decides which one to use.
-
The client executes the selected tool through the MCP server.
-
The results are returned to Claude
-
Claude organizes a natural language response
-
The response is displayed to you!
Fourth, the core MCP learning materials
As AI full book evangelist, just contact MCP is also confused, MCP in the end of 2024 or so came out, in order to develop a MCP service, looking for a lot of information to learn, I put these which is better to learn the material selected, share it with you to facilitate the reading of everyone, but also to save you from going to the Internet to look for fragmented information.
Official information
-
Official website: https://modelcontextprotocol.io
-
Protocol source code: https://github.com/modelcontextprotocol (including mcp core source code/various sdk)
Chinese learning
-
Chinese site: https://mcpcn.com (not sure if official)
-
Chinese site 2: https://modelcontextprotocol.info/zh-cn/docs/ (and the above content is basically the same)
Framework and practice
-
Examples of various language implementations: https://github.com/punkpeye/awesome-mcp-servers
-
FastMCP framework: https://github.com/jlowin/fastmcp (a python fast development mcp server framework)
-
Cursor in the configuration: https://docs.cursor.com/advanced/model-context-protocol (cursor inside the addition of mcp server instructions)
-
Cursor image generation plug-ins: https://aibook.ren/archives/mcp-server-for-cursor (This site developed a picture generated by the MCP Server )
-
970+ MCP Servers: https://www.pulsemcp.com/servers (970+ MCP Servers)
Other Practices
-
Python MCP Server development details: https://www.aisharenet.com/mcp-he-python-mcp-s/
-
Anthropic's MCP how to use: https://juejin.cn/post/7442320575749537807