> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Build your agent with Spiral

> Give the agent you build and sell every AI model and tool through one key: the Claude Agent SDK, the OpenAI Agents SDK, the Vercel AI SDK, LangChain or plain REST.

Building an agent your customers use? Put Spiral inside it. One API key gives your agent the models it thinks with and
the tools it works with (image, video, audio, search, scraping and data), billed per run on your Spiral balance at the
providers' list prices. You add no provider accounts and sign no contracts; your customers never see Spiral.

[Magica.com](https://magica.com) serves 2M+ users across 150+ countries, running millions of AI tasks every month,
making it one of the fastest-growing AI products in the world.

> [card] Tools over MCP
>
> Connect `https://api.spiral.ai/mcp` as an MCP server. Your agent searches the catalog, checks a price and
> runs any tool, with no tool code of your own.

> [card] Models on the same key
>
> Point your framework's model client at Spiral's [LLM APIs](/docs/concepts/llm-apis.md) (Anthropic Messages and
> OpenAI formats). Claude, GPT, Gemini and the rest, on the same balance.

## Set up

Create a key under **API keys** in the [console](https://spiral.ai/start) and store it on your server as
`SPIRAL_API_KEY`. Give it a spend cap: see [keys](#keys-and-your-customers) below. Every example on this page uses that
one key and nothing else.

## Pick your framework

Each example is a complete program. It asks the agent for an image; the agent looks the tool up on Spiral, runs it and
answers with the image's link.

> [tab] Claude Agent SDK
>
> The SDK runs Claude Code's agent loop. Point it at Spiral for the model and add Spiral as an MCP server.
> `allowedTools` keeps the agent to Spiral's tools, without file or shell access.
>
> ```typescript TypeScript theme={null}
> // npm i @anthropic-ai/claude-agent-sdk
> import { query } from "@anthropic-ai/claude-agent-sdk";
>
> const key = process.env.SPIRAL_API_KEY!;
>
> for await (const message of query({
>   prompt: "Make a low-quality 1024x1024 image of a lighthouse at dawn with OpenAI's gpt-image-2, then reply with its link.",
>   options: {
>     // The model runs on Spiral too: one key, one balance.
>     model: "anthropic/claude-sonnet-5",
>     env: { ...process.env, ANTHROPIC_BASE_URL: "https://api.spiral.ai", ANTHROPIC_AUTH_TOKEN: key },
>     mcpServers: {
>       spiral: { type: "http", url: "https://api.spiral.ai/mcp", headers: { Authorization: `Bearer ${key}` } },
>     },
>     allowedTools: ["mcp__spiral__*"],
>   },
> })) {
>   if (message.type === "result" && message.subtype === "success") console.log(message.result);
> }
> ```
>
> ```python Python theme={null}
> # pip install claude-agent-sdk
> import asyncio, os
> from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
>
> key = os.environ["SPIRAL_API_KEY"]
>
> options = ClaudeAgentOptions(
>     # The model runs on Spiral too: one key, one balance.
>     model="anthropic/claude-sonnet-5",
>     env={"ANTHROPIC_BASE_URL": "https://api.spiral.ai", "ANTHROPIC_AUTH_TOKEN": key},
>     mcp_servers={
>         "spiral": {"type": "http", "url": "https://api.spiral.ai/mcp", "headers": {"Authorization": f"Bearer {key}"}}
>     },
>     allowed_tools=["mcp__spiral__*"],
> )
>
> async def main():
>     prompt = "Make a low-quality 1024x1024 image of a lighthouse at dawn with OpenAI's gpt-image-2, then reply with its link."
>     async for message in query(prompt=prompt, options=options):
>         if isinstance(message, ResultMessage):
>             print(message.result)
>
> asyncio.run(main())
> ```

> [tab] OpenAI Agents SDK
>
> ```python theme={null}
> # pip install openai-agents
> import asyncio, os
> from agents import Agent, OpenAIChatCompletionsModel, Runner, set_tracing_disabled
> from agents.mcp import MCPServerStreamableHttp
> from openai import AsyncOpenAI
>
> key = os.environ["SPIRAL_API_KEY"]
> set_tracing_disabled(True)  # traces go to OpenAI's platform, which a Spiral key cannot write to
>
> async def main():
>     async with MCPServerStreamableHttp(
>         name="spiral",
>         params={"url": "https://api.spiral.ai/mcp", "headers": {"Authorization": f"Bearer {key}"}, "timeout": 90},
>         client_session_timeout_seconds=90,
>     ) as spiral:
>         agent = Agent(
>             name="Studio",
>             instructions="You make media for the user with Spiral's tools.",
>             # The model runs on Spiral too, through its OpenAI-compatible API.
>             model=OpenAIChatCompletionsModel(
>                 model="openai/gpt-5-mini",
>                 openai_client=AsyncOpenAI(base_url="https://api.spiral.ai/v1", api_key=key),
>             ),
>             mcp_servers=[spiral],
>         )
>         result = await Runner.run(
>             agent, "Make a low-quality 1024x1024 image of a lighthouse at dawn with OpenAI's gpt-image-2, then reply with its link."
>         )
>         print(result.final_output)
>
> asyncio.run(main())
> ```
>
> The `run` tool waits up to 60 seconds for a result, so give the MCP session a longer timeout than the SDK's
> default of 5 seconds.

> [tab] Vercel AI SDK
>
> ```typescript theme={null}
> // npm i ai @ai-sdk/mcp @ai-sdk/anthropic
> import { createAnthropic } from "@ai-sdk/anthropic";
> import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";
> import { generateText, stepCountIs } from "ai";
>
> const key = process.env.SPIRAL_API_KEY!;
>
> const spiral = await createMCPClient({
>   transport: { type: "http", url: "https://api.spiral.ai/mcp", headers: { Authorization: `Bearer ${key}` } },
> });
> // The model runs on Spiral too, through its Anthropic-compatible API.
> const anthropic = createAnthropic({ baseURL: "https://api.spiral.ai/v1", apiKey: key });
>
> try {
>   const { text } = await generateText({
>     model: anthropic("anthropic/claude-sonnet-5"),
>     tools: await spiral.tools(),
>     stopWhen: stepCountIs(10),
>     prompt: "Make a low-quality 1024x1024 image of a lighthouse at dawn with OpenAI's gpt-image-2, then reply with its link.",
>   });
>   console.log(text);
> } finally {
>   await spiral.close();
> }
> ```
>
> `streamText` takes the same `tools`. Close the MCP client when the response ends.

> [tab] LangChain
>
> ```python theme={null}
> # pip install langchain langchain-mcp-adapters langchain-openai
> import asyncio, os
> from langchain_mcp_adapters.client import MultiServerMCPClient
> from langchain_openai import ChatOpenAI
> from langchain.agents import create_agent
>
> key = os.environ["SPIRAL_API_KEY"]
>
> async def main():
>     client = MultiServerMCPClient(
>         {
>             "spiral": {
>                 "transport": "streamable_http",
>                 "url": "https://api.spiral.ai/mcp",
>                 "headers": {"Authorization": f"Bearer {key}"},
>             }
>         }
>     )
>     tools = await client.get_tools()
>     # The model runs on Spiral too, through its OpenAI-compatible API.
>     model = ChatOpenAI(model="openai/gpt-5-mini", base_url="https://api.spiral.ai/v1", api_key=key)
>     agent = create_agent(model, tools)
>     result = await agent.ainvoke(
>         {"messages": [("user", "Make a low-quality 1024x1024 image of a lighthouse at dawn with OpenAI's gpt-image-2, then reply with its link.")]}
>     )
>     print(result["messages"][-1].content)
>
> asyncio.run(main())
> ```
>
> `create_agent` runs on LangGraph; the same tools work in any LangGraph graph.

> [tab] REST
>
> Your own tool-calling loop: the model and the tools are both plain HTTPS calls to Spiral. Define only the tools
> your product needs; here, a catalog search and a run.
>
> ```typescript theme={null}
> // Node.js 22 or later; no packages.
> const API = "https://api.spiral.ai/v1";
> const headers = { Authorization: `Bearer ${process.env.SPIRAL_API_KEY}`, "Content-Type": "application/json" };
>
> async function request(path: string, init?: RequestInit) {
>   const res = await fetch(`${API}${path}`, { ...init, headers: { ...headers, ...init?.headers } });
>   const body = await res.json();
>   if (!res.ok) throw new Error(`${res.status} ${body.code ?? body.error?.code}: ${body.detail ?? body.error?.message}`);
>   return { body, retryAfter: Number(res.headers.get("retry-after")) };
> }
> const call = async (path: string, init?: RequestInit) => (await request(path, init)).body;
> const ended = (run: { status: string }) => ["completed", "failed", "canceled"].includes(run.status);
>
> const tools = [
>   {
>     type: "function",
>     function: {
>       name: "search_tools",
>       description: "Search Spiral's catalog of models and tools. Returns provider and model ids.",
>       parameters: { type: "object", properties: { q: { type: "string" } }, required: ["q"] },
>     },
>   },
>   {
>     type: "function",
>     function: {
>       name: "run_tool",
>       description: "Run one Spiral tool with the provider's own input fields and wait for its result.",
>       parameters: {
>         type: "object",
>         properties: { provider: { type: "string" }, model: { type: "string" }, input: { type: "object" } },
>         required: ["provider", "model", "input"],
>       },
>     },
>   },
> ];
>
> async function runTool(callId: string, args: { name: string; arguments: string }) {
>   const a = JSON.parse(args.arguments);
>   if (args.name === "search_tools") {
>     const { items } = await call(`/tools?limit=5&q=${encodeURIComponent(a.q)}`);
>     return items.map((t: { provider: string; model: string; title: string }) => ({ provider: t.provider, model: t.model, title: t.title }));
>   }
>   // The tool call's id is the Idempotency-Key: retrying this call never starts or charges a second run.
>   let run = await call("/runs", { method: "POST", headers: { "Idempotency-Key": callId }, body: JSON.stringify(a) });
>   // Long-poll the same run until it ends: never start a second one. A webhook suits runs that take minutes.
>   // A poll can answer at once (the long-poll wait is not always granted): wait Retry-After, else back off.
>   for (let pause = 2; !ended(run); pause = Math.min(pause * 1.5, 30)) {
>     const poll = await request(`/runs/${run.id}?wait_seconds=30`);
>     run = poll.body;
>     if (!ended(run)) await new Promise((r) => setTimeout(r, (poll.retryAfter || pause) * 1000));
>   }
>   return run;
> }
>
> const messages: unknown[] = [
>   { role: "user", content: "Make a low-quality 1024x1024 image of a lighthouse at dawn with OpenAI's gpt-image-2, then reply with its link." },
> ];
> for (let turn = 0; turn < 10; turn++) {
>   const reply = await call("/chat/completions", {
>     method: "POST",
>     body: JSON.stringify({ model: "openai/gpt-5-mini", messages, tools }),
>   });
>   const msg = reply.choices[0].message;
>   messages.push(msg);
>   if (!msg.tool_calls?.length) {
>     console.log(msg.content);
>     break;
>   }
>   for (const tc of msg.tool_calls) {
>     messages.push({ role: "tool", tool_call_id: tc.id, content: JSON.stringify(await runTool(tc.id, tc.function)) });
>   }
> }
> ```
>
> Before the run, `GET /v1/tools/inspect` gives a tool's input schema and `POST /v1/estimate` its price: see the
> [API reference](/docs/api-reference/introduction.md).

Any other framework that speaks MCP (Mastra, Pydantic AI, Google's ADK, CrewAI and the rest) connects the same way: the
URL `https://api.spiral.ai/mcp` and the header `Authorization: Bearer <key>`. The [MCP tools](/docs/mcp-server/tools.md) page
lists every tool and its arguments.

## Run it in production

### Keys and your customers

Your agent's key stays on your server: never ship it in a browser or app bundle, and never hand it to your customers.

* **One key per agent or deployment**, each with its own spend cap and rate limits, created under **API keys**. A cap
  is reserved before a run starts, so a runaway loop stops at the cap instead of spending your balance.
* **One key per large customer** when you want a hard cap for that customer, or want to revoke one customer's access
  without touching the rest.
* **Name the customer on every run** with `end_user_id` (REST, and the MCP `run` tool) or the `X-Spiral-End-User-Id`
  header (LLM APIs). `GET /v1/runs?end_user_id=…` then lists that customer's runs and their cost, to bill them from.

If your agent shows prices to your customers, set its key to the [customer price
view](/docs/concepts/pricing.md#keys-for-your-own-users): every amount is then stated in your own unit with your markup, and
Spiral's USD cost is never shown.

### Long runs: webhooks or polling

Search, scraping and LLM calls answer in seconds. Images take seconds to a minute; video and long audio can take
minutes.

* **Over MCP**, the `run` tool waits up to 60 seconds and returns the finished run; a run still going comes back with
  its id, and the agent calls `get_run` until it ends.
* **Over REST**, add `webhook.url` to `POST /v1/runs` and Spiral posts the finished run to your server, signed: see
  [webhooks](/docs/concepts/webhooks.md). Without a webhook, long-poll `GET /v1/runs/{id}?wait_seconds=30`.

A run cannot be canceled once it starts, so start it only when the user asked for it. Output links expire after 30 days:
copy the files your customers keep to your own storage.

### Cost and balance

Every run holds its estimated price before it starts and is charged the measured usage when it ends; the run's `cost`
shows both.

* `estimate_cost` (MCP) or `POST /v1/estimate` (REST) gives a run's price before starting it, so your agent can ask
  your customer before an expensive video.
* A run your balance or the key's cap cannot cover is refused before any work, with `402 INSUFFICIENT_BALANCE` or a
  spend-cap error: nothing is charged.
* A model call holds the most it can cost, its whole output cap included, until it ends. Agent loops send large output
  caps, so many agents running at once can hold far more than they are charged. Keep headroom in the balance, or lower
  the output cap where your framework sets one.
* Turn on auto top-up and balance alerts under **Billing**, so your agent never stops for lack of credit. See
  [pricing](/docs/concepts/pricing.md).

### Retries without double charges

Send an `Idempotency-Key` on every `POST /v1/runs`: a UUID you create for the intent and store with your task. A retry
with the same key returns the first run, never a second run or charge. The MCP `run` tool sends one for you, and the LLM
APIs take the same header. See [idempotency](/docs/concepts/idempotency.md).

Tool errors carry the same codes as the REST API, with `retryable` saying whether a retry can succeed: see
[errors](/docs/api-reference/errors.md).

## Next

> [card] [MCP tools](/docs/mcp-server/tools.md)
>
> Every tool your agent can call, with its arguments.

> [card] [LLM APIs](/docs/concepts/llm-apis.md)
>
> The models on your key, in Anthropic and OpenAI formats.

> [card] [Webhooks](/docs/concepts/webhooks.md)
>
> Get finished runs pushed to your server, signed.

> [card] [Pricing](/docs/concepts/pricing.md)
>
> Holds, charges, spend caps and your own prices.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.