Skip to content
Dashboard

Claude / AI Integration

Use Brainpercent as a tool for Claude and other AI assistants via function calling and MCP.

Overview

Claude (and other AI models with tool use capabilities) can call Brainpercent's API as a tool to generate articles, create social media content, and manage content workflows. This guide covers defining tool schemas, example interactions, and the MCP (Model Context Protocol) approach.

Tool Definitions

Define Brainpercent API endpoints as tools for Claude's tool_use feature. Each tool maps to an API endpoint.

Tool Definitions for Claude
[
  {
    "name": "generate_article",
    "description": "Generate an SEO-optimized article on a given topic using the Brainpercent API. Returns an article ID that can be polled for status. Costs 40 credits.",
    "input_schema": {
      "type": "object",
      "properties": {
        "topic": {
          "type": "string",
          "description": "The article topic or title (3-500 characters)"
        },
        "keywords": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Target SEO keywords (max 20)"
        },
        "tone": {
          "type": "string",
          "enum": ["professional", "casual", "academic", "conversational"],
          "description": "Writing tone for the article"
        },
        "length": {
          "type": "string",
          "enum": ["short", "medium", "long"],
          "description": "Target article length"
        }
      },
      "required": ["topic"]
    }
  },
  {
    "name": "check_article_status",
    "description": "Check the generation progress of an article. Poll until status is 'draft', 'published', or 'failed'.",
    "input_schema": {
      "type": "object",
      "properties": {
        "article_id": {
          "type": "string",
          "description": "The article ID returned from generate_article"
        }
      },
      "required": ["article_id"]
    }
  },
  {
    "name": "generate_social_content",
    "description": "Generate social media posts from a source URL for one or more platforms. Costs 9 credits per platform.",
    "input_schema": {
      "type": "object",
      "properties": {
        "source_url": {
          "type": "string",
          "description": "URL of the source article"
        },
        "platforms": {
          "type": "array",
          "items": {
            "type": "string",
            "enum": ["twitter", "linkedin", "facebook", "instagram"]
          },
          "description": "Target social media platforms"
        },
        "tone": {
          "type": "string",
          "enum": ["professional", "casual", "humorous", "informative"],
          "description": "Writing tone"
        }
      },
      "required": ["source_url", "platforms"]
    }
  },
  {
    "name": "check_credits",
    "description": "Check the current credit balance and plan details.",
    "input_schema": {
      "type": "object",
      "properties": {},
      "required": []
    }
  },
  {
    "name": "list_articles",
    "description": "List existing articles with optional filters.",
    "input_schema": {
      "type": "object",
      "properties": {
        "status": {
          "type": "string",
          "enum": ["draft", "published", "scheduled", "generating", "failed"],
          "description": "Filter by article status"
        },
        "limit": {
          "type": "integer",
          "description": "Number of results (1-100)",
          "default": 20
        }
      }
    }
  }
]

Tool Execution Handler

Implement the tool execution layer that connects Claude's tool calls to the Brainpercent API.

Tool Execution
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();
const BP_API_KEY = 'bp_your_key';
const BP_BASE = 'https://brainpercent.app/api/v1';

async function callBrainpercent(method, path, body) {
  const options = {
    method,
    headers: {
      'Authorization': `Bearer ${BP_API_KEY}`,
      'Content-Type': 'application/json',
    },
  };
  if (body && method !== 'GET') options.body = JSON.stringify(body);
  const res = await fetch(`${BP_BASE}${path}`, options);
  return res.json();
}

async function executeTool(name, input) {
  switch (name) {
    case 'generate_article':
      return callBrainpercent('POST', '/articles/generate', input);
    case 'check_article_status':
      return callBrainpercent('GET', `/articles/${input.article_id}/status`);
    case 'generate_social_content':
      return callBrainpercent('POST', '/social/generate', input);
    case 'check_credits':
      return callBrainpercent('GET', '/user/credits');
    case 'list_articles':
      const params = new URLSearchParams();
      if (input.status) params.set('status', input.status);
      if (input.limit) params.set('limit', input.limit.toString());
      return callBrainpercent('GET', `/articles?${params}`);
    default:
      return { error: `Unknown tool: ${name}` };
  }
}

Full Conversation Loop

The complete agentic loop where Claude calls tools, processes results, and responds to the user.

Conversation Loop
const tools = [ /* tool definitions from above */ ];

