What is MCP?
Model Context Protocol (MCP) is an open standard developed by Anthropic that enables AI agents to connect with external tools, data sources, and services in a standardized way. Think of it as a "USB for AI" - a universal interface that lets any AI model work with any compatible tool.
Before MCP, every AI application needed custom integrations for each tool. MCP changes this by providing:
- Standardized interface: One protocol for all tool integrations
- Discoverability: AI can discover available tools and their capabilities
- Security: Built-in permission and authentication handling
- Interoperability: Tools work across different AI models and platforms
Why MCP Matters
The AI ecosystem faced a fragmentation problem:
Before MCP
Each AI app needed custom code for every tool. 10 apps + 10 tools = 100 integrations.
With MCP
Tools implement MCP once, work everywhere. 10 apps + 10 tools = 20 implementations.
MCP is becoming the industry standard because:
- Anthropic's Claude natively supports MCP
- Major platforms (VS Code, JetBrains, etc.) are adopting it
- It's open-source and vendor-neutral
- Growing ecosystem of pre-built MCP servers
MCP Architecture
MCP uses a client-server architecture with three main components:
1. MCP Hosts
Applications that want to use AI capabilities (Claude Desktop, IDEs, custom apps).
2. MCP Clients
Protocol handlers within host applications that manage server connections.
3. MCP Servers
Services that expose tools, resources, and prompts via the MCP protocol.
# MCP Communication Flow
┌─────────────┐ MCP Protocol ┌─────────────┐
│ │ ◄──────────────────► │ │
│ MCP Host │ (JSON-RPC) │ MCP Server │
│ (Claude) │ │ (Tools) │
│ │ │ │
└─────────────┘ └─────────────┘
│ │
│ │
▼ ▼
User Interface External Services
(Chat, IDE, etc.) (APIs, Databases, etc.)
Core MCP Concepts
Tools
Functions that the AI can invoke to perform actions:
# Example MCP Tool Definition
{
"name": "search_database",
"description": "Search the customer database",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query"
},
"limit": {
"type": "integer",
"default": 10
}
},
"required": ["query"]
}
}
Resources
Data sources that provide context to the AI (files, database records, API responses):
# Example MCP Resource
{
"uri": "file:///project/README.md",
"name": "Project README",
"mimeType": "text/markdown",
"description": "Project documentation"
}
Prompts
Pre-defined prompt templates that can be reused:
# Example MCP Prompt
{
"name": "code_review",
"description": "Review code for issues",
"arguments": [
{
"name": "code",
"description": "Code to review",
"required": true
}
]
}
Building an MCP Server
Here's how to create a simple MCP server in Python:
Installation
pip install mcp
Basic MCP Server
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import asyncio
# Create server instance
server = Server("my-tools")
# Define available tools
@server.list_tools()
async def list_tools():
return [
Tool(
name="get_weather",
description="Get current weather for a city",
inputSchema={
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
}
},
"required": ["city"]
}
),
Tool(
name="calculate",
description="Perform mathematical calculations",
inputSchema={
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression to evaluate"
}
},
"required": ["expression"]
}
)
]
# Handle tool execution
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "get_weather":
city = arguments["city"]
# In reality, call a weather API
return [TextContent(
type="text",
text=f"Weather in {city}: 22°C, Sunny"
)]
elif name == "calculate":
expression = arguments["expression"]
try:
result = eval(expression) # Use safe eval in production!
return [TextContent(
type="text",
text=f"Result: {result}"
)]
except Exception as e:
return [TextContent(
type="text",
text=f"Error: {str(e)}"
)]
# Run the server
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
asyncio.run(main())
MCP Server with Resources
Expose data as resources that AI can access:
from mcp.server import Server
from mcp.types import Resource, TextContent
import os
server = Server("file-server")
@server.list_resources()
async def list_resources():
# List files in a directory
files = os.listdir("./documents")
return [
Resource(
uri=f"file:///documents/{f}",
name=f,
mimeType="text/plain"
)
for f in files if f.endswith('.txt')
]
@server.read_resource()
async def read_resource(uri: str):
# Extract filename from URI
path = uri.replace("file:///", "")
with open(path, 'r') as f:
content = f.read()
return TextContent(type="text", text=content)
Configuring MCP in Claude Desktop
To use MCP servers with Claude Desktop, configure them in the settings:
# claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/)
# (Windows: %APPDATA%\Claude\)
{
"mcpServers": {
"my-tools": {
"command": "python",
"args": ["/path/to/my_mcp_server.py"],
"env": {
"API_KEY": "your-api-key"
}
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/allowed/directory"
]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "your-github-token"
}
}
}
}
Popular MCP Servers
The MCP ecosystem includes many pre-built servers:
Filesystem
Read, write, and manage files on your computer.
GitHub
Interact with repositories, issues, and pull requests.
PostgreSQL
Query and manage PostgreSQL databases.
Slack
Send messages and interact with Slack workspaces.
Google Drive
Access and manage files in Google Drive.
Brave Search
Perform web searches using Brave Search API.
Installing Pre-built Servers
# Install via npm
npx -y @modelcontextprotocol/server-filesystem /path/to/directory
npx -y @modelcontextprotocol/server-github
npx -y @modelcontextprotocol/server-postgres postgresql://localhost/mydb
# Or via uvx (Python)
uvx mcp-server-sqlite --db-path /path/to/database.db
MCP with LangChain
Integrate MCP tools into LangChain applications:
from langchain_mcp import MCPToolkit
from langchain_anthropic import ChatAnthropic
from langchain.agents import create_tool_calling_agent, AgentExecutor
# Connect to MCP server
toolkit = MCPToolkit(
server_command="python",
server_args=["my_mcp_server.py"]
)
# Get tools from MCP server
tools = toolkit.get_tools()
# Create agent with MCP tools
llm = ChatAnthropic(model="claude-3-sonnet-20240229")
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)
# Run agent
result = executor.invoke({
"input": "What's the weather in Tokyo?"
})
Security Considerations
MCP includes security features, but you should also:
- Validate inputs: Always sanitize and validate tool inputs
- Limit permissions: Only expose necessary capabilities
- Use authentication: Protect sensitive operations with auth tokens
- Audit logging: Log all tool invocations for security review
- Sandboxing: Run MCP servers in isolated environments when possible
# Example: Input validation in MCP tool
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "execute_query":
query = arguments.get("query", "")
# Validate: prevent SQL injection
if any(dangerous in query.lower()
for dangerous in ["drop", "delete", "truncate", "update"]):
return [TextContent(
type="text",
text="Error: Dangerous operation not allowed"
)]
# Validate: limit query length
if len(query) > 1000:
return [TextContent(
type="text",
text="Error: Query too long"
)]
# Execute safely...
result = await safe_execute_query(query)
return [TextContent(type="text", text=result)]
Best Practices
- Clear descriptions: Write detailed tool descriptions so the AI knows when to use them
- Proper schemas: Define complete input schemas with types and descriptions
- Error handling: Return helpful error messages that the AI can understand
- Idempotency: Design tools to be safe for repeated invocation
- Rate limiting: Protect external APIs from excessive calls
- Timeout handling: Set appropriate timeouts for long-running operations
Master MCP with Expert Mentorship
Our Agentic AI program covers MCP and tool integration in-depth. Learn to build production-ready AI agents that seamlessly connect to external systems.
Explore Agentic AI Program