Anthropic MCP Lesson
No description available
Ask AI about Anthropic MCP Lesson
Powered by Claude Β· Grounded in docs
I know everything about Anthropic MCP Lesson. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
Model Context Protocol (MCP) Learning Project
π Overview
This project demonstrates the implementation and usage of the Model Context Protocol (MCP) with various tools and servers. MCP is a standardized protocol that allows AI models to securely connect to and interact with external tools and data sources.
π― Learning Objectives
By working through this project, you will learn:
- How to create MCP servers that expose tools to AI models
- How to build MCP clients that can connect to and use multiple servers
- How to implement tool-calling functionality with AI models
- How to structure a multi-server MCP architecture
- How to handle local vs remote MCP server connections
π Project Structure
MCP/
βββ π README.md # This documentation file
βββ π server_config.json # Configuration for multiple MCP servers
βββ π SECURITY.md # Security guidelines and API safety
β
βββ π€ Chatbot Implementations
β βββ chatbot.ipynb # Original notebook-based chatbot
β βββ mcp_chatbot.py # Single MCP server client
β βββ mcp_many_server_chatbot.py # Multi-server MCP client
β βββ chatbot_client.py # Alternative client implementation
β
βββ π§ Server Implementations
β βββ mcp_server_tool_creation.py # Basic MCP server creation
β βββ create_server.py # Server creation utilities
β βββ mcp_project_far/ # Research paper tools server
β βββ research_server.py # Local MCP server
β βββ remote_research_server.py # Remote MCP server
β βββ papers/ # Stored research data
β
βββ π Data Storage
βββ papers/ # Research papers database
βββ computers/
βββ mathematics/
βββ physics/
βββ quantum_physics/
π Getting Started
Prerequisites
# Required Python packages
pip install anthropic
pip install arxiv
pip install fastmcp
pip install python-dotenv
# Required Node.js packages (for MCP Inspector)
npx @modelcontextprotocol/inspectorcd C:/Users/ffarh/OneDrive/Desktop/MCP
python -m venv venv
source venv/Scripts/activate
pip install arxiv mcp anthropic python-dotenvcd C:/Users/ffarh/OneDrive/Desktop/MCP
python -m venv venv
source venv/Scripts/activate
pip install arxiv mcp anthropic python-dotenvcd C:/Users/ffarh/OneDrive/Desktop/MCP
python -m venv venv
source venv/Scripts/activate
pip install arxiv mcp anthropic python-dotenv
Environment Setup
- Create a
.envfile in your project root:
ANTHROPIC_API_KEY=your_anthropic_api_key_here
# Add other API keys as needed
- Activate your virtual environment:
source venv/Scripts/activate # Windows
# or
source venv/bin/activate # Linux/Mac
π Core Concepts
1. What is MCP?
Model Context Protocol (MCP) is a standardized way for AI models to:
- Connect to external tools and services
- Execute functions safely and reliably
- Exchange data in a structured format
- Scale across multiple tool providers
2. MCP Architecture
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β AI Model β β MCP Client β β MCP Server β
β (Claude) βββββΊβ (Your App) βββββΊβ (Tools) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
- AI Model: The language model (e.g., Claude) that needs tools
- MCP Client: Your application that manages tool connections
- MCP Server: Services that expose tools via MCP protocol
3. Transport Methods
Local (stdio)
# Direct process communication
server_config = {
"command": "python",
"args": ["server.py"]
}
Remote (SSE - Server-Sent Events)
# HTTP-based communication
server_url = "http://localhost:8001/sse"
π οΈ Implementation Examples
1. Basic MCP Server (mcp_server_tool_creation.py)
from mcp.server.fastmcp import FastMCP
# Initialize MCP server
mcp = FastMCP("my_server")
@mcp.tool()
def my_function(param: str) -> str:
"""Tool description for the AI model"""
return f"Result: {param}"
if __name__ == "__main__":
mcp.run()
Key Concepts:
@mcp.tool()decorator exposes functions as tools- Function docstrings become tool descriptions
- Type hints help with parameter validation
2. Research Paper Server (remote_research_server.py)
This server provides tools for:
- Searching arXiv papers by topic
- Extracting paper information by ID
- Storing results in JSON format
@mcp.tool()
def search_papers(topic: str, max_results: int = 5) -> List[str]:
"""Search for papers on arXiv based on a topic"""
# Implementation details...
@mcp.tool()
def extract_info(paper_id: str) -> str:
"""Get detailed information about a specific paper"""
# Implementation details...
3. Multi-Server Client (mcp_many_server_chatbot.py)
This client can connect to multiple MCP servers simultaneously:
class MCPChatbot:
def __init__(self):
self.servers = {}
self.available_tools = []
async def connect_to_servers(self):
"""Connect to all configured MCP servers"""
for server_name, config in server_configs.items():
# Connect to each server
# Collect available tools
Benefits:
- Access tools from multiple sources
- Centralized tool management
- Scalable architecture
π§ Running the Project
Option 1: Single Server Setup
- Start the research server:
cd mcp_project_far
python remote_research_server.py
- Run the MCP Inspector (in another terminal):
npx @modelcontextprotocol/inspector
- Connect via Inspector:
- URL:
http://localhost:8001/sse - Transport: SSE
- Connection: Via Proxy
- URL:
Option 2: Multi-Server Setup
- Configure servers in
server_config.json - Run the multi-server client:
python mcp_many_server_chatbot.py
ποΈ Configuration Files
server_config.json
{
"mcpServers": {
"far_research_assistant": {
"command": "python",
"args": ["mcp_project_far/research_server.py"]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/directory"]
}
}
}
Configuration Options:
- command: Executable to run the server
- args: Arguments passed to the command
- env: Environment variables (if needed)
π Tool Examples
Research Tools
# Search for papers
search_papers("machine learning", max_results=3)
# Returns: ["paper_id_1", "paper_id_2", "paper_id_3"]
# Get paper details
extract_info("2301.07041")
# Returns: JSON with title, authors, summary, etc.
Filesystem Tools
# Read file
read_file("/path/to/file.txt")
# Write file
write_file("/path/to/output.txt", "content")
# List directory
list_directory("/path/to/directory")
π¨ Security Considerations
API Key Management
- β DO: Use environment variables for API keys
- β
DO: Use
.envfiles that are gitignored - β DON'T: Hardcode API keys in source code
- β DON'T: Commit API keys to version control
Example Safe Implementation:
from dotenv import load_dotenv
import os
load_dotenv()
client = Anthropic() # Reads from ANTHROPIC_API_KEY env var
File Access Security
- MCP servers should validate file paths
- Restrict access to specific directories
- Validate user inputs to prevent path traversal
π Troubleshooting
Common Issues
1. "Connection failed" Error
# Check if server is running
python remote_research_server.py
# Verify the port is correct
netstat -an | findstr 8001
2. "404 Not Found" from MCP Server
- Ensure the server exposes MCP endpoints (usually
/sse) - Try different transport methods (stdio vs SSE)
- Check server logs for errors
3. "Tool not found" Error
- Verify tool registration with
@mcp.tool()decorator - Check tool name spelling in client calls
- Ensure server is properly connected
4. Import Errors
# Install missing packages
pip install anthropic arxiv fastmcp python-dotenv
# Verify virtual environment is activated
which python
π Advanced Topics
Custom Tool Schemas
@mcp.tool()
def advanced_search(
query: str,
filters: Dict[str, Any],
sort_by: Literal["relevance", "date"] = "relevance"
) -> Dict[str, Any]:
"""Advanced search with complex parameters"""
pass
Error Handling
@mcp.tool()
def robust_function(param: str) -> str:
try:
# Tool logic here
return result
except Exception as e:
return f"Error: {str(e)}"
Async Tools
@mcp.tool()
async def async_function(param: str) -> str:
"""Asynchronous tool execution"""
result = await some_async_operation(param)
return result
π Learning Path
Beginner Level
- Start with
chatbot.ipynbto understand basic concepts - Run
mcp_server_tool_creation.pyto create your first server - Use MCP Inspector to test your tools
Intermediate Level
- Study
mcp_chatbot.pyfor single-server client implementation - Create custom tools for your specific use case
- Learn about different transport methods
Advanced Level
- Implement
mcp_many_server_chatbot.pyfor multi-server architecture - Create production-ready error handling and logging
- Deploy servers remotely and manage authentication
π Additional Resources
π€ Contributing
This is a learning project. Feel free to:
- Add new tools and servers
- Improve error handling
- Enhance documentation
- Share your implementations
π License
This project is for educational purposes. Please respect API terms of service and rate limits when using external services.
This documentation is part of a comprehensive MCP learning project. Each file in this directory serves a specific educational purpose and demonstrates different aspects of MCP implementation.
