> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sammylabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Server Integration

> Integrate Smithery-hosted MCP servers with the Sammy Three package for enhanced AI capabilities

<Note>
  Smithery is a platform that hosts MCP (Model Context Protocol) servers as remote endpoints. This guide covers integrating these servers with the Sammy Three package.
</Note>

## Quick Start

### Basic Smithery Configuration

<CodeGroup>
  ```typescript Basic Setup theme={null}
  const config: SammyAgentConfig = {
    mcp: {
      enabled: true,
      debug: true,
      servers: [
        {
          name: 'hubspot',
          type: 'streamableHttp',
          streamableHttp: {
            url: 'https://server.smithery.ai/@BlackSand-Software/hubspot-mcp/mcp?api_key=YOUR_API_KEY&profile=YOUR_PROFILE'
          },
          autoConnect: true
        }
      ]
    }
  };
  ```

  ```typescript Using Smithery SDK theme={null}
  import { createSmitheryUrl } from "@smithery/sdk";

  const smitheryApiKey = process.env.SMITHERY_API_KEY;
  const smitheryProfile = process.env.SMITHERY_PROFILE;

  const serverUrl = createSmitheryUrl(
    "https://server.smithery.ai/@BlackSand-Software/hubspot-mcp", 
    { 
      apiKey: smitheryApiKey, 
      profile: smitheryProfile 
    }
  );

  // Then use serverUrl.toString() in your config
  ```
</CodeGroup>

## Common Issues and Solutions

### Content Security Policy (CSP) Errors

<Warning>
  If you see: `Refused to connect to 'https://server.smithery.ai/...' because it violates the following Content Security Policy directive`
</Warning>

<Steps>
  <Step title="Update next.config.js">
    Add `https://server.smithery.ai` to your CSP `connect-src` directive:

    ```javascript theme={null}
    const connectSources = [
      // ... other sources
      'https://server.smithery.ai',
      'blob:'  // Also needed for MCP
    ];
    ```
  </Step>

  <Step title="Restart Server">
    After updating `next.config.js`, you must restart your Next.js development server for the changes to take effect.
  </Step>
</Steps>

### Authentication Issues

<Card title="401 or 403 Errors" icon="lock">
  **Solutions:**

  * Verify your API key is correct and active
  * Check that your profile has access to the requested MCP server
  * Ensure the API key and profile are properly URL-encoded in the connection string
</Card>

### Connection Timeout

<Card title="Timeout Issues" icon="clock">
  **Solutions:**

  ```typescript theme={null}
  mcp: {
    timeout: 60000, // 60 seconds
    // ...
  }
  ```

  * Check if Smithery service is operational
  * Verify network connectivity
</Card>

### Tool Discovery Failures

<Info>
  If connection succeeds but no tools are discovered:
</Info>

<Steps>
  <Step title="Check Documentation">
    Review the MCP server documentation for available tools
  </Step>

  <Step title="Verify Path">
    Ensure the server path is correct (should end with `/mcp`)
  </Step>

  <Step title="Enable Debug Logging">
    ```typescript theme={null}
    mcp: {
      debug: true,
      // ...
    }
    ```
  </Step>
</Steps>

## Security Considerations

### API Key Management

<Warning>
  **Never hardcode API keys in your source code!** Use environment variables instead.
</Warning>

