MCP Servers Unleashed: Extend Claude with Custom Tool Integrations
Supercharge Claude AI with custom MCP servers: integrate proprietary data and APIs via Model Context Protocol for powerful, tailored tool use.
Introduction
Claude AI's tool use capabilities allow it to call external functions, but to truly extend its power with proprietary data sources or custom APIs, you need MCP servers. Model Context Protocol (MCP) servers act as secure intermediaries, enabling Claude to fetch real-time context, query databases, or interact with private services without exposing sensitive keys in prompts.
In this tutorial, we'll build, deploy, and integrate an MCP server step-by-step. Whether you're a developer automating workflows or a team evaluating Claude for enterprise, MCP unlocks agentic AI tailored to your stack. Expect hands-on code in Python, Claude API examples, and deployment to Vercel.
What is Model Context Protocol (MCP)?
MCP is Anthropic's standardized protocol for Claude to communicate with external servers via HTTP tool calls. Defined in Claude 3.5 Sonnet and later, it uses JSON payloads over POST requests for:
- Context Retrieval: Fetch documents, database results, or API data.
- Stateful Sessions: Maintain conversation context across calls.
- Authentication: Secure token-based access to private resources.
Unlike generic function calling, MCP ensures low-latency, structured responses optimized for Claude's XML tool_use format. Servers respond with context objects that Claude injects directly into its reasoning.
Key Benefits:
- Access proprietary data (e.g., internal CRM, knowledge bases) without fine-tuning.
- Scale Claude as an agent with tools like email, calendars, or custom ERPs.
- Enterprise-grade security: No API keys in Claude prompts.
Prerequisites
- Python 3.10+ and pip.
- Anthropic API key (from console.anthropic.com).
- Vercel account for deployment (free tier works).
- Basic familiarity with Flask and Claude's Messages API.
Install dependencies:
git clone <your-repo> # Or create new
cd mcp-server
pip install flask anthropic requests python-dotenv
Building Your First MCP Server
We'll create a simple Flask-based MCP server that queries a mock proprietary database (SQLite) for customer data.
Step 1: Project Structure
mcp-server/
├── app.py
├── requirements.txt
├── .env
├── db.sqlite
└── vercel.json
Step 2: Core MCP Endpoint
MCP requires a /mcp POST endpoint handling JSON with action, params, and session_id.
# app.py
from flask import Flask, request, jsonify
from anthropic import Anthropic # Optional for testing
import sqlite3
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
# Mock DB setup
conn = sqlite3.connect('db.sqlite', check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
c.execute("INSERT OR IGNORE INTO customers VALUES (1, 'Alice Johnson', 'alice@company.com')")
c.execute("INSERT OR IGNORE INTO customers VALUES (2, 'Bob Smith', 'bob@company.com')")
conn.commit()
@app.route('/mcp', methods=['POST'])
def mcp_handler():
data = request.json
action = data.get('action')
params = data.get('params', {})
session_id = data.get('session_id', 'default')
if action == 'query_customers':
query = params.get('query', '')
c.execute('SELECT * FROM customers WHERE name LIKE ?', (f'%{query}%',))
results = [{'id': row[0], 'name': row[1], 'email': row[2]} for row in c.fetchall()]
return jsonify({
'context': results,
'session_id': session_id,
'status': 'success'
})
return jsonify({'error': 'Unknown action'}), 400
if __name__ == '__main__':
app.run(debug=True)
Run locally: python app.py. Test with curl:
curl -X POST http://localhost:5000/mcp \
-H "Content-Type: application/json" \
-d '{"action": "query_customers", "params": {"query": "Alice"}}'
Expected: {"context": [{...}], "status": "success"}.
Defining MCP Tools in Claude API
Use Anthropic's Python SDK to define the MCP tool. Claude will parse the schema and call your server URL.
import anthropic
import os
client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
# Tool definition for MCP
mcp_tool = {
"name": "mcp_query",
"description": "Query proprietary customer database via MCP server.",
"input_schema": {
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["query_customers"]},
"params": {"type": "object", "properties": {"query": {"type": "string"}}},
"session_id": {"type": "string"}
},
"required": ["action"]
}
}
message = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
tools=[mcp_tool],
messages=[{
"role": "user",
"content": "Find customer info for Alice. Use the MCP tool if needed."
}],
tool_choice="auto" # Claude decides when to call
)
print(message.content)
# Claude will output tool_use with POST to YOUR_SERVER_URL/mcp
Important: Replace YOUR_SERVER_URL in the tool's server_url if extending the schema (MCP spec allows it). For now, hardcode in server logic or pass via params.
Testing the Integration
- Deploy locally, update tool call to
http://localhost:5000/mcp. - Run the API call above.
- Claude responds with
tool_use:{"name": "mcp_query", "input": {"action": "query_customers", "params": {"query": "Alice"}}}. - Manually simulate: POST the input to your server, feed
tool_resultback.
Full loop in code:
# After first response
if message.stop_reason == "tool_use":
tool_use = message.content[0].tool_use
# POST to your MCP server
server_resp = requests.post("http://localhost:5000/mcp", json=tool_use.input)
tool_result = {
"tool_use_id": tool_use.id,
"content": [{"type": "text", "text": str(server_resp.json())}]
}
# Second API call with tool_result
final_message = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
tools=[mcp_tool],
messages=message.messages + message.content + [tool_result],
)
print(final_message.content)
Claude now reasons: "Alice Johnson's email is alice@company.com from MCP context."
Advanced Features: Proprietary Data & Auth
Secure Private APIs
Extend for Salesforce or internal DBs:
# In mcp_handler
if action == 'salesforce_query':
sf = Salesforce(...) # Use salesforce-python-sdk
results = sf.query(params['soql'])
return jsonify({'context': results})
Authentication
Add API key validation:
@app.before_request
def auth():
key = request.headers.get('X-MCP-Key')
if key != os.getenv('MCP_SECRET'):
return jsonify({'error': 'Unauthorized'}), 401
Pass key in Claude's tool env or headers via custom agent.
Stateful Sessions
Use Redis for session_id:
import redis
r = redis.Redis(host='localhost', port=6379)
# Store/retrieve context per session
r.set(session_id, json.dumps(context))
Deployment to Vercel
- Add
vercel.json:
{
"version": 2,
"builds": [{ "src": "app.py", "use": "@vercel/python" }],
"routes": [{ "src": "/mcp", "dest": "app.py" }]
}
vercel --prod. Get URL:https://your-mcp.vercel.app.- Update Claude tool:
server_url: "https://your-mcp.vercel.app/mcp".
Costs: Free for <100k reqs/month. Scale with Upstash Redis.
Best Practices & Troubleshooting
Best Practices:
- Validate Inputs: Sanitize
paramsto prevent injection. - Rate Limiting: Use Flask-Limiter.
- Caching: Redis for frequent queries.
- Logging: Structured logs for Anthropic observability.
- Error Handling: Always return MCP-compliant
{'error': msg}.
Common Issues:
- Tool Not Called: Ensure
tool_choice="auto"and descriptive schema. - CORS: Add
flask-corsfor browser testing. - Latency: Keep server <200ms; Claude timeouts at 60s.
- XML Parsing: MCP responses must be JSON strings in tool_result.
Monitor with Vercel Analytics.
Conclusion
MCP servers turn Claude into your custom AI agent, bridging public models with private data. Start with this boilerplate, iterate for HR playbooks (employee DB), sales (CRM), or engineering (GitHub PRs). Check Anthropic docs for latest MCP spec updates.
Fork on GitHub, deploy today, and share your builds in Claude Directory comments!
Word count: ~1450
Comments
More Blog
View allBuilding Voice Agents with Claude API and ElevenLabs: Conversational AI Guide
Build natural voice agents combining Claude API's superior reasoning with ElevenLabs' lifelike TTS. This end-to-end guide creates a conversational web app with STT, AI chat, and speech synthesis.
Claude vs Mistral Large 2: 2025 Data Analysis Benchmarks and Use Cases
As data volumes explode in 2025, choosing between Claude's reasoning depth and Mistral Large 2's efficiency is critical. We benchmark SQL generation, visualizations, and large datasets to reveal the w
Claude Enterprise for Cybersecurity: Threat Modeling and Incident Response
In the high-stakes world of cybersecurity, rapid threat modeling and incident response can mean the difference between containment and catastrophe. Discover how Claude Enterprise empowers security tea
Claude Code in VS Code: Custom Commands for Refactoring Large Codebases
Refactoring sprawling codebases manually? Harness Claude Code's power in VS Code with custom commands to automate AI-driven refactors across TypeScript and Python projects—saving hours of drudgery.
Claude SDK Rust for Blockchain: Smart Contract Auditing Agents
Build blazing-fast smart contract auditing agents in Rust using the Claude SDK. Harness Claude's reasoning to scan Solidity code for vulnerabilities like reentrancy and overflows.
Advanced Claude Artifacts: Collaborative Editing in Multi-User Sessions
Elevate team productivity with Claude Artifacts in multi-user projects—enable real-time iterative editing for code reviews and docs without leaving the interface.