Swarms API MCP Server

Swarms API MCP Server

By The-Swarm-Corporation GitHub

-

swarms-api multi-agent-systems
Overview

What is Swarms API?

Swarms API is a powerful platform designed to build, deploy, and orchestrate AI agents at scale, providing a comprehensive suite of endpoints for managing multi-agent systems.

How to use Swarms API?

To use Swarms API, you need to obtain an API key and make requests to the various endpoints provided in the API documentation. You can run swarm tasks by sending a POST request with the required parameters.

Key features of Swarms API?

  • Powerful REST API for managing multi-agent systems.
  • Flexible Model Support for various AI models including GPT-4o and custom models.
  • Diverse Swarm Architectures to optimize task execution.
  • Dynamic Agent Configuration for customizable agent roles.
  • Real-time Monitoring of swarm performance.
  • Batch Processing for executing multiple tasks simultaneously.
  • Job Scheduling for automating recurring tasks.

Use cases of Swarms API?

  1. Automating financial analysis with multiple AI agents.
  2. Conducting market research using concurrent workflows.
  3. Scheduling tasks for data processing and analysis.

FAQ from Swarms API?

  • What types of AI models can I use?

You can use various models including GPT-4o, Claude, and custom models tailored to your needs.

  • Is there a cost associated with using the API?

Yes, API usage consumes credits based on the number of agents, input/output token count, and model selection.

  • How can I monitor API usage?

The API provides endpoints for tracking usage and credit consumption.

Content

Swarms API

Build, deploy, and orchestrate AI agents at scale with ease. Swarms API provides a comprehensive suite of endpoints for creating and managing multi-agent systems.

Languages: English | 中文

Features

FeatureDescription
Swarms APIA powerful REST API for managing and executing multi-agent systems with ease.
Flexible Model SupportUtilize various AI models, including GPT-4o, Claude, Deepseek, and custom models tailored to your needs.
Diverse Swarm ArchitecturesChoose from multiple swarm architectures such as Concurrent, Sequential, and Hybrid workflows to optimize task execution.
Dynamic Agent ConfigurationEasily configure agents with customizable parameters for different roles and tasks.
Supabase IntegrationBuilt-in database support for logging, API key management, and user authentication.
Real-time MonitoringTrack swarm performance and execution metrics in real-time for better insights and adjustments.
Batch ProcessingExecute multiple swarm tasks simultaneously for enhanced efficiency and throughput.
Job SchedulingSchedule swarm executions for future times to automate recurring tasks.
Usage TrackingMonitor API usage and credit consumption.

API Documentation & Resources

ResourceLink
DocumentationSwarms API Docs
Pricing InformationAPI Pricing
API KeysGet API Keys

API Endpoints

Core Endpoints

EndpointMethodDescriptionParameters
/healthGETCheck API healthNone
/v1/swarms/availableGETList available swarm typesNone

Swarm Operation Endpoints

EndpointMethodDescriptionParameters
/v1/swarm/completionsPOSTRun a single swarm taskSwarmSpec object
/v1/swarm/batch/completionsPOSTRun multiple swarm tasksArray of SwarmSpec objects
/v1/swarm/logsGETRetrieve API request logsNone

Scheduling Endpoints

EndpointMethodDescriptionParameters
/v1/swarm/schedulePOSTSchedule a swarm taskSwarmSpec with schedule object
/v1/swarm/scheduleGETList all scheduled jobsNone
/v1/swarm/schedule/{job_id}DELETECancel a scheduled jobjob_id

Request Parameters

SwarmSpec Object

ParameterTypeRequiredDescription
namestringNoName of the swarm
descriptionstringNoDescription of the swarm's purpose
agentsarrayYesArray of agent configurations
max_loopsintegerNoMaximum iteration loops (default: 1)
swarm_typestringNoType of workflow ("ConcurrentWorkflow", "SequentialWorkflow", etc.)
rearrange_flowstringNoInstructions to rearrange workflow
taskstringYesThe task to be performed
imgstringNoOptional image URL
return_historybooleanNoInclude conversation history (default: true)
rulesstringNoGuidelines for agent behavior
scheduleobjectNoScheduling details (for scheduled jobs)

AgentSpec Object

ParameterTypeRequiredDescription
agent_namestringYesName of the agent
descriptionstringNoAgent's purpose description
system_promptstringNoSystem prompt for the agent
model_namestringYesAI model to use (e.g., "gpt-4o", "claude-3-opus")
auto_generate_promptbooleanNoGenerate prompts automatically
max_tokensintegerNoMaximum tokens for responses (default: 8192)
temperaturefloatNoResponse randomness (default: 0.5)
rolestringNoAgent's role (default: "worker")
max_loopsintegerNoMaximum loops for this agent (default: 1)

