# AI Agent Integration (MCP)

Connect AI agents like Claude, ChatGPT, and custom applications to the GoSmarter API using the Model Context Protocol (MCP) server.

## What is MCP?

The Model Context Protocol (MCP) is a standardized way for AI agents to interact with APIs and resources. The GoSmarter MCP server provides:

- **API Tools** - All GoSmarter API operations available as callable tools
- **Documentation Resources** - Read-only access to product documentation
- **Standardized Protocol** - Works with any MCP-compatible AI agent
- **Same Authentication** - Uses your existing OAuth 2.0 credentials

## Quick Start with Claude Desktop

The easiest way to get started is with Claude Desktop:

### 1. Install Claude Desktop

Download from [claude.ai/download](https://claude.ai/download)

### 2. Get Your Credentials

You'll need:

- OAuth 2.0 client ID and secret
- API gateway URL

Contact your administrator if you don't have these.

### 3. Get an Access Token

```bash
curl --request POST \
  --url 'https://YOUR_TENANT.ciamlogin.com/YOUR_TENANT/oauth2/v2.0/token' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data grant_type=client_credentials \
  --data client_id=YOUR_CLIENT_ID \
  --data client_secret=YOUR_CLIENT_SECRET \
  --data scope=api://YOUR_API_ID/access_as_user
```

Save the `access_token` from the response.

### 4. Configure Claude Desktop

Edit the Claude Desktop config file:

**Mac**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "gosmarter": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-fetch",
        "https://YOUR_GATEWAY_URL.zuplo.app/mcp"
      ],
      "env": {
        "AUTHORIZATION": "Bearer YOUR_ACCESS_TOKEN"
      }
    }
  }
}
```

### 5. Restart Claude Desktop

Claude will now have access to all GoSmarter API operations and documentation.

## What Can AI Agents Do?

Once connected, AI agents can:

### Call API Operations

```
You: "Check the sync status for user ID abc-123"

Claude: I'll check that for you using the CheckUserSync tool.
[Calls CheckUserSync API with userId: "abc-123"]

The user sync status shows...
```

### Access Documentation

```
You: "How do I calculate scrap percentages?"

Claude: Let me check the documentation.
[Reads mcp://resources/docs/scrap-calculator/index]

According to the documentation, you can calculate scrap...
```

### Perform Complex Workflows

```
You: "Create an order for customer XYZ with 100 units of steel bar"

Claude: I'll help you create that order.
[Calls CreateOrder with appropriate parameters]

Order created successfully! Order ID: ORD-456...
```

## Available Tools

The MCP server exposes **all backend API operations** as tools:

### User Management

- `CheckUserSync` - Verify user synchronization status
- `UpdateUser` - Update user profile information

### Inventory

- `GetInventory` - Retrieve inventory levels
- `UpdateInventory` - Modify inventory quantities

### Orders

- `CreateOrder` - Create new customer orders
- `UpdateOrder` - Modify existing orders
- `GetOrderStatus` - Check order status

### Scrap Calculation

- `CalculateScrap` - Calculate cutting scrap
- `OptimizePattern` - Find optimal cutting patterns

### Mill Certificates

- `UploadCertificate` - Upload mill certificate
- `GetCertificate` - Retrieve certificate data

[See full list in the [API Reference](/api)]

## Available Documentation Resources

AI agents can read **multiple documentation resources** including:

- Dashboard usage guide
- FAQ and troubleshooting
- Getting started tutorials
- Glossary of terms
- Inventory management
- Mill certificates handling
- Optimization features
- Order management
- Quick reference guides
- Scrap calculator instructions
- General troubleshooting

## Using MCP Programmatically

### Python Example

```python
import requests
import os

class GoSmarterMCP:
    def __init__(self, gateway_url, access_token):
        self.url = f"{gateway_url}/mcp"
        self.headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json',
            'Accept': 'application/json, text/event-stream'
        }

    def list_tools(self):
        """List all available API tools"""
        response = requests.post(self.url, json={
            'jsonrpc': '2.0',
            'id': '1',
            'method': 'tools/list'
        }, headers=self.headers)

        return response.json()['result']['tools']

    def call_tool(self, tool_name, arguments):
        """Execute an API operation"""
        response = requests.post(self.url, json={
            'jsonrpc': '2.0',
            'id': '1',
            'method': 'tools/call',
            'params': {
                'name': tool_name,
                'arguments': arguments
            }
        }, headers=self.headers)

        return response.json()['result']

    def list_resources(self):
        """List all documentation resources"""
        response = requests.post(self.url, json={
            'jsonrpc': '2.0',
            'id': '1',
            'method': 'resources/list'
        }, headers=self.headers)

        return response.json()['result']['resources']

    def read_resource(self, uri):
        """Read a documentation resource"""
        response = requests.post(self.url, json={
            'jsonrpc': '2.0',
            'id': '1',
            'method': 'resources/read',
            'params': {'uri': uri}
        }, headers=self.headers)

        return response.json()['result']['contents'][0]['text']

