---
title: "BuildStability Agent Integration Guide"
version: "2.0.0"
created-date: "2025-01-18"
updated-date: "2025-01-18"
doc-id: "buildstability-agents-guide"
author: "BuildStability Team"
tags: ["mcp", "api", "ai-agents", "openapi", "integration", "fitness-software"]
purpose: "Complete technical guide for AI agents and developers integrating with BuildStability via MCP, OpenAPI, and direct database access"
target-audience: ["AI Agents", "LLMs", "Developers", "Automated Systems"]
---

# BuildStability Agent Integration Guide

> **Built for the AI Agent Era** — Unlike competitors who lock data in proprietary black boxes, BuildStability provides structured data access via MCP, OpenAPI, and standard PostgreSQL.

---

## Quick Start

**For AI Agents (Claude, ChatGPT, Gemini, etc.):**
1. Enable API access in Business Settings → API & Integrations
2. Authenticate with Supabase JWT token
3. Use MCP endpoint: `POST https://api.buildstability.com/api/mcp`
4. See [MCP Server](#mcp-server-model-context-protocol) section below

**For Developers:**
1. Download [OpenAPI Specification](/buildstability-openapi.json)
2. Read [Authentication Guide](/auth-guide.md)
3. Review [Code Examples](/code-examples.md)
4. Sign up at [Developer Portal](/developers/signup)

---

## Architecture Overview

BuildStability is built on modern, agent-friendly infrastructure:

| Component | Technology | Agent Access |
|-----------|-----------|--------------|
| **Database** | PostgreSQL 15+ (Supabase) | ✅ PostgREST REST API (JWT auth, RLS enforced) |
| **Authentication** | Supabase Auth (JWT) | ✅ Standard Bearer tokens |
| **API Layer** | MCP Server + PostgREST API | ✅ JSON-RPC 2.0 + REST (JWT auth, RLS enforced) |
| **Frontend** | React/Vite SPA | ℹ️ Human interface only |
| **Edge Functions** | Supabase Edge Functions | ✅ HTTP endpoints |

**Key Advantage:** All data is stored in standard PostgreSQL. No proprietary formats, no black boxes.

---

## MCP Server (Model Context Protocol)

### Overview

BuildStability exposes a native MCP endpoint for AI assistants (Claude, ChatGPT, Gemini, etc.) to interact directly with business data using JSON-RPC 2.0.

### Endpoint

```
POST https://api.buildstability.com/api/mcp
```

### Authentication

```http
Authorization: Bearer <supabase_jwt_token>
Content-Type: application/json
X-Business-ID: <business_uuid>  (optional - for multi-business users)
```

### Security Requirements

> ⚠️ **IMPORTANT:** API/MCP access must be explicitly enabled for each business.

1. **API Access Must Be Enabled:** Businesses must enable API access in their settings before MCP endpoints will work. This is a security measure to ensure only businesses that want API access have it.

2. **Business Isolation:** All data is scoped to the authenticated user's business. You can only access data for businesses where you are an active member AND where API access is enabled.

3. **Multi-Business Users:** If you belong to multiple businesses, use the `X-Business-ID` header to specify which business to access. Without this header, the system uses your first API-enabled business.

### Enabling API Access

Business administrators can enable API access:
1. Go to **Business Settings**
2. Navigate to **API & Integrations**
3. Toggle **Enable API Access**
4. Save changes

Once enabled, MCP endpoints will work for all members of that business.

### Protocol

**JSON-RPC 2.0** over HTTP

### Available Tools

#### Core Tools
| Tool Name | Description | Parameters |
|-----------|-------------|------------|
| `tools/list` | List all available tools | None |
| `buildstability/get_client_summary` | Get client details with engagement score | `client_id` (required) |
| `buildstability/list_active_programs` | List active workout programs | `limit` (optional, default: 10) |
| `buildstability/check_churn_risk` | Get clients at risk of churning | `threshold` (optional, default: 40) |
| `buildstability/get_business_stats` | Get high-level business metrics | None |

#### Schedule & Clients
| Tool Name | Description | Parameters |
|-----------|-------------|------------|
| `buildstability/get_schedule` | Get appointments and classes | `date` ("today", "week", or YYYY-MM-DD), `trainer_id`, `include_classes` |
| `buildstability/list_clients` | List all clients with engagement data | `status`, `search`, `limit` |
| `buildstability/get_available_slots` | Get available booking slots | `date`, `trainer_id`, `duration_minutes` |

#### Revenue & Analytics
| Tool Name | Description | Parameters |
|-----------|-------------|------------|
| `buildstability/get_revenue_summary` | Get revenue for a period | `period` ("today", "week", "month", "year", "custom"), `start_date`, `end_date` |
| `buildstability/get_attendance_stats` | Get attendance and no-show rates | `period`, `client_id` |
| `buildstability/get_popular_times` | Get booking time analytics | `period` |

#### Client Details
| Tool Name | Description | Parameters |
|-----------|-------------|------------|
| `buildstability/get_client_workout_history` | Get workout sessions and exercises | `client_id` (required), `limit`, `include_exercises` |
| `buildstability/get_client_notes` | Get notes and documents | `client_id` (required), `document_type`, `limit` |

#### Actions
| Tool Name | Description | Parameters |
|-----------|-------------|------------|
| `buildstability/send_client_message` | Send email to client | `client_id` (required), `message` (required), `subject`, `message_type` |
| `buildstability/create_client_note` | Add note to client profile | `client_id` (required), `content` (required), `title`, `document_type` |

### Example Request

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "buildstability/check_churn_risk",
  "params": {
    "threshold": 40
  }
}
```

### Example Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "threshold": 40,
    "at_risk_count": 3,
    "clients": [
      {
        "client_id": "uuid-here",
        "name": "John Smith",
        "email": "john@example.com",
        "engagement_score": 28,
        "last_workout": "2025-01-10",
        "recommendation": "Immediate outreach required - high churn risk"
      }
    ]
  }
}
```

