test_individual_tools.py•8.75 kB
#!/usr/bin/env python3
"""
MCP Tools Testing Guide
This script demonstrates different ways to test your MCP tools
"""
import asyncio
import os
from dotenv import load_dotenv
from fastmcp import Client
# Load environment variables
load_dotenv()
async def test_individual_tools():
"""Test each MCP tool individually with examples"""
print("=" * 60)
print("INDIVIDUAL MCP TOOL TESTING")
print("=" * 60)
try:
async with Client("server.py") as client:
# Test 1: Dice Rolling Tool
print("\n1. DICE ROLLING TOOL")
print("-" * 30)
dice_examples = [
("1d20", "Single d20 roll"),
("2d6", "Two d6 rolls"),
("3d20k1", "Three d20 rolls, keep highest (advantage)"),
("4d6k3", "Four d6 rolls, keep highest 3"),
("1d100", "Percentile roll"),
("2d10", "Two d10 rolls")
]
for notation, description in dice_examples:
try:
result = await client.call_tool("roll_dice", {"notation": notation})
text_content = result.content[0].text if result.content else str(result)
print(f" {notation:8} ({description:30}) → {text_content}")
except Exception as e:
print(f" {notation:8} ERROR: {e}")
# Test 2: Web Search Tool
print("\n2. WEB SEARCH TOOL")
print("-" * 30)
if os.getenv("TAVILY_API_KEY"):
search_examples = [
"What is the latest news about AI?",
"Python programming best practices",
"Stock market trends today"
]
for query in search_examples:
try:
result = await client.call_tool("web_search", {"query": query})
text_content = result.content[0].text if result.content else str(result)
print(f" Query: {query}")
print(f" Result: {text_content[:100]}...")
print()
except Exception as e:
print(f" Query: {query} → ERROR: {e}")
else:
print(" SKIPPED: TAVILY_API_KEY not set")
# Test 3: Stock Data Tool
print("\n3. STOCK DATA TOOL")
print("-" * 30)
if os.getenv("POLYGON_API_KEY"):
stock_examples = [
("AAPL", "Apple Inc."),
("MSFT", "Microsoft"),
("GOOGL", "Alphabet"),
("TSLA", "Tesla"),
("NVDA", "NVIDIA")
]
for symbol, company in stock_examples:
try:
result = await client.call_tool("get_stock_ohlc", {"symbol": symbol})
text_content = result.content[0].text if result.content else str(result)
print(f" {symbol} ({company})")
print(f" {text_content}")
print()
except Exception as e:
print(f" {symbol} ERROR: {e}")
else:
print(" SKIPPED: POLYGON_API_KEY not set")
except Exception as e:
print(f"ERROR: Failed to connect to MCP server: {e}")
async def test_interactive_scenarios():
"""Test realistic scenarios that combine multiple tools"""
print("\n" + "=" * 60)
print("REALISTIC SCENARIOS TESTING")
print("=" * 60)
try:
async with Client("server.py") as client:
# Scenario 1: Gaming Session
print("\nSCENARIO 1: D&D Gaming Session")
print("-" * 40)
# Roll for initiative
initiative = await client.call_tool("roll_dice", {"notation": "1d20"})
print(f" Initiative Roll: {initiative.content[0].text}")
# Roll for attack
attack = await client.call_tool("roll_dice", {"notation": "1d20"})
print(f" Attack Roll: {attack.content[0].text}")
# Roll damage
damage = await client.call_tool("roll_dice", {"notation": "2d6"})
print(f" Damage Roll: {damage.content[0].text}")
# Scenario 2: Investment Research
print("\nSCENARIO 2: Investment Research")
print("-" * 40)
if os.getenv("POLYGON_API_KEY") and os.getenv("TAVILY_API_KEY"):
# Get stock data
stock_data = await client.call_tool("get_stock_ohlc", {"symbol": "AAPL"})
print(f" Apple Stock Data:")
print(f" {stock_data.content[0].text}")
# Search for news
news = await client.call_tool("web_search", {"query": "Apple stock news today"})
print(f" Apple News: {news.content[0].text[:200]}...")
else:
print(" SKIPPED: Missing API keys")
# Scenario 3: Decision Making
print("\nSCENARIO 3: Decision Making")
print("-" * 40)
# Roll for random decision
decision = await client.call_tool("roll_dice", {"notation": "1d4"})
print(f" Decision Roll (1-4): {decision.content[0].text}")
# Search for information to help with decision
if os.getenv("TAVILY_API_KEY"):
info = await client.call_tool("web_search", {"query": "decision making strategies"})
print(f" Decision Help: {info.content[0].text[:150]}...")
except Exception as e:
print(f"ERROR: Failed to run scenarios: {e}")
def print_testing_guide():
"""Print comprehensive testing guide"""
print("\n" + "=" * 60)
print("COMPREHENSIVE MCP TESTING GUIDE")
print("=" * 60)
print("""
METHOD 1: Using Our Test Scripts
===============================
1. Run comprehensive test:
python test_mcp_functionality.py
2. Run individual tool tests:
python test_individual_tools.py
METHOD 2: Direct MCP Server Testing
===================================
1. Start MCP server:
python server.py
2. In another terminal, use MCP CLI:
mcp list-tools server.py
mcp call-tool server.py roll_dice '{"notation": "1d20"}'
mcp call-tool server.py web_search '{"query": "test"}'
mcp call-tool server.py get_stock_ohlc '{"symbol": "AAPL"}'
METHOD 3: LangGraph Agent Integration
=====================================
1. Test with LangGraph agent:
python test_agent.py
2. Or run the agent directly:
python langgraph_agent.py
METHOD 4: Individual Tool Testing
================================
1. Test dice roller directly:
python dice_roller.py
2. Test Polygon API directly:
python polygon_api.py
METHOD 5: Custom Testing Scripts
================================
Create your own test scripts using the fastmcp Client:
```python
from fastmcp import Client
import asyncio
async def test_my_tools():
async with Client("server.py") as client:
# Test any tool
result = await client.call_tool("tool_name", {"param": "value"})
print(result.content[0].text)
asyncio.run(test_my_tools())
```
EXAMPLE COMMANDS TO TRY:
=======================
Dice Rolling:
- roll_dice: {"notation": "1d20"}
- roll_dice: {"notation": "2d6"}
- roll_dice: {"notation": "3d20k1"}
- roll_dice: {"notation": "4d6k3"}
Web Search:
- web_search: {"query": "latest AI news"}
- web_search: {"query": "Python programming tips"}
- web_search: {"query": "stock market analysis"}
Stock Data:
- get_stock_ohlc: {"symbol": "AAPL"}
- get_stock_ohlc: {"symbol": "MSFT"}
- get_stock_ohlc: {"symbol": "GOOGL"}
- get_stock_ohlc: {"symbol": "TSLA"}
TROUBLESHOOTING:
===============
1. Make sure .env file has all API keys:
- TAVILY_API_KEY=your_key_here
- POLYGON_API_KEY=your_key_here
2. Check dependencies are installed:
pip install fastmcp mcp[cli] tavily-python
3. Verify server.py is working:
python server.py
4. Test individual components:
python dice_roller.py
python polygon_api.py
""")
if __name__ == "__main__":
print("MCP Tools Testing Guide")
print("=" * 60)
# Run individual tool tests
asyncio.run(test_individual_tools())
# Run scenario tests
asyncio.run(test_interactive_scenarios())
# Print comprehensive guide
print_testing_guide()