Skip to main content

Overview

When we interact with the prompt in the AI gateway playground, the playground UI renders the tool calls, their arguments, results and the LLM responses as they are streamed back from the gateway. If you want to do the same in your own application, or a different UI apart from the TrueFoundry playground, you can use the Agent API described below.

Quickstart

Get started with the Agent API in 3 simple steps:

Set your API token and base URL

See API Keys for details on getting your token.

Make your first request

Understand the response

You’ll receive a streaming response with:
  • Assistant content: The LLM’s text response
  • Tool calls: When the assistant decides to use tools (like web search)
  • Tool results: Output from executed tools
  • Follow-up: The assistant processes tool results and continues
The agent will automatically use the web_search tool to find image generation models and provide recommendations.

Request examples

Call with registered MCP servers

When you have MCP servers already registered in your TrueFoundry AI Gateway, you can reference them using their integration_fqn:

Use external MCP servers

You can connect to any MCP server accessible without pre-registering it in the gateway:

Override auth headers

You can override authentication per MCP server entry using either:
  1. The headers field in mcp_servers array (recommended): Pass headers directly in the request body for each MCP server entry
  2. The x-tfy-mcp-headers header: Pass headers in the HTTP request header using FQN-based format

Method 2: Using x-tfy-mcp-headers header (Registered servers only)

For Agent API requests with registered MCP servers, you can also pass custom headers using the x-tfy-mcp-headers HTTP header. This method uses an FQN-based format where you specify headers for each MCP server using its fully qualified name (FQN).
The x-tfy-mcp-headers header only works with registered MCP servers (using integration_fqn). For external servers (using url), you must use the headers field within the mcp_servers array as shown in Method 1.
Format: The header value should be a JSON string with the structure:
Key points:
  • Use the server’s full FQN as the key (e.g., truefoundry:mcp-server-group:remote-mcp-servers:mcp-server:hf-mcp-server)
  • You can copy the FQN from the MCP server details page using the Copy FQN button on the top right
  • For virtual servers, use the underlying remote server’s FQN
  • Headers specified here override any default authentication configured for the MCP server
Important differences:
  • The x-tfy-mcp-headers format for Agent API is different from the MCP Gateway format
  • Agent API always uses full FQN as keys (e.g., truefoundry:mcp-server-group:remote-mcp-servers:mcp-server:hf-mcp-server)
  • This method only works with registered servers (integration_fqn). For external servers, use the headers field in the mcp_servers array

API Reference

Request parameters

Request Parameters

About tool call iterations: An iteration represents a full loop of user → model → tool call → tool result → model. The iteration_limit sets the maximum number of such loops per request to prevent runaway chains.

MCP server configuration

Each entry in the mcp_servers array should include:

MCP Server Parameters

*Note: Either integration_fqn or url must be provided, but not both.

Tool configuration

Each entry in the tools array should include:

Tool Parameters

Streaming Response

The Chat API uses Server-Sent Events (SSE) to stream responses in real-time. This includes assistant text, tool calls (function names and their arguments), and tool results.
Both assistant content and tool call arguments are streamed incrementally across multiple chunks. You must accumulate these fragments to build complete responses.
Compatibility: The streaming format follows OpenAI Chat Completions streaming semantics. See the official guide: OpenAI streaming responses. In addition, the Gateway emits tool result chunks as extra delta events (with role: "tool", tool_call_id, and content) to carry tool outputs.

Quick Reference

Event Quick Reference

SSE Envelope

Each SSE line delivers a JSON payload:

Event Types

First chunk (role appears, empty content):
Subsequent chunk(s) with actual text:
  • Alternative: some models include the role on every chunk:
Role emission differs by provider. Do not assume the role is only present on the first chunk. Clients should set the role on the first chunk and carry it forward for subsequent chunks, and safely ignore repeated role fields on later chunks.
  • Concatenate delta.content across chunks to build the full assistant message.
Start of a tool call (function name announced):
Arguments streamed in later chunk(s):
  • Append function.arguments fragments per index to reconstruct full arguments.
  • Completion of this phase is indicated by finish_reason: "tool_calls".
Anthropic-specific behavior: Anthropic may stream an empty string for tool-call arguments ("arguments": ""). When invoking the tool, their API expects a valid JSON object. Normalize empty arguments to {} before issuing the call.
  • delta.role == "tool" indicates a tool result chunk.
  • The content is a JSON string; parse it to extract text or structured data if needed.

Processing Streaming events

How to Get the Code Snippet

You can generate a ready-to-use code snippet directly from the AI Gateway web UI:
  1. Go to the Playground or your MCP Server group in the AI Gateway.
  2. Click the API Code Snippet button.
  3. Copy the generated code and use it in your application.
The generated code snippet from the playground will only show the last assistant message, and will not show tool calls and results from that conversation.
TrueFoundry AI Gateway interface showing the API Code Snippet button

Agent API Code Snippet - Button

Generated code snippet for using the Agent API with MCP servers

Agent API Code Snippet - Example

Process streaming in code

OpenAI Client example

You can use the OpenAI client library with a custom base URL to handle the streaming response:

Configure client

  • Base URL: Point this to your Gateway Base URL with the /agent path which directly targets the Agent API.

Define common Agent configuration

  • model: Provider/model routed via Gateway.
  • mcp_servers: Select specific tools from an MCP server.
  • iteration_limit: Max agent tool-call iterations.

Collect streamed chunks into full messages

The get_messages function processes the streaming response to reconstruct complete messages. Let’s break it down:
1. Initialize and detect new messages
What’s happening: Each streaming chunk has an ID. When the ID changes, it signals a new message starting (assistant, tool result, etc.). We create a new message object with the role and empty content.
2. Handle tool result messages
What’s happening: Tool result messages have role: "tool" and include a tool_call_id that links the result back to the specific tool call that generated it.
3. Accumulate message content
What’s happening: Both assistant responses and tool results stream their content incrementally. We concatenate each chunk’s content to build the complete message.
4. Handle tool calls (function name and arguments)
What’s happening:
  • Tool calls are streamed with function names first, then arguments in chunks
  • Each tool call has an index to handle multiple simultaneous tool calls
  • We accumulate the arguments string as it streams in (like {"query": "Python tutorials"})
5. Apply Anthropic fix for empty arguments
What’s happening: Anthropic models sometimes send empty strings "" for tool arguments, but the OpenAI format expects "{}" for empty JSON objects. We normalize this.

Helper to send/merge a turn

Run a conversation and print outputs

Tool call flow

The streaming API follows this flow when tools are involved:
  1. Assistant Response Start: Initial content from the LLM (streamed)
  2. Tool Call Event: Function name, then arguments streamed incrementally
  3. Tool Execution: The gateway executes the complete tool call
  4. Tool Result Event: Results are streamed back
  5. Assistant Follow-up: The assistant processes results and continues

Stream termination

The stream ends with either:
  • A [DONE] message indicating completion
  • An error event if something goes wrong
  • Client disconnection