ScheduleSpec Object

ParameterTypeRequiredDescription
scheduled_timedatetimeYesWhen to execute the task (in UTC)
timezonestringNoTimezone for scheduling (default: "UTC")

Swarm Types

  • AgentRearrange
  • MixtureOfAgents
  • SpreadSheetSwarm
  • SequentialWorkflow
  • ConcurrentWorkflow
  • GroupChat
  • MultiAgentRouter
  • AutoSwarmBuilder
  • HiearchicalSwarm
  • auto
  • MajorityVoting

Authentication

All API endpoints (except health check) require an API key passed in the x-api-key header:

curl -H "x-api-key: your_api_key" -H "Content-Type: application/json" -X POST https://api.swarms.world/v1/swarm/completions

Example Usage

Here's a basic example of running a swarm with multiple agents:

import os
import requests
from dotenv import load_dotenv
import json

load_dotenv()

API_KEY = os.getenv("SWARMS_API_KEY")
BASE_URL = "https://api.swarms.world"

headers = {"x-api-key": API_KEY, "Content-Type": "application/json"}

def run_single_swarm():
    payload = {
        "name": "Financial Analysis Swarm",
        "description": "Market analysis swarm",
        "agents": [
            {
                "agent_name": "Market Analyst",
                "description": "Analyzes market trends",
                "system_prompt": "You are a financial analyst expert.",
                "model_name": "gpt-4o",
                "role": "worker",
                "max_loops": 1,
                "max_tokens": 8192,
                "temperature": 0.5
            },
            {
                "agent_name": "Economic Forecaster",
                "description": "Predicts economic trends",
                "system_prompt": "You are an expert in economic forecasting.",
                "model_name": "gpt-4o",
                "role": "worker",
                "max_loops": 1,
                "max_tokens": 8192,
                "temperature": 0.7
            },
            {
                "agent_name": "Data Scientist",
                "description": "Performs data analysis",
                "system_prompt": "You are a data science expert.",
                "model_name": "gpt-4o",
                "role": "worker",
                "max_loops": 1,
                "max_tokens": 8192,
                "temperature": 0.3
            },
        ],
        "max_loops": 1,
        "swarm_type": "ConcurrentWorkflow",
        "task": "What are the best ETFs and index funds for AI and tech?",
        "return_history": True,
    }

    response = requests.post(
        f"{BASE_URL}/v1/swarm/completions",
        headers=headers,
        json=payload,
    )

    return json.dumps(response.json(), indent=4)

if __name__ == "__main__":
    result = run_single_swarm()
    print("Swarm Result:")
    print(result)

MCP

You can leverage the swarms api as a MCP server like listed below. Click here for the code

# server.py
from datetime import datetime
import os
from typing import Any, Dict, List, Optional

import requests
import httpx
from fastmcp import FastMCP
from pydantic import BaseModel, Field
from swarms import SwarmType
from dotenv import load_dotenv

load_dotenv()



BASE_URL = "https://swarms-api-285321057562.us-east1.run.app"


# Create an MCP server
mcp = FastMCP("swarms-api")


# Add an addition tool
@mcp.tool(name="swarm_completion", description="Run a swarm completion.")
def swarm_completion(swarm: SwarmSpec) -> Dict[str, Any]:
    api_key = os.getenv("SWARMS_API_KEY")
    headers = {"x-api-key": api_key, "Content-Type": "application/json"}

    payload = swarm.model_dump()

    response = requests.post(f"{BASE_URL}/v1/swarm/completions", json=payload, headers=headers)
    
    return response.json()

@mcp.tool(name="swarms_available", description="Get the list of available swarms.")
async def swarms_available() -> Any:
    """
    Get the list of available swarms.
    """
    headers = {"Content-Type": "application/json"}

    async with httpx.AsyncClient() as client:
        response = await client.get(f"{BASE_URL}/v1/models/available", headers=headers)
        response.raise_for_status()  # Raise an error for bad responses
        return response.json()


if __name__ == "__main__":
    mcp.run(transport="sse")

Credit Usage

API usage consumes credits based on:

  1. Number of agents used

  2. Input/output token count

  3. Model selection

  4. Time of day (discounts during off-peak hours)

For detailed pricing information, visit the API Pricing page.

Error Handling

HTTP Status CodeDescription
200Success
400Bad request (invalid parameters)
401Unauthorized (invalid or missing API key)
402Payment required (insufficient credits)
429Rate limit exceeded
500Internal server error

Getting Support

For questions or support:

Todo

No tools information available.
Swarms API MCP Server
Swarms API MCP Server by The-Swarm-Corporation

-

swarms-api multi-agent-systems
View Details