Skip to main content

Overview

The Swarms TypeScript MCP Server bridges MCP-compatible agents (Claude Desktop, Cursor IDE, OpenAI Agents, and other MCP clients) with the Swarms AI agent platform. Built with Stainless and following the Model Context Protocol standard, this server exposes Swarms’ API endpoints as discoverable tools that agents can invoke directly—enabling agents to execute single agents, orchestrate multi-agent swarms, run reasoning workflows, and process batch operations without custom API integration code.

Key Capabilities

  • Single Agent Execution: Run individual Swarms agents with custom tasks, model selection, and configuration parameters
  • Multi-Agent Orchestration: Coordinate swarms using architectural patterns including sequential workflows, concurrent execution, hierarchical structures, graph-based routing, and majority voting
  • Reasoning Agents: Execute chain-of-thought reasoning agents for step-by-step problem analysis and complex decision-making
  • Batch Processing: Process multiple agent tasks or swarm operations in parallel using thread pools for high-throughput workloads
  • Dynamic Discovery: Use runtime endpoint discovery to explore available API operations, or configure static tool exposure for better performance and type safety
  • Client Optimization: Automatically adapts tool schemas and capabilities to match your MCP client (Claude Desktop, Cursor IDE, OpenAI Agents, Claude Code, and custom clients)

Why Use This Server?

The Swarms MCP Server eliminates the need to write custom API integration code when building agent-powered applications. Instead of manually constructing HTTP requests, handling authentication, and parsing responses, agents can directly invoke Swarms operations through standardized MCP tools. The server provides production-ready error handling, rate limit monitoring, health checks, and flexible configuration options—allowing you to expose only the tools your agents need while maintaining full compatibility with the MCP ecosystem.

Table of Contents

  1. Installation
  2. Configuration
  3. Tool Exposure Strategies
  4. Client Compatibility
  5. Available Tools and Resources
  6. Advanced Usage
  7. Error Handling
  8. Best Practices
  9. Client Setup Examples

Installation

Prerequisites

  • Node.js (version 14 or higher recommended)
  • A valid Swarms API key
  • An MCP-compatible client application

Method 1: Direct Invocation via npx

For quick testing or one-time usage, you can run the MCP server directly without installation:
export SWARMS_API_KEY="your_api_key_here"
npx -y swarms-ts-mcp@latest

Method 2: Installation via npm

For persistent usage or integration into projects:
npm install swarms-ts-mcp

Method 3: MCP Client Configuration

