What This Tutorial Builds
A command-line tool you can run asnpm start "your question here" that:
- Connects to the hosted Swarms MCP server — nothing to install or self-host
- Runs a single agent and prints its answer
- Carries conversation history across turns so follow-up questions work
- Reports the exact cost of every call
- Fails loudly and correctly instead of printing
undefined
Why MCP Instead of Plain HTTP
You can callhttps://api.swarms.world/v1/agent/completions with fetch and it works. MCP earns its place when the same client also needs to discover what is available, or when the client is itself an agent choosing tools at runtime. Over MCP you get a typed tool list, a uniform result envelope, and one transport that any other MCP-aware program can reuse. The credential also lives on the transport rather than in your request bodies, so it never travels as a tool argument.
No installation required. The Swarms MCP server is hosted at
https://mcp.swarms.world/mcp. You need an API key from the API Keys page and nothing else.Step 1: Create the Project
"type": "module" in package.json so top-level await works, and add a start script:
Step 2: Connect to the Server
Createclient.ts. This is the only file that knows about transports and credentials.
Step 3: See What the Server Offers
Before writing any tool call, look at what is actually there. Createlist.ts:
run_agent_v1_agent_completions_post, which maps to POST /v1/agent/completions.
listTools works without a valid key — discovery is open. Only callTool requires credentials. That is useful when you want an agent to inspect the tool surface before you commit a key to it.Step 4: Your First Agent Call
Createagent.ts:
Step 5: Read the Result Correctly
Every tool result carries the same envelope, and getting this right is most of what separates a working client from a flaky one.
The critical detail: an upstream failure does not throw. A 429, a 422, an expired key — all of these come back as a normal result with
isError: true. If you skip the check and read structuredContent, you get undefined and a confusing crash three lines later.
outputs is an array because an agent running max_loops greater than one produces one entry per loop. The last entry is the final answer.
Step 6: Add Conversation History
A single call is stateless. To make follow-ups work, pass the prior turns back ashistory — an array of { role, content } objects.
Step 7: Handle Timeouts
Agents with highmax_loops, or swarms, routinely run longer than a default HTTP timeout. Raise it explicitly on the call:
Step 8: The Complete CLI
agent.ts, in full:
Common Errors
Next Steps
- Build a Multi-Agent Research Tool in Rust over MCP — when one agent is not enough
- Run a Batch Pipeline over MCP (Python) — for thousands of records
- Swarms API MCP Server — the full tool reference