# Usage
mcp = GoSmarterMCP(
    gateway_url='https://your-gateway.zuplo.app',
    access_token='your-access-token'
)

# List available tools
tools = mcp.list_tools()
print(f"Found {len(tools)} API operations")

# Call an API operation
result = mcp.call_tool('CheckUserSync', {
    'userId': 'abc-123'
})

# Read documentation
docs = mcp.read_resource('mcp://resources/docs/getting-started/index')
print(docs)
```

### JavaScript Example

```javascript
class GoSmarterMCP {
  constructor(gatewayUrl, accessToken) {
    this.url = `${gatewayUrl}/mcp`;
    this.headers = {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
      Accept: "application/json, text/event-stream",
    };
  }

  async listTools() {
    const response = await fetch(this.url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: "1",
        method: "tools/list",
      }),
    });

    const data = await response.json();
    return data.result.tools;
  }

  async callTool(toolName, args) {
    const response = await fetch(this.url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: "1",
        method: "tools/call",
        params: {
          name: toolName,
          arguments: args,
        },
      }),
    });

    const data = await response.json();
    return data.result;
  }

  async readResource(uri) {
    const response = await fetch(this.url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: "1",
        method: "resources/read",
        params: { uri },
      }),
    });

    const data = await response.json();
    return data.result.contents[0].text;
  }
}

// Usage
const mcp = new GoSmarterMCP(
  "https://your-gateway.zuplo.app",
  "your-access-token"
);

// List and call tools
const tools = await mcp.listTools();
const result = await mcp.callTool("CheckUserSync", { userId: "abc-123" });

// Read documentation
const docs = await mcp.readResource(
  "mcp://resources/docs/getting-started/index"
);
```

## MCP Protocol Reference

### Request Format

All MCP requests use JSON-RPC 2.0:

```json
{
  "jsonrpc": "2.0",
  "id": "unique-request-id",
  "method": "method-name",
  "params": {
    // Method-specific parameters
  }
}
```

### Response Format

```json
{
  "jsonrpc": "2.0",
  "id": "unique-request-id",
  "result": {
    // Method-specific result
  }
}
```

### Error Format

```json
{
  "jsonrpc": "2.0",
  "id": "unique-request-id",
  "error": {
    "code": -32601,
    "message": "Method not found"
  }
}
```

## Authentication with MCP

MCP requests use the same OAuth 2.0 authentication as regular API calls:

```bash
POST https://your-gateway.zuplo.app/mcp
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
Accept: application/json, text/event-stream
```

:::warning{title="Important"}

Always include the `Accept: application/json, text/event-stream` header. Some MCP servers require this header to process requests correctly.

:::

## Token Management for AI Agents

Since tokens expire after 1 hour:

1. **For Interactive Use** (Claude Desktop):
   - Generate a token before starting a session
   - Update the config file with the new token when it expires
   - Restart Claude Desktop after updating

2. **For Programmatic Use**:
   - Implement automatic token refresh (see [Authentication guide](/docs/authentication))
   - Cache tokens and refresh proactively
   - Handle 401 errors by refreshing and retrying

## Troubleshooting

### 406 Not Acceptable Error

**Cause**: Missing or incorrect `Accept` header

**Solution**: Always include:

```
Accept: application/json, text/event-stream
```

### 401 Unauthorized

**Cause**: Token expired or invalid

**Solution**:

1. Generate a new access token
2. Update your configuration
3. Restart the AI agent/application

### Tool Not Found

**Cause**: Tool name is incorrect

**Solution**:

1. List available tools using `tools/list`
2. Use the exact `name` field from the tool definition
3. Tool names are case-sensitive

### Resource Not Found

**Cause**: Resource URI is incorrect

**Solution**:

1. List available resources using `resources/list`
2. Use the exact `uri` field from the resource definition
3. URI format is `mcp://resources/docs/{path}`

## Best Practices

### For AI Agents

- **List tools first** - Let the agent discover available operations
- **Provide context** - Give the agent relevant documentation resources
- **Handle errors gracefully** - Implement retry logic for network issues
- **Cache tool lists** - Don't list tools on every request

### For Developers

- **Implement token refresh** - Automate token renewal
- **Log requests** - Track API usage and debug issues
- **Validate responses** - Check for errors before processing results
- **Rate limit** - Respect API rate limits (1000 req/hour)

## Next Steps

- [Authentication Guide](/docs/authentication) - Learn about OAuth 2.0 and token management
- [API Reference](/api) - Explore all available API operations
- [Quick Start](/docs/quickstart) - Test the API directly before using MCP

## Support

- Technical questions: support@gosmarter.ai
- Report MCP issues: [GitHub Issues](https://github.com/GoSmarter-ai/gosmarter-core-platform/issues)
- Check service status: [status.gosmarter.ai](https://status.gosmarter.ai)
