# Barndoor SDK Examples

This directory contains working examples that demonstrate how to use the Barndoor TypeScript SDK with MCP servers.

## Key Patterns

Both examples follow the same proven pattern:

```javascript
// 1. Authenticate
const sdk = await loginInteractive();

// 2. Ensure server is connected
await ensureServerConnected(sdk, SERVER_SLUG);

// 3. Create MCP client
const mcpClient = await makeMcpClient(sdk, SERVER_SLUG);

// 4. Use MCP client
const { tools } = await mcpClient.listTools();
const result = await mcpClient.callTool({ name: 'tool_name', arguments: {} });

// 5. Cleanup
await mcpClient.close();
await sdk.close();
```

## Configuration

Both examples use the same authentication pattern:

1. **Environment Variables** (create a `.env` file):
    
   ```
   AUTH_DOMAIN=your-auth-domain
   AGENT_CLIENT_ID=your-client-id
   AGENT_CLIENT_SECRET=your-client-secret
   MODE=development  # or production
   ```

2. **Server Configuration**: Change the `SERVER_SLUG` constant in each file to target different MCP servers:   
   - `'salesforce'` - Salesforce integration
   - `'notion'` - Notion integration
   - Or any other configured MCP server

## Working Examples

### 1. `basic-mcp-client.js` - Direct MCP Client

Basic example showing direct MCP server interaction without AI frameworks. **What it does:**
- Authenticates with Barndoor
- Connects to an MCP server
- Lists available tools and resources
- Executes basic operations

**Requirements:**

```
npm install dotenv
```

**Run:**

```
node examples/basic-mcp-client.js
```

```javascript
/**
 * 🔗 Universal Barndoor MCP Client
 *
 * Lets the user pick any available MCP server, list its tools,
 * and run a custom prompt / command interactively — no hardcoded Salesforce or Notion.
 */

import 'dotenv/config';
import readline from 'readline/promises';
import {
  loginInteractive,
  ensureServerConnected,
  makeMcpClient,
  BarndoorSDK,
  getDynamicConfig,
  getStaticConfig,
  hasOrganizationInfo,
} from '../dist/index.esm.js';

// simple input helper
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
async function ask(q) {
  return (await rl.question(q)).trim();
}

async function main() {
  try {
    console.log('\n🚀 Starting Universal MCP Client Example...\n');

// ---------------------------------------------------------------------
    // 1. Authenticate to Barndoor
    // ---------------------------------------------------------------------
    console.log('🔐 Authenticating with Barndoor...');
    let sdk;
    const envToken = process.env.BARNDOOR_ACCESS_TOKEN;

if (envToken) {
      console.log('🔑 Using token from BARNDOOR_ACCESS_TOKEN');
      const cfg = hasOrganizationInfo(envToken)
        ? getDynamicConfig(envToken)
        : getStaticConfig();
      sdk = new BarndoorSDK(cfg.apiBaseUrl, { token: envToken });
      await sdk.listServers();
      console.log('✅ Authentication successful (env token)!');
    } else {
      sdk = await loginInteractive();
      await sdk.listServers();
      console.log('✅ Authentication successful!');
    }

// ---------------------------------------------------------------------
    // 2. List all available servers
    // ---------------------------------------------------------------------
    const servers = await sdk.listServers();
    if (!servers.length) throw new Error('No MCP servers found for this user.');
    console.log('\n📡 Available MCP servers:');
    servers.forEach((s, i) => console.log(`  ${i + 1}. ${s.slug} (${s.connection_status})`));

// Ask user which one to use
    let idx = await ask('\n👉 Enter the number of the server you want to use: ');
    const choice = servers[parseInt(idx) - 1];
    if (!choice) throw new Error('Invalid selection.');
    const SERVER_SLUG = choice.slug;
    console.log(`\n🔗 Selected: ${SERVER_SLUG}\n`);

// ---------------------------------------------------------------------
    // 3. Ensure it’s connected
    // ---------------------------------------------------------------------
    await ensureServerConnected(sdk, SERVER_SLUG);
    console.log(`✅ ${SERVER_SLUG} connected.`);

// ---------------------------------------------------------------------
    // 4. Build MCP client and show available tools
    // ---------------------------------------------------------------------
    const mcpClient = await makeMcpClient(sdk, SERVER_SLUG);
    console.log('\n🔧 Fetching available tools...');
    const { tools = [] } = await mcpClient.listTools();
    if (!tools.length) console.log('⚠️  No tools found for this server.');
    else tools.forEach((t, i) => console.log(`  ${i + 1}. ${t.name} — ${t.description || 'No description'}`));

// ---------------------------------------------------------------------
    // 5. Ask user for a custom prompt
    // ---------------------------------------------------------------------
    const prompt = await ask('\n💬 What do you want to ask or do? (describe task): ');
    console.log(`\n🧠 Interpreting prompt: \