Most MCP clients support configuration through a JSON file. Add the following configuration to your client’s MCP server settings:
{
  "mcpServers": {
    "swarms_ts_api": {
      "command": "npx",
      "args": ["-y", "swarms-ts-mcp", "--client=claude", "--tools=all"],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}
Replace your_api_key_here with your actual Swarms API key.

Configuration

Environment Variables

The server requires the following environment variable:
  • SWARMS_API_KEY: Your Swarms platform API key (required)

Command-Line Arguments

The MCP server supports extensive command-line configuration:

Tool Selection

  • --tools=all: Expose all available tools
  • --tools=dynamic: Enable dynamic tool discovery mode
  • --tool=<name>: Include a specific tool by name
  • --no-tool=<name>: Exclude a specific tool by name

Resource Filtering

  • --resource=<name>: Include all tools under a specific resource
  • --resource=<pattern>*: Include resources matching a wildcard pattern
  • --no-resource=<name>: Exclude a specific resource

Operation Filtering

  • --operation=read: Include only read operations (GET/LIST)
  • --operation=write: Include only write operations (POST/PUT/DELETE)

Client Configuration

  • --client=<type>: Configure for a specific MCP client
    • Valid values: openai-agents, claude, claude-code, cursor

Capability Settings

  • --capability=<name>: Enable specific client capabilities
    • top-level-unions: Support for top-level union types
    • valid-json: JSON string parsing for arguments
    • refs: Support for $ref pointers in schemas
    • unions: Support for union types (anyOf)
    • formats: Support for format validations
    • tool-name-length=N: Maximum tool name length

Utility Commands

  • --list: Display all available tools
  • --help: Show help information

Configuration Examples

Filter for read-only operations on a specific resource:
npx swarms-ts-mcp --resource=agent --operation=read
Exclude specific tools while including others:
npx swarms-ts-mcp --resource=swarms --no-tool=run_swarms_batch
Configure for Cursor with custom capabilities:
npx swarms-ts-mcp --client=cursor --capability=tool-name-length=40
Complex multi-criteria filtering:
npx swarms-ts-mcp --resource=agent,swarms --operation=read --no-tool=get_logs_swarms

Tool Exposure Strategies

The Swarms MCP server offers two primary strategies for exposing API endpoints as tools:

Static Tool Exposure

In this mode, each API endpoint is exposed as a dedicated tool with a fully-defined schema. This approach provides:
  • Better autocomplete and type safety in client applications
  • More accurate parameter validation
  • Clearer documentation for each endpoint
  • Optimal performance for smaller API surfaces
Recommendation: Use static exposure when working with a focused subset of the API or when the client has sufficient context window capacity.

Dynamic Tool Discovery

When configured with --tools=dynamic, the server exposes three meta-tools that enable runtime endpoint discovery:

list_api_endpoints

Discovers available endpoints with optional search filtering. Parameters:
  • search (optional): Query string to filter endpoints
Use case: Finding relevant endpoints without loading all schemas into context.

get_api_endpoint_schema

Retrieves detailed schema information for a specific endpoint. Parameters:
  • endpoint: The name or identifier of the endpoint
Use case: Obtaining parameter requirements before invoking an endpoint.

invoke_api_endpoint

Executes any endpoint with appropriate parameters. Parameters:
  • endpoint: The endpoint to invoke
  • parameters: JSON object containing endpoint-specific parameters
Use case: Making API calls after discovering and understanding the schema. Recommendation: Use dynamic tools when:
  • Working with a large API surface
  • Context window limitations are a concern
  • Runtime endpoint discovery is required
  • The full API schema exceeds available context

Hybrid Approach

You can combine both strategies by specifying explicit tools alongside dynamic tools:
npx swarms-ts-mcp --tool=run_agent --tools=dynamic
This provides immediate access to frequently-used tools while maintaining the flexibility of dynamic discovery.

Client Compatibility

Different MCP clients have varying capabilities for handling tool schemas and complex types. The Swarms MCP server automatically adapts its output based on the specified client.

Supported Clients

Claude (--client=claude)

Optimized for Claude AI assistant with full schema support.

Claude Code (--client=claude-code)

Configured for the Claude Code command-line environment.

Cursor (--client=cursor)

Adapted for the Cursor IDE with appropriate schema simplifications.

OpenAI Agents (--client=openai-agents)

Compatible with OpenAI’s agent framework.

Manual Capability Configuration

For clients not listed above or to override defaults:
npx swarms-ts-mcp --capability=top-level-unions,refs,unions,formats,tool-name-length=50
Available capabilities:
  • top-level-unions: Enables union types at the schema root
  • valid-json: Enables JSON string parsing for complex arguments
  • refs: Enables JSON Schema $ref pointers
  • unions: Enables anyOf union types
  • formats: Enables format validators (date-time, email, etc.)
  • tool-name-length=N: Sets maximum tool name length

Available Tools and Resources

The Swarms MCP server exposes 12 tools by default when using --tools=all. These tools are organized by resource and operation type, providing comprehensive access to the Swarms API functionality.

Complete Tools Reference Table

Tool NameResourceOperation TypeDescriptionPrimary Use Case
get_root_client$clientReadRoot client informationAPI connectivity verification and health checks
check_healthhealthReadHealth status of the Swarms APIMonitoring API uptime and status
run_agentagentWriteExecute a single agent with a specified taskRunning individual AI agents for specific tasks
run_agent_batchagent.batchWriteExecute multiple agents concurrently using thread poolParallel processing of multiple independent agent tasks
list_available_modelsmodelsReadRetrieve all available AI modelsModel discovery and selection for agent configuration
check_available_swarmsswarmsReadQuery available swarm types and configurationsDetermining which swarm architecture to use
get_logs_swarmsswarmsReadRetrieve API request logs for associated API keysAuditing, debugging, and usage analysis
run_swarmsswarmsWriteExecute a swarm with a specified taskOrchestrating multiple agents in coordinated patterns
run_swarms_batchswarms.batchWriteExecute multiple swarms concurrently using thread poolLarge-scale parallel swarm processing
create_completion_reasoning_agentsreasoning_agentsWriteExecute a reasoning agent with chain-of-thoughtComplex problem-solving requiring step-by-step analysis
list_types_reasoning_agentsreasoning_agentsReadList available reasoning agent typesSelecting appropriate reasoning strategies
get_limits_client_rateclient.rateReadQuery rate limits and current usage statisticsMonitoring API quota and preventing rate limit violations

Dynamic Discovery Tools

When using --tools=dynamic, these additional meta-tools become available:
Tool NameDescriptionParameters
list_api_endpointsDiscover available endpoints with optional filteringsearch (optional): Query string to filter endpoints
get_api_endpoint_schemaRetrieve detailed schema for a specific endpointendpoint: Endpoint name or identifier
invoke_api_endpointExecute any endpoint with appropriate parametersendpoint: Endpoint to invoke
parameters: JSON object with endpoint-specific parameters

Resource: $client

get_root_client (read)
  • Description: Root client information
  • Use case: Health checks and API connectivity verification

Resource: health

check_health (read)
  • Description: Health status of the Swarms API
  • Returns: API health metrics and status
  • Use case: Monitoring and uptime verification

Resource: agent

run_agent (write)
  • Description: Execute a single agent with a specified task
  • Parameters:
    • task: The task description for the agent
    • Additional agent configuration parameters
  • Returns: Agent execution results
  • Use case: Running individual AI agents for specific tasks

Resource: agent.batch

run_agent_batch (write)
  • Description: Execute multiple agents concurrently using a thread pool
  • Parameters:
    • tasks: Array of task descriptions
    • Batch configuration options
  • Returns: Aggregated results from all agents
  • Use case: Parallel processing of multiple independent tasks

Resource: models

list_available_models (read)
  • Description: Retrieve all available AI models
  • Returns: List of model identifiers and capabilities
  • Use case: Model discovery and selection

Resource: swarms

check_available_swarms (read)
  • Description: Query available swarm types and configurations
  • Returns: List of swarm architectures and their capabilities
  • Use case: Determining which swarm pattern to use
get_logs_swarms (read)
  • Description: Retrieve API request logs for all associated API keys
  • Returns: Log entries (excluding client IP information)
  • Use case: Auditing, debugging, and usage analysis
run_swarms (write)
  • Description: Execute a swarm with a specified task
  • Parameters:
    • task: The task for the swarm to execute
    • swarm_type: The type of swarm architecture
    • Additional swarm configuration
  • Returns: Swarm execution results
  • Use case: Orchestrating multiple agents in coordinated patterns

Resource: swarms.batch

run_swarms_batch (write)
  • Description: Execute multiple swarms concurrently using a thread pool
  • Parameters:
    • tasks: Array of swarm tasks
    • Batch and swarm configuration
  • Returns: Aggregated swarm results
  • Use case: Large-scale parallel swarm processing

Resource: reasoning_agents

create_completion_reasoning_agents (write)
  • Description: Execute a reasoning agent with chain-of-thought capabilities
  • Parameters:
    • task: The reasoning task
    • Reasoning configuration options
  • Returns: Reasoning output with intermediate steps
  • Use case: Complex problem-solving requiring step-by-step analysis
list_types_reasoning_agents (read)
  • Description: List available reasoning agent types
  • Returns: Reasoning agent architectures and their characteristics
  • Use case: Selecting appropriate reasoning strategies

Resource: client.rate

get_limits_client_rate (read)
  • Description: Query rate limits and current usage
  • Returns: Rate limit information and usage statistics
  • Use case: Monitoring API quota and preventing rate limit violations

Tools by Operation Type

The 12 default tools are divided into read and write operations:

Read Operations (7 tools)

Read operations are safe, idempotent operations that retrieve information without modifying state:
  • get_root_client
  • check_health
  • list_available_models
  • check_available_swarms
  • get_logs_swarms
  • list_types_reasoning_agents
  • get_limits_client_rate
Plus dynamic tools (when enabled):
  • list_api_endpoints
  • get_api_endpoint_schema

Write Operations (5 tools)

Write operations execute actions and may modify state or consume resources:
  • run_agent
  • run_agent_batch
  • run_swarms
  • run_swarms_batch
  • create_completion_reasoning_agents
Plus dynamic tool (when enabled):
  • invoke_api_endpoint
Total: 12 static tools (7 read + 5 write)

Advanced Usage

Programmatic Integration

For custom integrations, you can import and configure the server programmatically:
import { server, endpoints, init } from "swarms-ts-mcp/server";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

// Initialize the server with all endpoints
init({ server, endpoints });

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

Importing Specific Tools

import getRootClient from "swarms-ts-mcp/tools/top-level/get-root-client";
import { init } from "swarms-ts-mcp/server";

// Initialize with only specific tools
init({ 
  server: myServer, 
  endpoints: [getRootClient] 
});

Creating Custom Endpoints

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { zodToJsonSchema } from "zod-to-json-schema";
import { z } from "zod";

const myServer = new McpServer({
  name: "custom-swarms-server",
  version: "1.0.0"
});

const myCustomEndpoint = {
  tool: {
    name: 'my_custom_tool',
    description: 'Custom tool for specialized operations',
    inputSchema: zodToJsonSchema(z.object({ 
      query: z.string(),
      options: z.object({
        verbose: z.boolean().optional()
      }).optional()
    })),
  },
  handler: async (client, args) => {
    // Custom implementation
    return { 
      result: "Custom operation completed",
      data: args 
    };
  }
};

init({ 
  server: myServer, 
  endpoints: [myCustomEndpoint] 
});

Error Handling

When integrating with the Swarms MCP server, implement appropriate error handling:

Common Error Scenarios

  1. Authentication Errors: Invalid or missing API key
  2. Rate Limiting: Exceeded API quota
  3. Invalid Parameters: Malformed requests or missing required fields
  4. Network Issues: Connectivity problems or timeouts
  5. Resource Unavailability: Requested models or swarm types not available

Best Practices for Error Management

  • Always validate the presence of the SWARMS_API_KEY environment variable
  • Implement retry logic with exponential backoff for transient failures
  • Monitor rate limits using get_limits_client_rate before heavy operations
  • Log errors with sufficient context for debugging
  • Provide meaningful error messages to end users

Best Practices

Best Practice CategoryRecommendationDescription/Details
Batch OperationsUse batch endpointsWhen processing multiple tasks, prefer batch endpoints to reduce overhead.
Tool ExposureFilter unnecessary toolsMinimize context window usage by exposing only the tools required for your workflow.
Rate Limit MonitoringMonitor rate limitsRegularly check your usage with get_limits_client_rate to avoid hitting rate limits.
Model List OptimizationCache model listsStore the output of list_available_models to prevent repeated, redundant API calls.
API Key SecuritySecure API key storageNever commit API keys to version control; use secure secrets management.
Environment ManagementUse environment variablesManage sensitive information via secure environment variable configuration.
Access ControlLimit tool exposure by permissionRestrict tool access based on user permissions when possible.
Audit LoggingUtilize audit loggingUse get_logs_swarms for security auditing and tracking usage.
Tool Strategy (Exploration)Start with dynamic toolsUse --tools=dynamic during early exploration and development to discover available endpoints.
Tool Strategy (Production)Transition to static tool exposureOnce requirements are clear, switch to static tool exposure for performance and predictability.
Tool Filter TestingTest tool/resource/operation filtersVerify your configurations (--tool, --resource, --operation) to ensure only expected endpoints are exposed.
Client CompatibilityTest with target clientAlways verify integration and tool compatibility with your specific client setup.
Version ManagementPin production versionsSpecify the exact package version (e.g., [email protected]) in production deployments.
Health MonitoringImplement health checksRegularly call check_health to ensure server and API availability.
API ReliabilityHandle API unavailability gracefullyImplement graceful degradation strategies for scenarios when the API is down.
Internal DocumentationMaintain documentation of exposed toolsKeep internal documentation up-to-date on which tools/endpoints are available and why they’re exposed.

Client Setup Examples

Claude Code

Claude Code is a command-line tool that enables Claude to interact with your codebase and execute operations. Here’s how to configure the Swarms MCP server for Claude Code.

Configuration

Add the Swarms MCP server to your Claude Code configuration file (typically located at ~/.config/claude-code/mcp.json or similar):
{
  "mcpServers": {
    "swarms_api": {
      "command": "npx",
      "args": ["-y", "swarms-ts-mcp@latest", "--client=claude-code", "--tools=all"],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}
For optimal performance with Claude Code, consider using a focused set of tools:
{
  "mcpServers": {
    "swarms_api": {
      "command": "npx",
      "args": [
        "-y",
        "swarms-ts-mcp@latest",
        "--client=claude-code",
        "--resource=agent,swarms,reasoning_agents",
        "--capability=tool-name-length=50"
      ],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}

Usage Example: Running an Agent

Once configured, you can ask Claude Code to execute Swarms agents directly:
# In Claude Code, you can now use natural language:
# "Run a Swarms agent to analyze this codebase and generate a summary"
Claude Code will automatically invoke the run_agent tool:
{
  "tool": "run_agent",
  "parameters": {
    "task": "Analyze the codebase structure and generate a comprehensive summary of the architecture, key components, and dependencies.",
    "model": "gpt-4",
    "max_tokens": 2000
  }
}

Usage Example: Batch Processing

For processing multiple files or tasks:
# "Process all Python files in this directory using a batch of agents"
Claude Code will use the batch endpoint:
{
  "tool": "run_agent_batch",
  "parameters": {
    "tasks": [
      "Analyze file1.py and extract function signatures",
      "Analyze file2.py and identify class definitions",
      "Analyze file3.py and document module exports"
    ],
    "model": "gpt-4"
  }
}

Usage Example: Multi-Agent Swarm

For complex tasks requiring multiple agents:
# "Use a sequential swarm to: 1) analyze the code, 2) generate tests, 3) create documentation"
{
  "tool": "run_swarms",
  "parameters": {
    "task": "Analyze the codebase, generate comprehensive tests, and create API documentation",
    "swarm_type": "sequential_workflow",
    "model": "gpt-4"
  }
}

Usage Example: Reasoning Agent

For complex problem-solving tasks:
# "Use a reasoning agent to debug this error and provide a step-by-step solution"
{
  "tool": "create_completion_reasoning_agents",
  "parameters": {
    "task": "Debug the following error: [error message]. Provide a step-by-step analysis and solution.",
    "reasoning_type": "chain_of_thought"
  }
}

Dynamic Tool Discovery

If you prefer runtime discovery, configure with dynamic tools:
{
  "mcpServers": {
    "swarms_api": {
      "command": "npx",
      "args": [
        "-y",
        "swarms-ts-mcp@latest",
        "--client=claude-code",
        "--tools=dynamic"
      ],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}
Then use the discovery tools:
{
  "tool": "list_api_endpoints",
  "parameters": {
    "search": "agent"
  }
}

Claude Chat (Claude Desktop)

Claude Chat (Claude Desktop) provides a conversational interface where Claude can use MCP tools to interact with the Swarms API.

Configuration

Add the Swarms MCP server to your Claude Desktop configuration file. On macOS, this is typically located at ~/Library/Application Support/Claude/claude_desktop_config.json:
{
  "mcpServers": {
    "swarms_api": {
      "command": "npx",
      "args": ["-y", "swarms-ts-mcp@latest", "--client=claude", "--tools=all"],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}
For Claude Chat, you may want to expose all tools for maximum flexibility:
{
  "mcpServers": {
    "swarms_api": {
      "command": "npx",
      "args": [
        "-y",
        "swarms-ts-mcp@latest",
        "--client=claude",
        "--tools=all"
      ],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}

Usage Example: Health Check

Start by verifying the connection:
You: "Check if the Swarms API is healthy"
Claude will automatically use the health check tool:
{
  "tool": "check_health",
  "parameters": {}
}

Usage Example: Agent Execution

Execute agents through natural conversation:
You: "Run a Swarms agent to summarize the key points from this document"
Claude will invoke the agent:
{
  "tool": "run_agent",
  "parameters": {
    "task": "Summarize the key points from the provided document",
    "model": "gpt-4",
    "max_tokens": 1000
  }
}

Usage Example: Model Discovery

Discover available models before running agents:
You: "What models are available in Swarms?"
{
  "tool": "list_available_models",
  "parameters": {}
}

Usage Example: Swarm Orchestration

Use multi-agent swarms for complex workflows:
You: "Use a concurrent swarm to analyze these three documents in parallel and provide a comparative analysis"
{
  "tool": "run_swarms",
  "parameters": {
    "task": "Analyze three documents in parallel and provide a comparative analysis",
    "swarm_type": "concurrent_workflow",
    "model": "gpt-4"
  }
}

Usage Example: Rate Limit Monitoring

Check your API usage:
You: "What's my current rate limit status?"
{
  "tool": "get_limits_client_rate",
  "parameters": {}
}

Filtered Configuration Example

If you want to limit Claude Chat to read-only operations:
{
  "mcpServers": {
    "swarms_api": {
      "command": "npx",
      "args": [
        "-y",
        "swarms-ts-mcp@latest",
        "--client=claude",
        "--operation=read"
      ],
      "env": {
        "SWARMS_API_KEY": "your_api_key_here"
      }
    }
  }
}
This configuration exposes only read operations like check_health, list_available_models, check_available_swarms, and get_limits_client_rate, preventing accidental execution of agents or swarms.

Resources

ResourceLink
GitHub Repositoryswarms-ts GitHub
npm Packageswarms-ts-mcp on npm
Model Context Protocolmodelcontextprotocol.io
LicenseApache-2.0

Version Information

  • Current Version: 0.1.0-alpha.10
  • Status: Alpha release
  • Last Updated: 6 months ago

Support

For issues, feature requests, or contributions:
  • Open an issue on the GitHub repository
  • Review existing documentation and examples
  • Check the Model Context Protocol specification for general MCP questions