async function chat(userMessage) {
  const messages = [{ role: 'user', content: userMessage }];

  while (true) {
    const response = await anthropic.messages.create({
      model: 'claude-sonnet-4-6',
      max_tokens: 4096,
      tools,
      messages,
    });

    // If no tool use, return the text response
    if (response.stop_reason === 'end_turn') {
      return response.content
        .filter(block => block.type === 'text')
        .map(block => block.text)
        .join('');
    }

    // Execute tool calls
    const toolResults = [];
    for (const block of response.content) {
      if (block.type === 'tool_use') {
        const result = await executeTool(block.name, block.input);
        toolResults.push({
          type: 'tool_result',
          tool_use_id: block.id,
          content: JSON.stringify(result),
        });
      }
    }

    // Add assistant response and tool results
    messages.push({ role: 'assistant', content: response.content });
    messages.push({ role: 'user', content: toolResults });
  }
}

// Example usage
const answer = await chat(
  'Check my credit balance and generate an article about AI trends in 2026 if I have enough credits.'
);
console.log(answer);

Example Interaction

Here is a sample conversation flow showing how Claude orchestrates multiple tool calls to fulfill a user request.

User Prompt

"Generate an article about sustainable packaging trends and create Twitter and LinkedIn posts from it."

Claude's Tool Calls

1

Calls check_credits

Verifies 850 credits available — enough for article generation (40) and social posts (18).

2

Calls generate_article with topic "Sustainable Packaging Trends"

Receives article_id and status "generating".

3

Calls check_article_status

Status: "generating", progress: 40%.

4

Calls check_article_status again

Status: "draft" — article generation is complete.

5

Calls generate_social_content with article URL and platforms ["twitter", "linkedin"]

Social posts generated for both platforms (18 credits).

6

Responds to the user

Provides a summary of the generated article and social media posts, total credits used: 58.

200Final tool result (social content)
{
  "success": true,
  "data": {
    "posts": [
      {
        "platform": "twitter",
        "content": "Sustainable packaging is reshaping the industry. From biodegradable materials to zero-waste designs, brands are innovating fast. Here are the top trends to watch.",
        "character_count": 184
      },
      {
        "platform": "linkedin",
        "content": "The sustainable packaging industry is undergoing a major transformation. In our latest deep-dive, we explore the trends driving change, from plant-based materials to circular economy models. Read the full article to learn how leading brands are reducing their environmental footprint while maintaining product quality.",
        "character_count": 312
      }
    ],
    "credits_used": 18
  }
}

MCP Server (Model Context Protocol)

The Model Context Protocol (MCP) is an open standard for connecting AI models to external tools and data sources. You can expose the Brainpercent API as an MCP server for any compatible AI client.

Instead of manually defining tool schemas in each client, an MCP server advertises its tools and handles execution. Any MCP-compatible client (Claude Desktop, Claude Code, and others) can discover and use these tools automatically.

MCP Server Skeleton
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server(
  { name: 'brainpercent', version: '1.0.0' },
  { capabilities: { tools: {} } }
);

server.setRequestHandler('tools/list', async () => ({
  tools: [
    {
      name: 'generate_article',
      description: 'Generate an SEO article via Brainpercent',
      inputSchema: {
        type: 'object',
        properties: {
          topic: { type: 'string', description: 'Article topic' },
          keywords: { type: 'array', items: { type: 'string' } },
          tone: { type: 'string', enum: ['professional', 'casual', 'academic'] },
          length: { type: 'string', enum: ['short', 'medium', 'long'] },
        },
        required: ['topic'],
      },
    },
    // Add more tools for other endpoints...
  ],
}));

server.setRequestHandler('tools/call', async (request) => {
  const { name, arguments: args } = request.params;

  // Route to Brainpercent API
  const response = await fetch('https://brainpercent.app/api/v1/articles/generate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.BRAINPERCENT_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(args),
  });

  const result = await response.json();
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
});

const transport = new StdioServerTransport();
await server.connect(transport);

Add this server to your MCP-compatible client's configuration to give Claude (or any MCP client) direct access to Brainpercent's content generation capabilities.

Prompt Examples

Common prompts and the tools Claude will use to fulfill them.

PromptTools UsedCredits
"Generate an article about AI trends"generate_article, check_article_status40
"Create social posts from my latest article"list_articles, generate_social_content18-36
"Check if I have enough credits for 5 articles"check_credits0
"Generate an article and share it on all platforms"generate_article, check_article_status, generate_social_content76

Best Practices

  • Always include check_credits as a tool so Claude can verify credit balance before expensive operations.
  • Use descriptive tool names and descriptions to help Claude choose the right tool.
  • Implement error handling in executeTool to return clear error messages Claude can interpret.
  • Consider adding a wait_for_article helper tool that combines polling logic.
  • Set reasonable max_tokens to control response length.
  • For production use, implement the MCP server approach for cleaner integration.