<CodeGroup>
  ```bash .env.local theme={null}
  SMITHERY_API_KEY=your-api-key-here
  SMITHERY_PROFILE=your-profile-here
  ```

  ```typescript Configuration theme={null}
  streamableHttp: {
    url: `https://server.smithery.ai/@org/server/mcp?api_key=${process.env.SMITHERY_API_KEY}&profile=${process.env.SMITHERY_PROFILE}`
  }
  ```
</CodeGroup>

### Client-Side Security

<Note>
  Since MCP connections are made from the browser, your API keys will be exposed in network requests. Consider these security measures:
</Note>

<Columns cols={2}>
  <Card title="Server-Side Proxy" icon="server">
    Route MCP requests through your backend
  </Card>

  <Card title="Token Rotation" icon="refresh">
    Use short-lived tokens
  </Card>

  <Card title="Restrict Permissions" icon="shield">
    Limit what the API key can access
  </Card>

  <Card title="Monitor Usage" icon="chart-line">
    Track API key usage for anomalies
  </Card>
</Columns>

### CORS Considerations

Smithery servers should handle CORS appropriately, but if you encounter CORS issues:

1. Verify the server supports browser-based connections
2. Check if additional headers are needed in the configuration
3. Consider using a proxy server for the connection

## Debugging Guide

<Steps>
  <Step title="Enable Debug Logging">
    ```typescript theme={null}
    mcp: { debug: true }
    ```
  </Step>

  <Step title="Check Browser Console">
    Look for:

    * CSP violations
    * Network errors
    * CORS issues
  </Step>

  <Step title="Verify Network Tab">
    Check that:

    * Request is being sent to correct URL
    * API key and profile are in query params
    * Response status and body
  </Step>

  <Step title="Test Connection Directly">
    ```bash theme={null}
    curl "https://server.smithery.ai/@org/server/mcp?api_key=KEY&profile=PROFILE"
    ```
  </Step>
</Steps>

## Complete HubSpot Integration Example

<Tabs>
  <Tab title="Configuration">
    ```typescript theme={null}
    export const createSammyProviderConfig = ({
      jwtToken,
      onTokenExpired,
      captureMethod,
    }: SammyProviderConfigParams): SammyAgentConfig => {
      return {
        // ... other config
        mcp: {
          enabled: true,
          debug: process.env.NODE_ENV === 'development',
          timeout: 45000, // HubSpot API calls might take longer
          autoReconnect: true,
          reconnectDelay: 5000,
          maxReconnectAttempts: 3,
          
          servers: [
            {
              name: 'hubspot',
              type: 'streamableHttp',
              description: 'HubSpot CRM integration via Smithery',
              autoConnect: true,
              streamableHttp: {
                url: `https://server.smithery.ai/@BlackSand-Software/hubspot-mcp/mcp?api_key=${process.env.NEXT_PUBLIC_SMITHERY_API_KEY}&profile=${process.env.NEXT_PUBLIC_SMITHERY_PROFILE}`,
                headers: {
                  // Add any additional headers if required
                  'User-Agent': 'Sammy-Agent/1.0'
                }
              }
            }
          ]
        }
      };
    };
    ```
  </Tab>

  <Tab title="Event Monitoring">
    ```typescript theme={null}
    mcp: {
      onEvent: (event) => {
        if (event.type === 'mcp:server:connected') {
          console.log(`Connected to Smithery server: ${event.serverName}`);
        }
        if (event.type === 'mcp:tool:discovered') {
          console.log(`Discovered tool: ${event.toolName}`);
        }
        if (event.type === 'mcp:server:error') {
          console.error(`Smithery connection error:`, event.error);
          // Send to error tracking service
        }
      }
    }
    ```
  </Tab>
</Tabs>

## MCP Configuration Reference

### Server Configuration

```typescript theme={null}
interface MCPServerConfig {
  name: string;                  // Server identifier
  type: 'streamableHttp';        // Connection type
  description?: string;          // Server description
  autoConnect?: boolean;         // Auto-connect on startup
  streamableHttp: {
    url: string;                 // Server endpoint URL
    headers?: Record<string, string>; // Additional headers
  };
}
```

### Global MCP Settings

```typescript theme={null}
interface MCPConfig {
  enabled: boolean;              // Enable/disable MCP
  debug?: boolean;               // Debug logging
  timeout?: number;              // Connection timeout (ms)
  autoReconnect?: boolean;       // Auto-reconnect on failure
  reconnectDelay?: number;       // Delay between reconnects (ms)
  maxReconnectAttempts?: number; // Max reconnection attempts
  servers: MCPServerConfig[];    // Server configurations
  onEvent?: (event: MCPEvent) => void; // Event handler
}
```

## Resources

<Columns cols={3}>
  <Card title="Smithery Docs" icon="book" href="https://smithery.ai/docs">
    Official Smithery documentation
  </Card>

  <Card title="MCP Specification" icon="file-code" href="https://modelcontextprotocol.io">
    Model Context Protocol spec
  </Card>

  <Card title="Debug Guide" icon="bug" href="../../packages/sammy-three/docs/mcp/mcp-debugging-guide.md">
    Sammy Three MCP debugging
  </Card>
</Columns>
