🔌 API Examples
Practical examples and code samples for integrating with the Nexus MCP Server HTTP API across different programming languages.
🎯 Base URL: All examples assume the server is running at
http://localhost:9999. Adjust the URL according to your deployment.
🚀 Getting Started
Health Check
Verify Server Status
# Using curl
curl http://localhost:9999/
# Using httpie
http GET localhost:9999
Expected Response:
{
"status": "healthy",
"message": "Nexus MCP Server Enhanced API is running",
"tools_count": 39,
"server_info": {
"name": "NexusServer-Enhanced",
"version": "3.0.0",
"type": "HTTP-MCP Bridge"
}
}
List Available Tools
Discover Tools
# Get all tools
curl http://localhost:9999/tools
# Get tools with detailed schemas
curl http://localhost:9999/tools?include_schema=true
🐍 Python Examples
Basic API Client
Simple Python Client
import requests
import json
class NexusClient:
def __init__(self, base_url="http://localhost:9999"):
self.base_url = base_url
self.session = requests.Session()
def health_check(self):
"""Check server health"""
response = self.session.get(f"{self.base_url}/")
return response.json()
def list_tools(self, include_schema=False):
"""List available tools"""
params = {"include_schema": include_schema} if include_schema else {}
response = self.session.get(f"{self.base_url}/tools", params=params)
return response.json()
def execute_tool(self, tool_name, arguments=None):
"""Execute a tool with given arguments"""
payload = {
"tool_name": tool_name,
"arguments": arguments or {}
}
response = self.session.post(
f"{self.base_url}/execute",
json=payload,
headers={"Content-Type": "application/json"}
)
return response.json()
# Usage example
client = NexusClient()
# Check server health
health = client.health_check()
print(f"Server status: {health['status']}")
# List tools
tools = client.list_tools()
print(f"Available tools: {len(tools['tools'])}")
# Execute a simple math operation
result = client.execute_tool("add", {"a": 5, "b": 3})
print(f"5 + 3 = {result['result']}")
Advanced Python Examples
File Operations
def file_operations_example():
client = NexusClient()
# Create a file
create_result = client.execute_tool("create_file", {
"path": "test.txt",
"content": "Hello, Nexus!"
})
print(f"File created: {create_result}")
# Read the file
read_result = client.execute_tool("read_file", {
"path": "test.txt"
})
print(f"File content: {read_result['content']}")
# List files in directory
list_result = client.execute_tool("list_files", {
"path": "."
})
print(f"Files: {list_result['files']}")
file_operations_example()
System Information
def system_info_example():
client = NexusClient()
# Get system information
sys_info = client.execute_tool("get_system_info")
print("System Info:")
for key, value in sys_info['result'].items():
print(f" {key}: {value}")
# Check disk usage
disk_usage = client.execute_tool("get_disk_usage", {"path": "/"})
print(f"Disk usage: {disk_usage}")
# Get current time
current_time = client.execute_tool("get_current_time")
print(f"Current time: {current_time['result']}")
system_info_example()
🟨 JavaScript Examples
Node.js Client
Node.js with Axios
const axios = require('axios');
class NexusClient {
constructor(baseUrl = 'http://localhost:9999') {
this.baseUrl = baseUrl;
this.client = axios.create({
baseURL: baseUrl,
headers: {
'Content-Type': 'application/json'
}
});
}
async healthCheck() {
try {
const response = await this.client.get('/');
return response.data;
} catch (error) {
throw new Error(`Health check failed: ${error.message}`);
}
}
async listTools(includeSchema = false) {
const params = includeSchema ? { include_schema: true } : {};
const response = await this.client.get('/tools', { params });
return response.data;
}
async executeTool(toolName, arguments = {}) {
const payload = {
tool_name: toolName,
arguments: arguments
};
const response = await this.client.post('/execute', payload);
return response.data;
}
}
// Usage example
async function main() {
const client = new NexusClient();
try {
// Check health
const health = await client.healthCheck();
console.log(`Server status: ${health.status}`);
// List tools
const tools = await client.listTools();
console.log(`Available tools: ${tools.tools.length}`);
// Execute calculator
const result = await client.executeTool('multiply', { a: 6, b: 7 });
console.log(`6 * 7 = ${result.result}`);
} catch (error) {
console.error('Error:', error.message);
}
}
main();
Browser JavaScript
Browser Fetch API
class BrowserNexusClient {
constructor(baseUrl = 'http://localhost:9999') {
this.baseUrl = baseUrl;
}
async makeRequest(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...options.headers
},
...options
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
async executeTool(toolName, arguments = {}) {
return await this.makeRequest('/execute', {
method: 'POST',
body: JSON.stringify({
tool_name: toolName,
arguments: arguments
})
});
}
}
// Usage in web page
document.addEventListener('DOMContentLoaded', async () => {
const client = new BrowserNexusClient();
// Example: Random number generation
const randomResult = await client.executeTool('generate_random_number', {
min: 1,
max: 100
});
document.getElementById('result').textContent =
`Random number: ${randomResult.result}`;
});
🌐 cURL Examples
Basic Operations
Mathematical Operations
# Addition
curl -X POST http://localhost:9999/execute \
-H "Content-Type: application/json" \
-d '{"tool_name": "add", "arguments": {"a": 10, "b": 5}}'
# Subtraction
curl -X POST http://localhost:9999/execute \
-H "Content-Type: application/json" \
-d '{"tool_name": "subtract", "arguments": {"a": 10, "b": 3}}'
# Calculate percentage
curl -X POST http://localhost:9999/execute \
-H "Content-Type: application/json" \
-d '{"tool_name": "calculate_percentage", "arguments": {"value": 25, "total": 200}}'
Text Processing
String Operations
# Count words
curl -X POST http://localhost:9999/execute \
-H "Content-Type: application/json" \
-d '{"tool_name": "count_words", "arguments": {"text": "Hello world from Nexus"}}'
# Convert to uppercase
curl -X POST http://localhost:9999/execute \
-H "Content-Type: application/json" \
-d '{"tool_name": "to_uppercase", "arguments": {"text": "hello nexus"}}'
# Generate UUID
curl -X POST http://localhost:9999/execute \
-H "Content-Type: application/json" \
-d '{"tool_name": "generate_uuid"}'
🐹 Go Examples
Go HTTP Client
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type NexusClient struct {
BaseURL string
Client *http.Client
}
type ExecuteRequest struct {
ToolName string `json:"tool_name"`
Arguments map[string]interface{} `json:"arguments"`
}
type ExecuteResponse struct {
Result interface{} `json:"result"`
Error string `json:"error,omitempty"`
}
func NewNexusClient(baseURL string) *NexusClient {
return &NexusClient{
BaseURL: baseURL,
Client: &http.Client{},
}
}
func (nc *NexusClient) ExecuteTool(toolName string, args map[string]interface{}) (*ExecuteResponse, error) {
reqBody := ExecuteRequest{
ToolName: toolName,
Arguments: args,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
resp, err := nc.Client.Post(
nc.BaseURL+"/execute",
"application/json",
bytes.NewBuffer(jsonData),
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result ExecuteResponse
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return &result, nil
}
func main() {
client := NewNexusClient("http://localhost:9999")
// Example: Calculate factorial
result, err := client.ExecuteTool("factorial", map[string]interface{}{
"n": 5,
})
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Factorial of 5: %v\n", result.Result)
}
🚨 Error Handling
Robust Error Handling (Python)
import requests
from requests.exceptions import RequestException, Timeout, ConnectionError
class NexusAPIError(Exception):
"""Custom exception for Nexus API errors"""
pass
class RobustNexusClient:
def __init__(self, base_url="http://localhost:9999", timeout=30):
self.base_url = base_url
self.timeout = timeout
self.session = requests.Session()
def execute_tool_safe(self, tool_name, arguments=None, retries=3):
"""Execute tool with comprehensive error handling"""
payload = {
"tool_name": tool_name,
"arguments": arguments or {}
}
for attempt in range(retries):
try:
response = self.session.post(
f"{self.base_url}/execute",
json=payload,
timeout=self.timeout,
headers={"Content-Type": "application/json"}
)
# Check HTTP status
response.raise_for_status()
result = response.json()
# Check for API-level errors
if 'error' in result:
raise NexusAPIError(f"Tool execution failed: {result['error']}")
return result
except ConnectionError:
if attempt == retries - 1:
raise NexusAPIError("Unable to connect to Nexus server")
print(f"Connection failed, retrying... ({attempt + 1}/{retries})")
except Timeout:
if attempt == retries - 1:
raise NexusAPIError("Request timed out")
print(f"Request timed out, retrying... ({attempt + 1}/{retries})")
except requests.HTTPError as e:
raise NexusAPIError(f"HTTP error: {e.response.status_code}")
except ValueError as e:
raise NexusAPIError(f"Invalid JSON response: {e}")
raise NexusAPIError("Max retries exceeded")
# Usage with error handling
client = RobustNexusClient()
try:
result = client.execute_tool_safe("divide", {"a": 10, "b": 0})
print(result)
except NexusAPIError as e:
print(f"API Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
📦 Batch Operations
Multiple Tool Execution
async def batch_execute_example():
"""Execute multiple tools concurrently"""
import asyncio
import aiohttp
async def execute_tool_async(session, tool_name, arguments):
payload = {
"tool_name": tool_name,
"arguments": arguments
}
async with session.post(
"http://localhost:9999/execute",
json=payload
) as response:
return await response.json()
async with aiohttp.ClientSession() as session:
tasks = [
execute_tool_async(session, "add", {"a": 1, "b": 2}),
execute_tool_async(session, "multiply", {"a": 3, "b": 4}),
execute_tool_async(session, "subtract", {"a": 10, "b": 5}),
execute_tool_async(session, "divide", {"a": 20, "b": 4}),
]
results = await asyncio.gather(*tasks)
for i, result in enumerate(results):
print(f"Task {i + 1}: {result}")
# Run batch operations
asyncio.run(batch_execute_example())
🛠️ Dynamic Tool Creation
Creating Custom Tools
def create_custom_tool_example():
"""Example of creating and using dynamic tools"""
client = NexusClient()
# Create a custom Python tool
tool_code = '''
def process_data(data_list, operation="sum"):
"""Process a list of numbers with specified operation"""
if operation == "sum":
return sum(data_list)
elif operation == "average":
return sum(data_list) / len(data_list) if data_list else 0
elif operation == "max":
return max(data_list) if data_list else None
elif operation == "min":
return min(data_list) if data_list else None
else:
return "Unknown operation"
'''
# Create the dynamic tool
create_result = client.execute_tool("create_and_run_tool", {
"name": "data_processor",
"code": tool_code,
"language": "python",
"arguments": {
"data_list": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"operation": "average"
}
})
print(f"Dynamic tool result: {create_result}")
create_custom_tool_example()
🔗 Integration Patterns
Webhook Integration
Webhook Handler Example
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
nexus_client = NexusClient("http://localhost:9999")
@app.route('/webhook/process', methods=['POST'])
def process_webhook():
"""Process incoming webhook data with Nexus tools"""
data = request.json
try:
# Use Nexus to process the webhook data
if data.get('type') == 'text_analysis':
result = nexus_client.execute_tool("analyze_text", {
"text": data.get('content', '')
})
elif data.get('type') == 'calculation':
result = nexus_client.execute_tool("calculate", {
"expression": data.get('expression', '')
})
else:
return jsonify({"error": "Unknown webhook type"}), 400
return jsonify({
"status": "success",
"result": result
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e)
}), 500
if __name__ == '__main__':
app.run(port=5000)
⚡ Performance Tips
🚀 Optimization Strategies
- Connection Pooling: Reuse HTTP connections with session objects
- Async Operations: Use async/await for concurrent tool execution
- Caching: Cache tool metadata and frequently used results
- Batch Requests: Group multiple operations when possible
- Timeout Handling: Set appropriate timeouts for long-running tools