---

## OpenAPI Specification

A full **OpenAPI 3.1** specification is available for GPT Actions and API clients:

```
https://buildstability.com/buildstability-openapi.json
```

**Use Cases:**
- Import into OpenAI GPT Actions
- Generate client SDKs (TypeScript, Python, etc.)
- API documentation tools (Swagger UI, Postman)
- API testing and validation

---

## Authentication

Agents acting on behalf of a user must obtain a valid JWT from Supabase Auth.

### Method

**Bearer Token** in `Authorization` header

### Getting Your Token

**Method 1: Browser Console (Quick Test)**
1. Log in to BuildStability
2. Open DevTools (F12) → Application → Local Storage
3. Find `sb-<project-id>-auth-token`
4. Copy the `access_token` value

**Method 2: Supabase Client (Recommended)**
```typescript
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_ANON_KEY!
);

const { data: { session } } = await supabase.auth.getSession();
const accessToken = session?.access_token;
```

### Token Expiration

- **Access tokens:** 1 hour
- **Refresh tokens:** 30 days
- Supabase client automatically refreshes tokens

### Security Best Practices

- ✅ Never commit tokens to version control
- ✅ Use environment variables
- ✅ Store tokens securely (Keychain/Keystore on mobile)
- ✅ Always use HTTPS
- ✅ Rotate tokens if compromised

---

## Data Schema (Core Entities)

### Client

Represents a fitness client managed by a trainer.

```typescript
interface Client {
  id: string;              // UUID
  first_name: string;
  last_name: string;
  email: string;
  status: 'active' | 'archived' | 'lead';
  join_date: string;       // ISO 8601
  managing_trainer_id: string; // UUID of the trainer
  business_id: string;     // UUID of the business
}
```

### Program Template

A reusable workout structure.

```typescript
interface ProgramTemplate {
  id: string;              // UUID
  name: string;            // e.g., "Hypertrophy Phase 1"
  goal: string;            // e.g., "Muscle Gain"
  weeks: WorkoutWeek[];    // JSON structure of weeks/days/exercises
  trainer_id: string;      // UUID
  business_id: string;     // UUID
}
```

### Assigned Program

An active instance of a program assigned to a client.

```typescript
interface AssignedProgram {
  id: string;              // UUID
  client_id: string;       // UUID
  program_template_id: string; // UUID
  start_date: string;      // YYYY-MM-DD
  status: 'Active' | 'Completed' | 'Paused';
  current_week: number;
}
```

### Engagement Score

Client retention prediction metric.

```typescript
interface EngagementScore {
  client_id: string;       // UUID
  score: number;           // 0-100
  risk_level: 'low' | 'moderate' | 'high';
  last_workout: string;    // ISO 8601 date
  workouts_this_week: number;
}
```

---

## AI Capabilities

BuildStability exposes several AI-powered features that agents can leverage:

### 1. AI Workout Generator

**Endpoint:** `POST /functions/v1/ai-plan-generator`

**Purpose:** Generates personalised, periodised workout programs in 60 seconds. Supports 10 goal types including sport-specific programming.

**Supported Goals:**
- Build Muscle, Increase Strength, Lean & Toned, Improve Endurance, Athletic Performance
- **HYROX / Functional Race**: All 8 stations, 3 race variants (Singles/Doubles/Relay), weak station emphasis, race simulation days, target time calibration
- **Sprint Performance**: Acceleration drills, max velocity, speed endurance, plyometrics, distance-based rest (4-6 min for 60m max effort)
- **Running / Endurance**: 5K to ultra, 80/20 polarised model, VO2 max zones, tempo/interval/long run
- **Hybrid Athlete**: Balanced running + strength, never peaks both in same week
- **Sport-Specific**: Any sport with phase and athlete level context

