Sponsored by Deepsite.site

Swarms API MCP Server

Created By
The-Swarm-Corporation8 months ago
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

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Tavily Mcp
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
ChatWiseThe second fastest AI chatbot™
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Amap Maps高德地图官方 MCP Server
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Serper MCP ServerA Serper MCP Server
CursorThe AI Code Editor
Playwright McpPlaywright MCP server
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
WindsurfThe new purpose-built IDE to harness magic
DeepChatYour AI Partner on Desktop
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.