# MCP Client Setup

Guide to integrating AIDP using the Model Context Protocol (MCP).

## What is MCP?

The Model Context Protocol (MCP) is an open standard for connecting AI assistants to external data sources and tools. AIDP provides native MCP support for seamless integration.

***

## Installation

### TypeScript/JavaScript

```bash
npm install @modelcontextprotocol/sdk @aidp/mcp-client
```

### Python

```bash
pip install mcp-sdk aidp-mcp-client
```

***

## Quick Start

### TypeScript

```typescript
import { MCPClient } from '@modelcontextprotocol/sdk';
import { AIDPMCPServer } from '@aidp/mcp-client';

// Initialize MCP client
const client = new MCPClient({
  serverUrl: 'https://mcp.aidp.dev',
  apiKey: process.env.AIDP_API_KEY,
});

// Connect to AIDP MCP server
await client.connect();

// Search for businesses
const results = await client.callTool('search_businesses', {
  query: 'coffee shops',
  location: { lat: 45.5231, lon: -122.6765 },
});

console.log(results);
```

### Python

```python
from mcp import MCPClient
from aidp_mcp import AIDPMCPServer

# Initialize MCP client
client = MCPClient(
    server_url='https://mcp.aidp.dev',
    api_key=os.environ['AIDP_API_KEY']
)

# Connect
await client.connect()

# Search for businesses
results = await client.call_tool('search_businesses', {
    'query': 'coffee shops',
    'location': {'lat': 45.5231, 'lon': -122.6765}
})

print(results)
```

***

## Available MCP Tools

### search\_businesses

Search for businesses using natural language.

**Parameters**:

```json
{
  "query": "string (required)",
  "location": {
    "lat": "number (required)",
    "lon": "number (required)",
    "distance": "string (optional, default: '10km')"
  },
  "category": "string (optional)",
  "limit": "number (optional, default: 10)"
}
```

**Returns**:

```json
{
  "businesses": [...],
  "total": 42,
  "response": "AI-generated response text"
}
```

***

### get\_business

Get detailed information about a specific business.

**Parameters**:

```json
{
  "businessId": "string (required)"
}
```

**Returns**:

```json
{
  "id": "biz_abc123",
  "name": "Artisan Coffee Roasters",
  "category": "restaurants",
  ...
}
```

***

### get\_business\_hours

Check if a business is currently open.

**Parameters**:

```json
{
  "businessId": "string (required)",
  "datetime": "string (optional, ISO 8601)"
}
```

**Returns**:

```json
{
  "isOpen": true,
  "currentHours": { "open": "07:00", "close": "18:00" },
  "nextChange": "2024-12-12T18:00:00Z"
}
```

***

### get\_business\_services

Get services offered by a business.

**Parameters**:

```json
{
  "businessId": "string (required)"
}
```

**Returns**:

```json
{
  "services": [
    {
      "name": "Espresso Drinks",
      "description": "...",
      "pricing": {...}
    }
  ]
}
```

***

## Configuration

### Server Configuration

```typescript
const client = new MCPClient({
  serverUrl: 'https://mcp.aidp.dev',
  apiKey: process.env.AIDP_API_KEY,
  timeout: 30000,
  retries: 3,
  headers: {
    'X-Platform': 'my-ai-platform',
  },
});
```

### Tool Discovery

List available tools:

```typescript
const tools = await client.listTools();

tools.forEach((tool) => {
  console.log(`Tool: ${tool.name}`);
  console.log(`Description: ${tool.description}`);
  console.log(`Parameters:`, tool.parameters);
});
```

***

## Advanced Usage

### Custom Tool Handlers

```typescript
client.onToolCall('search_businesses', async (params) => {
  // Pre-process parameters
  const enhancedParams = {
    ...params,
    sessionId: getCurrentSessionId(),
  };

  // Call tool
  const results = await client.callTool('search_businesses', enhancedParams);

  // Post-process results
  return formatResults(results);
});
```

### Error Handling

```typescript
try {
  const results = await client.callTool('search_businesses', params);
} catch (error) {
  if (error.code === 'TOOL_NOT_FOUND') {
    console.error('Tool not available');
  } else if (error.code === 'INVALID_PARAMETERS') {
    console.error('Invalid parameters:', error.details);
  } else {
    console.error('Tool call failed:', error.message);
  }
}
```

***

## Self-Hosting MCP Server

Run your own AIDP MCP server:

```bash
# Using Docker
docker run -p 3000:3000 \
  -e AIDP_API_KEY=your-api-key \
  aidp/mcp-server:latest

# Using npm
npm install -g @aidp/mcp-server
aidp-mcp-server --port 3000 --api-key your-api-key
```

**Configuration**:

```yaml
# config.yml
server:
  port: 3000
  host: 0.0.0.0

aidp:
  apiKey: ${AIDP_API_KEY}
  environment: production

tools:
  - search_businesses
  - get_business
  - get_business_hours
  - get_business_services
```

***

## Testing

### Test MCP Connection

```typescript
import { MCPClient } from '@modelcontextprotocol/sdk';

async function testConnection() {
  const client = new MCPClient({
    serverUrl: 'https://mcp.aidp.dev',
    apiKey: process.env.AIDP_TEST_API_KEY,
  });

  try {
    await client.connect();
    console.log('✅ Connected to AIDP MCP server');

    const tools = await client.listTools();
    console.log(`✅ Found ${tools.length} tools`);

    const results = await client.callTool('search_businesses', {
      query: 'test',
      location: { lat: 45.5231, lon: -122.6765 },
    });
    console.log('✅ Search test successful');
  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await client.disconnect();
  }
}

testConnection();
```

***

## Best Practices

### 1. Connection Pooling

Reuse MCP connections:

```typescript
class MCPConnectionPool {
  private connections: Map<string, MCPClient> = new Map();

  async getConnection(apiKey: string): Promise<MCPClient> {
    if (!this.connections.has(apiKey)) {
      const client = new MCPClient({
        serverUrl: 'https://mcp.aidp.dev',
        apiKey,
      });
      await client.connect();
      this.connections.set(apiKey, client);
    }
    return this.connections.get(apiKey)!;
  }
}
```

### 2. Graceful Shutdown

Clean up connections:

```typescript
process.on('SIGTERM', async () => {
  await client.disconnect();
  process.exit(0);
});
```

### 3. Monitoring

Monitor MCP health:

```typescript
setInterval(async () => {
  try {
    await client.ping();
  } catch (error) {
    console.error('MCP server unhealthy:', error);
    await client.reconnect();
  }
}, 30000);
```

***

## Support

* 📧 Email: <mcp@aidp.dev>
* 💬 GitHub Discussions: [github.com/aidp/platform/discussions](https://github.com/aidp/platform/discussions)
* 📚 MCP Spec: [modelcontextprotocol.io](https://modelcontextprotocol.io)

***

**Next**: [Discovery & Search →](https://amistan.gitbook.io/aidp-docs/for-ai-platform-developers/discovery)