**Input:**
```json
{
  "goal": "Strength",
  "daysPerWeek": 4,
  "equipment": ["Barbell", "Dumbbells"],
  "experienceLevel": "Intermediate",
  "injuries": ["Lower Back"]
}
```

### 2. Client Engagement Score (Churn Prediction)

**MCP Tool:** `buildstability/check_churn_risk`

**Direct Endpoint:** `GET /rest/v1/client_engagement_scores?client_id=eq.{id}`

**Purpose:** Returns a 0-100 score indicating retention probability.

**Interpretation:**
- `< 40`: High Risk (Immediate intervention needed)
- `40-70`: Moderate Risk
- `> 70`: Low Risk (Healthy)

---

## Integration Best Practices for Agents

### 1. Use MCP for Tool Calls

The MCP endpoint (`/api/mcp`) is the recommended way for AI assistants (Claude, ChatGPT, Gemini, etc.) to interact with BuildStability. It provides:
- Structured tool definitions
- Consistent error handling
- Business context isolation
- Type-safe responses

### 2. Prefer `select` with Filters

When querying data directly, always filter by `business_id` or `trainer_id` to respect multi-tenancy:

```sql
SELECT * FROM clients 
WHERE business_id = '<business-uuid>' 
AND status = 'active';
```

### 3. Use Semantic Search

For exercise lookups, use the `match_exercises` RPC function which performs vector similarity search:

```sql
SELECT * FROM rpc.match_exercises(
  query_embedding := <embedding_vector>,
  match_threshold := 0.7
);
```

### 4. Structured Output

When generating workout plans, ensure strict adherence to the `WorkoutWeek` / `WorkoutDay` JSON structure to ensure frontend rendering compatibility.

### 5. Rate Limits

BuildStability enforces rate limits to ensure fair usage and cost protection:

**Rate Limits (per 15-minute window):**

| Plan | Rate Limit | Daily Cap | Max Clients/Query |
|------|------------|-----------|-------------------|
| **Free Trial** | 25 req/15min | 500/day | 5 |
| **Essential** | 50 req/15min | 1,000/day | 10 |
| **Starter** | 100 req/15min | 5,000/day | 25 |
| **Pro** | 200 req/15min | 15,000/day | 50 |
| **Studio** | 500 req/15min | 50,000/day | 100 |

**Response Headers:**
- `X-RateLimit-Limit` - Your rate limit
- `X-RateLimit-Remaining` - Requests remaining in window
- `X-DailyLimit-Limit` - Your daily cap
- `X-DailyLimit-Remaining` - Requests remaining today
- `X-DailyLimit-Reset` - When daily cap resets (midnight UTC)

### 6. Error Handling

Always handle these error scenarios:
- `401 Unauthorized` - Token expired or invalid
- `403 Forbidden` - API access not enabled or insufficient permissions
- `429 Too Many Requests` - Rate limit exceeded (implement exponential backoff)
- `500 Internal Server Error` - Retry with exponential backoff

---

## Why BuildStability is Agent-Friendly

Unlike competitors who lock your data in proprietary black boxes:

| Feature | BuildStability | Competitors |
|---------|---------------|-------------|
| **Database** | ✅ PostgreSQL (standard SQL) | ❌ Proprietary formats |
| **API Access** | ✅ MCP + OpenAPI + REST | ❌ Limited or none |
| **Data Export** | ✅ Full SQL export | ❌ Locked in |
| **Integration** | ✅ Native MCP support | ❌ Manual scraping |
| **Documentation** | ✅ Comprehensive guides | ❌ Minimal or outdated |

**Key Advantages:**
- **PostgreSQL:** Standard SQL database that any tool can query
- **MCP Native:** Direct integration with Claude, ChatGPT, Gemini, and other AI assistants
- **OpenAPI Spec:** Import into GPT Actions or any API client
- **Structured Data:** Clean, typed schemas for reliable parsing
- **No Lock-in:** Export your data anytime in standard formats

---

## Related Resources

| Resource | Description | URL |
|----------|-------------|-----|
| **OpenAPI Spec** | Full API specification | `/buildstability-openapi.json` |
| **LLM Context** | Quick reference for LLMs | `/llms.txt` |
| **Developer Portal** | Main developer hub | `/developers` |
| **Developer Sign Up** | Register for developer access | `/developers/signup` |
| **Quick Start** | 5-minute setup guide | `/quickstart-mcp.md` |
| **Code Examples** | Ready-to-use code | `/code-examples.md` |
| **Auth Guide** | Detailed authentication guide | `/auth-guide.md` |

---

## Version History

- **v2.0.0** (2025-01-18): Added security requirements, API access opt-in documentation
- **v1.0.0** (2024-12-01): Initial release

---

## Support

For technical questions or integration support:
- **Documentation:** [https://buildstability.com/developers](/developers)
- **Email:** developers@buildstability.com
- **GitHub Issues:** (if applicable)

---

*Last updated: 2025-01-18*