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

# AI SDK Adapter - API Reference

> Functions, types, and options exported by @corti/ai-sdk-adapter

Complete API documentation for the `@corti/ai-sdk-adapter` package.

## Functions

### `convertToParams()`

Converts an array of `CortiUIMessage` objects (from the Vercel AI SDK `useChat` hook) into A2A `MessageSendParams` ready to send to a Corti agent.

```ts theme={null}
function convertToParams(
  messages: CortiUIMessage[],
  credentials?: ExpertCredential[]
): MessageSendParams;
```

| Parameter     | Type                 | Required | Description                        |
| :------------ | :------------------- | :------- | :--------------------------------- |
| `messages`    | `CortiUIMessage[]`   | Yes      | The messages array from `useChat`. |
| `credentials` | `ExpertCredential[]` | No       | Credentials for MCP servers.       |

**Returns:** `MessageSendParams` — an A2A-compatible params object you can pass to `client.sendMessage()` or `client.sendMessageStream()`.

**Automatic behavior:**

* Extracts `contextId` from the last assistant message to maintain conversation context.
* Includes `taskId` only when the last assistant message has `state: 'input-required'`.
* Attaches `credentials` only on the first message.

***

### `toUIMessageStream()`

Converts an A2A streaming response into a UI message stream compatible with the Vercel AI SDK's `createUIMessageStreamResponse()`.

```ts theme={null}
function toUIMessageStream(
  a2aStream: AsyncIterable<StreamEvent>,
  options?: StreamConversionOptions
): ReadableStream;
```

| Parameter   | Type                         | Required | Description                                          |
| :---------- | :--------------------------- | :------- | :--------------------------------------------------- |
| `a2aStream` | `AsyncIterable<StreamEvent>` | Yes      | The stream returned by `client.sendMessageStream()`. |
| `options`   | `StreamConversionOptions`    | No       | Configuration including lifecycle callbacks.         |

**Returns:** `ReadableStream` — a stream you can pass to `createUIMessageStreamResponse({ stream })`.

***

### `createA2AClientFactory()`

Creates a factory for building A2A clients that are pre-configured with Corti authentication.

```ts theme={null}
function createA2AClientFactory(
  cortiClient: CortiClient
): A2AClientFactory;
```

| Parameter     | Type          | Required | Description                                                |
| :------------ | :------------ | :------- | :--------------------------------------------------------- |
| `cortiClient` | `CortiClient` | Yes      | An authenticated `CortiClient` instance from `@corti/lib`. |

**Returns:** `A2AClientFactory` — a factory with a `createFromUrl(url, agentId)` method to build A2A clients.

**Usage:**

```ts theme={null}
import { createA2AClientFactory } from '@corti/ai-sdk-adapter';
import { CortiClient } from '@corti/lib';

const corti = new CortiClient({ /* config */ });
const factory = createA2AClientFactory(corti);

const agentUrl = await corti.agents.getCardUrl("YOUR_AGENT_ID");
const client = factory.createFromUrl(agentUrl.toString(), '');
```

***

### `createFetchImplementation()`

Creates a `fetch`-compatible function that automatically injects Corti authentication headers into every request. This is the lower-level primitive used internally by `createA2AClientFactory()`, but you can use it directly when you need a custom A2A client setup.

```ts theme={null}
function createFetchImplementation(
  client: CortiClient
): (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
```

| Parameter | Type          | Required | Description                                                |
| :-------- | :------------ | :------- | :--------------------------------------------------------- |
| `client`  | `CortiClient` | Yes      | An authenticated `CortiClient` instance from `@corti/sdk`. |

**Returns:** A `fetch`-compatible function `(input, init?) => Promise<Response>` that adds Corti authentication to outgoing requests.

**Usage:**

