Code Examples

Practical examples for integrating with the Fenceline MCP Server in various programming languages.

JavaScript/Node.js

Basic Tool Call

const response = await fetch('https://mcp.fenceline.ai/mcp/rpc', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'tools/call',
    params: {
      name: 'rag.search',
      arguments: {
        query: 'fence materials',
        topK: 5
      }
    }
  })
});

const data = await response.json();
console.log(data.result);

List Available Tools

async function listTools(apiKey) {
  const response = await fetch('https://mcp.fenceline.ai/mcp/rpc', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': apiKey
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'tools/list',
      params: {}
    })
  });
  
  const data = await response.json();
  return data.result.tools;
}

Python

Using requests library

import requests
import json

def call_mcp_tool(api_key, tool_name, arguments):
    url = 'https://mcp.fenceline.ai/mcp/rpc'
    headers = {
        'Content-Type': 'application/json',
        'X-API-Key': api_key
    }
    payload = {
        'jsonrpc': '2.0',
        'id': 1,
        'method': 'tools/call',
        'params': {
            'name': tool_name,
            'arguments': arguments
        }
    }
    
    response = requests.post(url, headers=headers, json=payload)
    return response.json()

# Example usage
result = call_mcp_tool(
    'YOUR_API_KEY',
    'materials.search',
    {'query': 'vinyl fence panels', 'filters': {'maxPrice': 100}}
)
print(result['result'])

cURL

Search Business Data

curl -X POST https://mcp.fenceline.ai/mcp/rpc \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "rag.search",
      "arguments": {
        "query": "fence installation projects",
        "topK": 10
      }
    }
  }'

Analyze Permit Requirements

curl -X POST https://mcp.fenceline.ai/mcp/rpc \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "permits.analyze_requirements",
      "arguments": {
        "address": "123 Main St, Austin, TX",
        "fenceType": "wood",
        "height": 6
      }
    }
  }'

Error Handling Examples

JavaScript with Error Handling

async function callMcpTool(toolName, args) {
  try {
    const response = await fetch('https://mcp.fenceline.ai/mcp/rpc', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.MCP_API_KEY
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: Date.now(),
        method: 'tools/call',
        params: { name: toolName, arguments: args }
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    
    if (data.error) {
      throw new Error(`MCP Error: ${data.error.message}`);
    }

    return data.result;
  } catch (error) {
    console.error('MCP Tool Call Failed:', error);
    throw error;
  }
}

Integration Patterns

Batch Tool Calls

async function batchToolCalls(apiKey, calls) {
  const promises = calls.map((call, index) => 
    fetch('https://mcp.fenceline.ai/mcp/rpc', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': apiKey
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: index,
        method: 'tools/call',
        params: call
      })
    }).then(r => r.json())
  );
  
  return Promise.all(promises);
}

Retry Logic

async function callWithRetry(toolName, args, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await callMcpTool(toolName, args);
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // Exponential backoff
      await new Promise(resolve => 
        setTimeout(resolve, Math.pow(2, i) * 1000)
      );
    }
  }
}

Testing Examples

Jest Test

describe('MCP Server Integration', () => {
  test('should list available tools', async () => {
    const tools = await listTools(process.env.MCP_API_KEY);
    
    expect(tools).toBeInstanceOf(Array);
    expect(tools.length).toBeGreaterThan(0);
    expect(tools[0]).toHaveProperty('name');
    expect(tools[0]).toHaveProperty('description');
  });

  test('should search materials successfully', async () => {
    const result = await callMcpTool('materials.search', {
      query: 'fence posts',
      filters: { limit: 5 }
    });
    
    expect(result.content[0].text).toContain('materials');
  });
});

Next Steps