Skip to main content

MCP Examples

Complete examples of MCP tools in action.

Order Management Example

Tool Schema

{
"name": "get_order_status",
"description": "Get order status and details",
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "Order ID",
"required": true
}
}
}
}

Use in Agent

import requests

# Create agent with order tool
response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "order_agent",
"system_prompt": "Help users check order status and manage orders.",
"model": "gpt-4",
"builtin_tools": [],
"mcp_servers": ["ORDER_API"],
"tool_choice": "auto",
"max_iterations": 3
}
)

agent_id = response.json()["id"]

# Chat with agent
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "What's the status of order #12345?"
}
)

result = chat_response.json()
print(f"Response: {result['response']}")
print(f"Tool used: {result['tool_calls'][0]['tool_name']}")

Weather Service Example

Tool Schema

{
"name": "get_weather",
"description": "Get current weather and forecast",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name or postal code",
"required": true
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius"
}
}
}
}

Use in Agent

import requests

# Create agent with weather tool
response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "weather_agent",
"system_prompt": "Provide current weather information and forecasts.",
"model": "gpt-4",
"builtin_tools": [],
"mcp_servers": ["WEATHER"],
"tool_choice": "auto",
"max_iterations": 2
}
)

agent_id = response.json()["id"]

# Chat with agent
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "What's the weather like in New York?"
}
)

result = chat_response.json()
print(f"Response: {result['response']}")

CRM Integration Example

Tool Schema

{
"name": "get_customer_info",
"description": "Retrieve customer information from CRM",
"parameters": {
"type": "object",
"properties": {
"customer_id": {
"type": "string",
"description": "Customer ID",
"required": true
},
"include_orders": {
"type": "boolean",
"default": true
}
}
}
}

Use in Agent

import requests

# Create agent with CRM tool
response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "support_agent",
"system_prompt": "Help customers with their account and orders.",
"model": "gpt-4",
"builtin_tools": [],
"mcp_servers": ["CRM"],
"tool_choice": "auto",
"max_iterations": 5
}
)

agent_id = response.json()["id"]

# Chat with agent
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "When was my last order and what was it?"
}
)

result = chat_response.json()
print(f"Response: {result['response']}")

Multi-Tool Agent Example

Configure Multiple MCP Servers

# In .env file
MCP_ORDER_API_URL=https://orders.api.com
MCP_ORDER_API_KEY=order_key
MCP_WEATHER_URL=https://weather.api.com
MCP_WEATHER_KEY=weather_key
MCP_CRM_URL=https://crm.api.com
MCP_CRM_TOKEN=crm_token

Create Agent

import requests

response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "full_support_agent",
"system_prompt": "Comprehensive support agent with access to orders, weather, and customer data.",
"model": "gpt-4",
"builtin_tools": [],
"mcp_servers": ["ORDER_API", "WEATHER", "CRM"],
"tool_choice": "auto",
"max_iterations": 10
}
)

agent_id = response.json()["id"]

Complex Query

# Query that uses multiple tools
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "Check order #12345 status. If it's shipped, will the weather affect delivery?"
}
)

result = chat_response.json()
print(f"Response: {result['response']}")

# Show tools used
print("\nTools used:")
for tool_call in result.get('tool_calls', []):
print(f" - {tool_call['tool_name']}")

Custom Data Analysis Tool

Tool Schema

{
"name": "analyze_sales_data",
"description": "Analyze sales data from internal database",
"parameters": {
"type": "object",
"properties": {
"time_range": {
"type": "string",
"enum": ["week", "month", "quarter", "year"],
"required": true
},
"metrics": {
"type": "array",
"description": "Metrics to calculate",
"default": ["total_sales", "avg_order_value", "top_products"]
}
}
}
}

Use in Agent

import requests

# Create agent
response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "analytics_agent",
"system_prompt": "Analyze sales data and provide insights.",
"model": "gpt-4",
"builtin_tools": [],
"mcp_servers": ["ANALYTICS"],
"tool_choice": "auto",
"max_iterations": 5
}
)

agent_id = response.json()["id"]

# Query analytics
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "What are our top selling products this month?"
}
)

result = chat_response.json()
print(f"Analysis: {result['response']}")

React Integration

import React, { useState } from 'react';

function MCPSupport() {
const [agentId, setAgentId] = useState('');
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);

const createAgent = async () => {
try {
const res = await fetch('http://localhost/api/v1/agent/configs', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'order_agent',
system_prompt: 'Help users with order inquiries.',
model: 'gpt-4',
builtin_tools: [],
mcp_servers: ['ORDER_API'],
tool_choice: 'auto',
max_iterations: 3
})
});

const agent = await res.json();
setAgentId(agent.id);
} catch (error) {
console.error('Error creating agent:', error);
}
};

const sendMessage = async () => {
if (!message.trim() || loading) return;

setLoading(true);
try {
const res = await fetch('http://localhost/api/v1/agent/chat', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
agent_id: agentId,
message
})
});

const result = await res.json();
setResponse(result.response);
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};

return (
<div className="p-6">
{!agentId ? (
<button
onClick={createAgent}
className="px-4 py-2 bg-blue-500 text-white rounded"
>
Create Agent
</button>
) : (
<div>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Ask about your order..."
className="w-full p-2 border rounded"
rows={3}
/>

<button
onClick={sendMessage}
disabled={loading || !message}
className="mt-2 px-4 py-2 bg-green-500 text-white rounded"
>
{loading ? 'Sending...' : 'Send'}
</button>

{response && (
<div className="mt-4 p-4 bg-gray-100 rounded">
<h3 className="font-bold mb-2">Response:</h3>
<p>{response}</p>
</div>
)}
</div>
)}
</div>
);
}

export default MCPSupport;

Error Handling Example

import requests
from requests.exceptions import RequestException

def safe_mcp_chat(agent_id, message, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": message
},
timeout=30
)

response.raise_for_status()
return response.json()

except RequestException as e:
if attempt == max_retries - 1:
raise
print(f"Attempt {attempt + 1} failed. Retrying...")
time.sleep(2 ** attempt)

# Use with error handling
try:
result = safe_mcp_chat(agent_id, "Check order status")
print(f"Response: {result['response']}")
except Exception as e:
print(f"All attempts failed: {e}")

Best Practices

  1. Clear tool names - Use descriptive, action-oriented names
  2. Detailed descriptions - Explain tool purpose and parameters
  3. Error messages - Provide helpful error information
  4. Retry logic - Handle transient failures gracefully
  5. Testing - Test tools thoroughly in production
  6. Monitoring - Track tool usage and performance

Next Steps