```ts theme={null}
import { createFetchImplementation } from '@corti/ai-sdk-adapter';
import { CortiClient } from '@corti/sdk';
import { ClientFactory } from '@a2a-js/sdk/client';

const corti = new CortiClient({ /* config */ });
const fetch = createFetchImplementation(corti);

// Use with A2A ClientFactory directly
const factory = new ClientFactory({ fetch });
```

***

## Types

### `CortiUIMessage`

Extends the standard Vercel AI SDK `UIMessage` with A2A-specific metadata and data parts.

```ts theme={null}
import type { CortiUIMessage } from '@corti/ai-sdk-adapter';
```

**Metadata fields:**

| Field       | Type       | Description                                           |
| :---------- | :--------- | :---------------------------------------------------- |
| `contextId` | `string`   | Conversation context identifier.                      |
| `taskId`    | `string`   | Task identifier for multi-turn interactions.          |
| `history`   | `object[]` | Conversation history from the A2A response.           |
| `credits`   | `number`   | Credits consumed by this response.                    |
| `state`     | `string`   | Task state (e.g., `'completed'`, `'input-required'`). |

**Custom data parts:**

| Part discriminator   | Type                | Description                         |
| :------------------- | :------------------ | :---------------------------------- |
| `data-text`          | `CortiTextPart`     | Text content with an optional name. |
| `data-json`          | `CortiJSONPart`     | Structured JSON data with a name.   |
| `data-status-update` | `CortiStatusUpdate` | Status update from the agent.       |

***

### `CortiTextPart`

A text data part. Alias for `string`.

```ts theme={null}
type CortiTextPart = string;
```

***

### `CortiJSONPart`

A JSON data part. Alias for `JSONValue` from `@ai-sdk/provider`.

```ts theme={null}
type CortiJSONPart = JSONValue;
```

***

### `CortiStatusUpdate`

A status update emitted by the agent during streaming.

```ts theme={null}
type CortiStatusUpdate = {
  state: string;
  message?: string;
};
```

| Field     | Type     | Required | Description                             |
| :-------- | :------- | :------- | :-------------------------------------- |
| `state`   | `string` | Yes      | Current task state.                     |
| `message` | `string` | No       | Optional human-readable status message. |

***

### `ExpertCredential`

Credentials for authenticating with MCP servers connected to a Corti agent.

```ts theme={null}
type ExpertCredential =
  | {
      mcp_name: string;
      token: string;
      type: 'bearer';
    }
  | {
      mcp_name: string;
      client_id: string;
      client_secret: string;
      type: 'oauth2.0';
    };
```

| Field           | Type                     | Description                                        |
| :-------------- | :----------------------- | :------------------------------------------------- |
| `mcp_name`      | `string`                 | Name of the MCP server to authenticate with.       |
| `token`         | `string`                 | Bearer token (when `type` is `'bearer'`).          |
| `client_id`     | `string`                 | OAuth client ID (when `type` is `'oauth2.0'`).     |
| `client_secret` | `string`                 | OAuth client secret (when `type` is `'oauth2.0'`). |
| `type`          | `'bearer' \| 'oauth2.0'` | Authentication method.                             |

***

### `StreamConversionOptions`

Options passed to `toUIMessageStream()` to configure stream behavior.

```ts theme={null}
interface StreamConversionOptions {
  callbacks?: {
    onStart?: () => void;
    onEvent?: (event: StreamEvent) => void;
    onFinish?: (state: TaskStatus) => void;
    onError?: (error: Error) => void;
    onAbort?: () => void;
  };
}
```

**Callback reference:**

| Callback   | Parameters           | Description                                                  |
| :--------- | :------------------- | :----------------------------------------------------------- |
| `onStart`  | —                    | Called when streaming begins.                                |
| `onEvent`  | `event: StreamEvent` | Called on each new event from the A2A stream.                |
| `onFinish` | `state: TaskStatus`  | Called when the stream completes with the final task status. |
| `onError`  | `error: Error`       | Called if an error occurs during streaming.                  |
| `onAbort`  | —                    | Called when the stream is aborted by the client.             |
