# MutagenT SDK

<!-- NOTE: README.npm.md is the public-facing README for npm publish.
     See publish workflow for copy step. -->

```bash
╔════════════════════════════════════════════════════════════════════════════════════════════╗
║                                                                                            ║
║        ███╗   ███╗██╗   ██╗████████╗ █████╗  ██████╗ ███████╗███╗   ██╗████████╗           ║
║        ████╗ ████║██║   ██║╚══██╔══╝██╔══██╗██╔════╝ ██╔════╝████╗  ██║╚══██╔══╝           ║
║        ██╔████╔██║██║   ██║   ██║   ███████║██║  ███╗█████╗  ██╔██╗ ██║   ██║              ║
║        ██║╚██╔╝██║██║   ██║   ██║   ██╔══██║██║   ██║██╔══╝  ██║╚██╗██║   ██║              ║
║        ██║ ╚═╝ ██║╚██████╔╝   ██║   ██║  ██║╚██████╔╝███████╗██║ ╚████║   ██║              ║
║        ╚═╝     ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚═╝  ╚═══╝   ╚═╝              ║
║                                                                                            ║
║                   ███████╗██████╗ ██╗  ██╗                                                 ║
║                   ██╔════╝██╔══██╗██║ ██╔╝                                                 ║
║                   ███████╗██║  ██║█████╔╝                                                  ║
║                   ╚════██║██║  ██║██╔═██╗                                                  ║
║                   ███████║██████╔╝██║  ██╗                                                 ║
║                   ╚══════╝╚═════╝ ╚═╝  ╚═╝                                                 ║
║                                                                                            ║
║                         TypeScript SDK for AI-Native Development.                          ║
║                                                                                            ║
╚════════════════════════════════════════════════════════════════════════════════════════════╝
```

<p align="center">
  <a href="https://www.npmjs.com/package/@mutagent/sdk"><img src="https://img.shields.io/npm/v/@mutagent/sdk?style=for-the-badge&color=cb3837&logo=npm&logoColor=white" alt="npm"></a>
  <a href="https://bun.sh"><img src="https://img.shields.io/badge/Bun-1.1+-f472b6?style=for-the-badge&logo=bun&logoColor=white" alt="Bun"></a>
  <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node-18+-339933?style=for-the-badge&logo=node.js&logoColor=white" alt="Node.js"></a>
  <a href="https://www.typescriptlang.org"><img src="https://img.shields.io/badge/TypeScript-5.0+-3178C6?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript"></a>
  <a href="#"><img src="https://img.shields.io/badge/License-Proprietary-ff6b6b?style=for-the-badge" alt="License: Proprietary"></a>
</p>

<p align="center">
  <strong>Type-safe. Framework-agnostic. Production-ready.</strong><br>
  <em>The official SDK for building with the MutagenT AI platform.</em>
</p>

---

## 🎯 What is MutagenT SDK?

The **MutagenT SDK** is a developer-friendly, type-safe TypeScript client for the MutagenT AI platform. Built for modern AI applications, it provides:

- 🔒 **Full Type Safety** - End-to-end TypeScript with Zod validation
- 🚀 **Multiple Runtimes** - Works with Bun, Node.js, Deno, and Edge runtimes
- 📦 **Multiple Module Formats** - ESM, CommonJS, and UMD support
- 🌲 **Tree-shakeable** - Import only what you need
- ⚡ **Auto-generated** - Always in sync with the latest API

### Core Capabilities

| Feature | Description |
|---------|-------------|
| **Prompt Management** | Create, version, and optimize prompts programmatically |
| **Dataset Operations** | Import, export, and manage evaluation datasets |
| **Evaluation Engine** | Run automated evaluations against your prompts |
| **Auto-Optimization** | Let AI improve your prompts based on metrics |
| **Trace Collection** | Replace Langfuse with native observability |
| **Multi-tenant** | Organizations, workspaces, and teams |

---

## 📦 Installation

### Using npm

```bash
npm install @mutagent/sdk
```

### Using pnpm

```bash
pnpm add @mutagent/sdk
```

### Using Bun

```bash
bun add @mutagent/sdk
```

### Using Yarn

```bash
yarn add @mutagent/sdk
```

> **Note:** This package supports both CommonJS (`require`) and ES Modules (`import`).

---

## 🚀 Quick Start

### 1. Initialize the Client

```typescript
import { Mutagent } from '@mutagent/sdk';

const mutagent = new Mutagent({
  security: {
    apiKey: process.env.MUTAGENT_API_KEY,
  },
  serverURL: 'https://api.mutagent.io/v1', // Optional
});
```

### 2. Create Your First Prompt

```typescript
const prompt = await mutagent.prompt.createPrompt({
  name: 'Customer Support Template',
  content: 'You are a helpful support agent. User query: {{query}}',
  variables: ['query'],
});

console.log(`Created prompt: ${prompt.id}`);
```

### 3. Add a Dataset

```typescript
const dataset = await mutagent.promptDatasets.createPromptDataset({
  id: prompt.id,
  name: 'Support Tickets',
  description: 'Real customer support interactions',
});

// Add items to dataset
await mutagent.promptDatasetItems.bulkCreatePromptDatasetItems({
  id: dataset.id,
  items: [
    { input: { query: 'How do I reset my password?' }, expected: '...' },
    { input: { query: 'What are your business hours?' }, expected: '...' },
  ],
});
```

### 4. Run Optimization

```typescript
const optimization = await mutagent.optimization.optimizePrompt({
  id: prompt.id,
  datasetId: dataset.id,
  metric: 'response_quality',
});

// Check progress
const status = await mutagent.optimization.getOptimization({
  id: optimization.id,
});

console.log(`Optimization progress: ${status.progress}%`);
```

### 5. Get Optimized Prompt

```typescript
const results = await mutagent.optimization.getOptimizationProgress({
  id: optimization.id,
});

// Use the optimized version
const optimizedPrompt = results.bestVersion;
```

---

## 🔐 Authentication

The SDK supports both API key and Bearer token authentication. Set your credentials when initializing:

```typescript
const mutagent = new Mutagent({
  security: {
    apiKey: process.env.MUTAGENT_API_KEY,
    // OR use bearerAuth:
    // bearerAuth: process.env.MUTAGENT_BEARER_AUTH,
  },
});
```

Or use environment variables:

```bash
export MUTAGENT_API_KEY="sk_live_xxxxxxxx"
# OR
export MUTAGENT_BEARER_AUTH="your-bearer-token"
```

---

## 📚 Core Resources

### Prompts

```typescript
// List all prompts
const prompts = await mutagent.prompt.listPrompts();

// Get a specific prompt
const prompt = await mutagent.prompt.getPrompt({ id: 'prompt-id' });

// Update a prompt
await mutagent.prompt.updatePrompt({
  id: 'prompt-id',
  content: 'Updated prompt content...',
});

// Create a new version
await mutagent.prompt.createPromptVersion({
  id: 'prompt-id',
  content: 'New version content...',
});
```

### Datasets

```typescript
// List datasets for a prompt
const datasets = await mutagent.promptDatasets.listDatasetsForPrompt({
  id: 'prompt-id',
});

// Create dataset
const dataset = await mutagent.promptDatasets.createPromptDataset({
  id: 'prompt-id',
  name: 'My Dataset',
});

// Export dataset
const exportData = await mutagent.promptDatasets.exportPromptDataset({
  id: 'dataset-id',
});
```

### Evaluations

```typescript
// Create evaluation
const evaluation = await mutagent.promptEvaluations.createEvaluation({
  promptId: 'prompt-id',
  datasetId: 'dataset-id',
  metrics: ['accuracy', 'relevance'],
});

// Run evaluation
await mutagent.promptEvaluations.runEvaluation({
  id: evaluation.id,
});

// Get results
const results = await mutagent.promptEvaluations.getEvaluationResult({
  id: evaluation.id,
});
```

### Agents

```typescript
// Create an agent
const agent = await mutagent.agents.createAgent({
  name: 'Support Agent',
  description: 'Handles customer support queries',
  promptId: 'prompt-id',
});

// Create conversation
const conversation = await mutagent.agentConversations.createAgentConversation({
  id: agent.id,
});

// Send message
await mutagent.conversations.sendConversationMessage({
  id: conversation.id,
  content: 'How do I reset my password?',
});
```

---

## 📊 Tracing & Observability

The SDK includes built-in tracing support to collect and analyze LLM interactions, chains, and agent workflows.

### Initialize Tracing

```typescript
import { initTracing, shutdownTracing } from '@mutagent/sdk';

// Initialize tracing with your MutagenT API key
initTracing({
  apiKey: process.env.MUTAGENT_API_KEY!,
  endpoint: 'https://api.mutagent.io',
  environment: 'production',
  batchSize: 10,        // Optional: spans per batch (default: 10)
  flushInterval: 5000,  // Optional: flush every 5s (default: 5000ms)
});

// Your application code here...

// Shutdown tracing when your app exits (flushes remaining spans)
await shutdownTracing();
```

### Using the @trace Decorator

Automatically instrument class methods with the `@trace` decorator:

```typescript
import { trace } from '@mutagent/sdk';

class MyAgent {
  @trace({ kind: 'agent', name: 'customer-support-agent' })
  async processQuery(query: string) {
    // Method automatically traced with input/output/duration
    const response = await this.generateResponse(query);
    return response;
  }

  @trace({ kind: 'llm.chat', name: 'openai-gpt4' })
  private async generateResponse(query: string) {
    // LLM call is traced separately
    return await callOpenAI(query);
  }
}
```

### Using the withTrace Wrapper

For functional-style code or fine-grained control:

```typescript
import { withTrace } from '@mutagent/sdk';

async function ragPipeline(query: string) {
  return await withTrace(
    { kind: 'chain', name: 'rag-pipeline' },
    async (span) => {
      // Add custom attributes
      span.setAttributes({
        'gen_ai.model': 'gpt-4',
        'user.query': query,
      });

      // Retrieve documents
      const docs = await retrieveDocuments(query);
      span.addEvent('documents_retrieved', { count: docs.length });

      // Generate answer
      const answer = await generateAnswer(query, docs);

      // Set output
      span.setOutput({ text: answer, sources: docs.map(d => d.id) });

      return answer;
    }
  );
}
```

### SpanKinds Taxonomy

The SDK supports the following span kinds for categorizing traces:

| SpanKind | Description | Example Use Case |
|----------|-------------|------------------|
| `llm.chat` | Chat completion calls | OpenAI ChatGPT, Anthropic Claude |
| `llm.completion` | Text completion calls | GPT-3 Davinci, Legacy completions |
| `llm.embedding` | Embedding generation | OpenAI Embeddings, Cohere Embed |
| `chain` | Sequential processing pipeline | LangChain chains, RAG pipelines |
| `agent` | Autonomous agent execution | ReAct agents, AutoGPT |
| `graph` | State graph execution | LangGraph workflows |
| `node` | Individual graph node | Graph state transitions |
| `edge` | Graph transitions | Conditional routing |
| `workflow` | Multi-step workflows | Business process automation |
| `middleware` | Request/response processing | Auth, rate limiting |
| `tool` | External tool calls | API calls, calculators |
| `retrieval` | Document retrieval | Vector search, keyword search |
| `rerank` | Result reranking | Cohere Rerank, cross-encoders |
| `guardrail` | Safety/validation checks | PII detection, content filtering |
| `custom` | Custom operations | Your domain-specific ops |

---

## 🌲 Tree-shakeable Imports

Import only what you need for smaller bundle sizes:

```typescript
// Import specific operations as standalone functions
import {
  promptListPrompts,
  promptCreatePrompt,
  promptDatasetsListDatasetsForPrompt,
} from '@mutagent/sdk/functions';

// Use standalone functions (pass client or security directly)
const prompts = await promptListPrompts(client);
const prompt = await promptCreatePrompt(client, {
  name: 'New Prompt',
  content: 'Template with {{variable}}',
});
```

---

## 🔄 Error Handling

```typescript
import { Mutagent } from '@mutagent/sdk';

const mutagent = new Mutagent({
  security: {
    apiKey: process.env.MUTAGENT_API_KEY,
  },
});

try {
  const prompt = await mutagent.prompt.getPrompt({ id: 'invalid-id' });
} catch (error) {
  if (error.statusCode === 404) {
    console.error('Prompt not found');
  } else if (error.statusCode === 401) {
    console.error('Authentication failed');
  } else {
    console.error('Unknown error:', error);
  }
}
```

---

## 🛠️ Framework Integrations

Use MutagenT with your favorite framework:

### Mastra

```typescript
import { MutagentObserver } from '@mutagent/sdk/mastra';

const observer = new MutagentObserver({
  apiKey: process.env.MUTAGENT_API_KEY,
});
```

### LangChain

```typescript
import { MutagentCallbackHandler } from '@mutagent/sdk/langchain';

const handler = new MutagentCallbackHandler({
  apiKey: process.env.MUTAGENT_API_KEY,
  promptId: 'my-prompt',
});

const llm = new ChatOpenAI({ callbacks: [handler] });
```

### Vercel AI SDK

```typescript
import { withMutagent } from '@mutagent/sdk/vercel-ai';

const result = await withMutagent(
  streamText({ model: openai('gpt-4o'), messages }),
  { apiKey: process.env.MUTAGENT_API_KEY }
);
```

See full integration guides with the [MutagenT CLI](https://github.com/mutagent/mutagent-cli):

```bash
npx @mutagent/cli integrate mastra
```

---

## 🌍 Server Selection

```typescript
const mutagent = new Mutagent({
  security: {
    apiKey: process.env.MUTAGENT_API_KEY,
  },
  serverURL: 'https://api.mutagent.io/v1', // Production (default)
  // serverURL: 'https://staging-api.mutagent.io/v1', // Staging
  // serverURL: 'http://localhost:3003', // Local development
});
```

---

## 🧪 Development

### Prerequisites

- [Bun](https://bun.sh) >= 1.1.0
- Node.js >= 18.0.0

### Setup

```bash
git clone https://github.com/mutagent/mutagent-sdk.git
cd mutagent-sdk
bun install
```

### Build

```bash
bun run build
```

### Test

```bash
bun test
```

---

## 📖 API Reference

For detailed API documentation, see:

- [SDK Reference](./docs/sdks/)
- [Standalone Functions](./FUNCTIONS.md)
- [Runtime Support](./RUNTIMES.md)

---

## 🤝 Contributing

Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md).

---

## 📄 License

This software is proprietary and confidential. Unauthorized copying, distribution, or use is strictly prohibited.

© 2026 MutagenT. All rights reserved.

---

For full API reference, see [docs.mutagent.io](https://docs.mutagent.io)

---

<p align="center">
  <sub>Built with ❤️ by the MutagenT Team</sub>
</p>

<p align="center">
  <a href="https://twitter.com/mutagent">Twitter</a> •
  <a href="https://discord.gg/mutagent">Discord</a> •
  <a href="https://mutagent.io">Website</a> •
  <a href="https://docs.mutagent.io">Documentation</a>
</p>

<!-- Start Summary [summary] -->
## Summary

MutagenT Server API Documentation: Comprehensive API documentation for MutagenT AI Agent Server with Auto-tuning capabilities
<!-- End Summary [summary] -->

<!-- Start Table of Contents [toc] -->
## Table of Contents
<!-- $toc-max-depth=2 -->
* [MutagenT SDK](#mutagent-sdk)
  * [🎯 What is MutagenT SDK?](#what-is-mutagent-sdk)
  * [📦 Installation](#installation)
  * [🚀 Quick Start](#quick-start)
  * [🔐 Authentication](#authentication)
  * [📚 Core Resources](#core-resources)
  * [📊 Tracing & Observability](#tracing-observability)
  * [🌲 Tree-shakeable Imports](#tree-shakeable-imports)
  * [🔄 Error Handling](#error-handling)
  * [🛠️ Framework Integrations](#framework-integrations)
  * [🌍 Server Selection](#server-selection)
  * [🧪 Development](#development)
  * [📖 API Reference](#api-reference)
  * [🤝 Contributing](#contributing)
  * [📄 License](#license)
  * [SDK Installation](#sdk-installation)
  * [Requirements](#requirements)
  * [SDK Example Usage](#sdk-example-usage)
  * [Authentication](#authentication-1)
  * [Available Resources and Operations](#available-resources-and-operations)
  * [Standalone functions](#standalone-functions)
  * [Pagination](#pagination)
  * [Retries](#retries)
  * [Error Handling](#error-handling-1)
  * [Server Selection](#server-selection-1)
  * [Custom HTTP Client](#custom-http-client)
  * [Debugging](#debugging)

<!-- End Table of Contents [toc] -->

<!-- Start SDK Installation [installation] -->
## SDK Installation

The SDK can be installed with either [npm](https://www.npmjs.com/), [pnpm](https://pnpm.io/), [bun](https://bun.sh/) or [yarn](https://classic.yarnpkg.com/en/) package managers.

### NPM

```bash
npm add @mutagent/sdk
```

### PNPM

```bash
pnpm add @mutagent/sdk
```

### Bun

```bash
bun add @mutagent/sdk
```

### Yarn

```bash
yarn add @mutagent/sdk
```

> [!NOTE]
> This package is published with CommonJS and ES Modules (ESM) support.
<!-- End SDK Installation [installation] -->

<!-- Start Requirements [requirements] -->
## Requirements

For supported JavaScript runtimes, please consult [RUNTIMES.md](RUNTIMES.md).
<!-- End Requirements [requirements] -->

<!-- Start SDK Example Usage [usage] -->
## SDK Example Usage

### Example

```typescript
import { Mutagent } from "@mutagent/sdk";

const mutagent = new Mutagent({
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  const result = await mutagent.userProfile.getProfile();

  console.log(result);
}

run();

```
<!-- End SDK Example Usage [usage] -->

<!-- Start Authentication [security] -->
## Authentication

### Per-Client Security Schemes

This SDK supports the following security schemes globally:

| Name         | Type   | Scheme      | Environment Variable   |
| ------------ | ------ | ----------- | ---------------------- |
| `apiKey`     | apiKey | API key     | `MUTAGENT_API_KEY`     |
| `bearerAuth` | http   | HTTP Bearer | `MUTAGENT_BEARER_AUTH` |

You can set the security parameters through the `security` optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
```typescript
import { Mutagent } from "@mutagent/sdk";

const mutagent = new Mutagent({
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  const result = await mutagent.userProfile.getProfile();

  console.log(result);
}

run();

```
<!-- End Authentication [security] -->

<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations

<details open>
<summary>Available methods</summary>

### [Agents](docs/sdks/agents/README.md)

* [listAgents](docs/sdks/agents/README.md#listagents) - List agents
* [createAgent](docs/sdks/agents/README.md#createagent) - Create agent
* [getAgent](docs/sdks/agents/README.md#getagent) - Get agent
* [updateAgent](docs/sdks/agents/README.md#updateagent) - Update agent
* [deleteAgent](docs/sdks/agents/README.md#deleteagent) - Delete agent
* [getAgentBySlug](docs/sdks/agents/README.md#getagentbyslug) - Get agent by slug

### [Invitations](docs/sdks/invitations/README.md)

* [createInvitation](docs/sdks/invitations/README.md#createinvitation) - Create invitation
* [listInvitations](docs/sdks/invitations/README.md#listinvitations) - List organization invitations
* [getInvitation](docs/sdks/invitations/README.md#getinvitation) - Get invitation
* [deleteInvitation](docs/sdks/invitations/README.md#deleteinvitation) - Delete/revoke invitation
* [resendInvitation](docs/sdks/invitations/README.md#resendinvitation) - Resend invitation

### [OrganizationMembers](docs/sdks/organizationmembers/README.md)

* [listOrganizationMembers](docs/sdks/organizationmembers/README.md#listorganizationmembers) - List organization members
* [addOrganizationMember](docs/sdks/organizationmembers/README.md#addorganizationmember) - Add organization member
* [updateOrganizationMember](docs/sdks/organizationmembers/README.md#updateorganizationmember) - Update member role
* [removeOrganizationMember](docs/sdks/organizationmembers/README.md#removeorganizationmember) - Remove organization member

### [Organizations](docs/sdks/organizations/README.md)

* [createOrganization](docs/sdks/organizations/README.md#createorganization) - Create organization
* [listOrganizations](docs/sdks/organizations/README.md#listorganizations) - List user organizations
* [getOrganization](docs/sdks/organizations/README.md#getorganization) - Get organization
* [updateOrganization](docs/sdks/organizations/README.md#updateorganization) - Update organization
* [deleteOrganization](docs/sdks/organizations/README.md#deleteorganization) - Delete organization
* [getOrganizationBySlug](docs/sdks/organizations/README.md#getorganizationbyslug) - Get organization by slug
* [checkOrganizationSlug](docs/sdks/organizations/README.md#checkorganizationslug) - Check slug availability
* [getOrganizationMemberCount](docs/sdks/organizations/README.md#getorganizationmembercount) - Get member count

### [ProviderConfigs](docs/sdks/providerconfigs/README.md)

* [listProviders](docs/sdks/providerconfigs/README.md#listproviders) - List provider configs
* [createProvider](docs/sdks/providerconfigs/README.md#createprovider) - Create provider config
* [listAvailableModels](docs/sdks/providerconfigs/README.md#listavailablemodels) - List available models
* [getProvider](docs/sdks/providerconfigs/README.md#getprovider) - Get provider config
* [updateProvider](docs/sdks/providerconfigs/README.md#updateprovider) - Update provider config
* [deleteProvider](docs/sdks/providerconfigs/README.md#deleteprovider) - Delete provider config
* [getModelsCatalog](docs/sdks/providerconfigs/README.md#getmodelscatalog) - Get models catalog
* [listProviderModels](docs/sdks/providerconfigs/README.md#listprovidermodels) - List a provider configuration models
* [testProvider](docs/sdks/providerconfigs/README.md#testprovider) - Test provider connection

### [UserProfile](docs/sdks/userprofile/README.md)

* [getProfile](docs/sdks/userprofile/README.md#getprofile) - Get current user profile
* [updateProfile](docs/sdks/userprofile/README.md#updateprofile) - Update user profile
* [deleteAccount](docs/sdks/userprofile/README.md#deleteaccount) - Delete account
* [changePassword](docs/sdks/userprofile/README.md#changepassword) - Change password
* [listSessions](docs/sdks/userprofile/README.md#listsessions) - List active sessions
* [deleteSession](docs/sdks/userprofile/README.md#deletesession) - Revoke session

### [WorkspaceMembers](docs/sdks/workspacemembers/README.md)

* [listWorkspaceMembers](docs/sdks/workspacemembers/README.md#listworkspacemembers) - List workspace members
* [addWorkspaceMember](docs/sdks/workspacemembers/README.md#addworkspacemember) - Add workspace member
* [updateWorkspaceMember](docs/sdks/workspacemembers/README.md#updateworkspacemember) - Update member role
* [removeWorkspaceMember](docs/sdks/workspacemembers/README.md#removeworkspacemember) - Remove workspace member

### [Workspaces](docs/sdks/workspaces/README.md)

* [listWorkspaces](docs/sdks/workspaces/README.md#listworkspaces) - List workspaces
* [createWorkspace](docs/sdks/workspaces/README.md#createworkspace) - Create workspace
* [getWorkspace](docs/sdks/workspaces/README.md#getworkspace) - Get workspace
* [updateWorkspace](docs/sdks/workspaces/README.md#updateworkspace) - Update workspace
* [deleteWorkspace](docs/sdks/workspaces/README.md#deleteworkspace) - Delete workspace
* [setDefaultWorkspace](docs/sdks/workspaces/README.md#setdefaultworkspace) - Set default workspace

</details>
<!-- End Available Resources and Operations [operations] -->

<!-- Start Standalone functions [standalone-funcs] -->
## Standalone functions

All the methods listed above are available as standalone functions. These
functions are ideal for use in applications running in the browser, serverless
runtimes or other environments where application bundle size is a primary
concern. When using a bundler to build your application, all unused
functionality will be either excluded from the final bundle or tree-shaken away.

To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md).

<details>

<summary>Available standalone functions</summary>

- [`agentsCreateAgent`](docs/sdks/agents/README.md#createagent) - Create agent
- [`agentsDeleteAgent`](docs/sdks/agents/README.md#deleteagent) - Delete agent
- [`agentsGetAgent`](docs/sdks/agents/README.md#getagent) - Get agent
- [`agentsGetAgentBySlug`](docs/sdks/agents/README.md#getagentbyslug) - Get agent by slug
- [`agentsListAgents`](docs/sdks/agents/README.md#listagents) - List agents
- [`agentsUpdateAgent`](docs/sdks/agents/README.md#updateagent) - Update agent
- [`invitationsCreateInvitation`](docs/sdks/invitations/README.md#createinvitation) - Create invitation
- [`invitationsDeleteInvitation`](docs/sdks/invitations/README.md#deleteinvitation) - Delete/revoke invitation
- [`invitationsGetInvitation`](docs/sdks/invitations/README.md#getinvitation) - Get invitation
- [`invitationsListInvitations`](docs/sdks/invitations/README.md#listinvitations) - List organization invitations
- [`invitationsResendInvitation`](docs/sdks/invitations/README.md#resendinvitation) - Resend invitation
- [`organizationMembersAddOrganizationMember`](docs/sdks/organizationmembers/README.md#addorganizationmember) - Add organization member
- [`organizationMembersListOrganizationMembers`](docs/sdks/organizationmembers/README.md#listorganizationmembers) - List organization members
- [`organizationMembersRemoveOrganizationMember`](docs/sdks/organizationmembers/README.md#removeorganizationmember) - Remove organization member
- [`organizationMembersUpdateOrganizationMember`](docs/sdks/organizationmembers/README.md#updateorganizationmember) - Update member role
- [`organizationsCheckOrganizationSlug`](docs/sdks/organizations/README.md#checkorganizationslug) - Check slug availability
- [`organizationsCreateOrganization`](docs/sdks/organizations/README.md#createorganization) - Create organization
- [`organizationsDeleteOrganization`](docs/sdks/organizations/README.md#deleteorganization) - Delete organization
- [`organizationsGetOrganization`](docs/sdks/organizations/README.md#getorganization) - Get organization
- [`organizationsGetOrganizationBySlug`](docs/sdks/organizations/README.md#getorganizationbyslug) - Get organization by slug
- [`organizationsGetOrganizationMemberCount`](docs/sdks/organizations/README.md#getorganizationmembercount) - Get member count
- [`organizationsListOrganizations`](docs/sdks/organizations/README.md#listorganizations) - List user organizations
- [`organizationsUpdateOrganization`](docs/sdks/organizations/README.md#updateorganization) - Update organization
- [`providerConfigsCreateProvider`](docs/sdks/providerconfigs/README.md#createprovider) - Create provider config
- [`providerConfigsDeleteProvider`](docs/sdks/providerconfigs/README.md#deleteprovider) - Delete provider config
- [`providerConfigsGetModelsCatalog`](docs/sdks/providerconfigs/README.md#getmodelscatalog) - Get models catalog
- [`providerConfigsGetProvider`](docs/sdks/providerconfigs/README.md#getprovider) - Get provider config
- [`providerConfigsListAvailableModels`](docs/sdks/providerconfigs/README.md#listavailablemodels) - List available models
- [`providerConfigsListProviderModels`](docs/sdks/providerconfigs/README.md#listprovidermodels) - List a provider configuration models
- [`providerConfigsListProviders`](docs/sdks/providerconfigs/README.md#listproviders) - List provider configs
- [`providerConfigsTestProvider`](docs/sdks/providerconfigs/README.md#testprovider) - Test provider connection
- [`providerConfigsUpdateProvider`](docs/sdks/providerconfigs/README.md#updateprovider) - Update provider config
- [`userProfileChangePassword`](docs/sdks/userprofile/README.md#changepassword) - Change password
- [`userProfileDeleteAccount`](docs/sdks/userprofile/README.md#deleteaccount) - Delete account
- [`userProfileDeleteSession`](docs/sdks/userprofile/README.md#deletesession) - Revoke session
- [`userProfileGetProfile`](docs/sdks/userprofile/README.md#getprofile) - Get current user profile
- [`userProfileListSessions`](docs/sdks/userprofile/README.md#listsessions) - List active sessions
- [`userProfileUpdateProfile`](docs/sdks/userprofile/README.md#updateprofile) - Update user profile
- [`workspaceMembersAddWorkspaceMember`](docs/sdks/workspacemembers/README.md#addworkspacemember) - Add workspace member
- [`workspaceMembersListWorkspaceMembers`](docs/sdks/workspacemembers/README.md#listworkspacemembers) - List workspace members
- [`workspaceMembersRemoveWorkspaceMember`](docs/sdks/workspacemembers/README.md#removeworkspacemember) - Remove workspace member
- [`workspaceMembersUpdateWorkspaceMember`](docs/sdks/workspacemembers/README.md#updateworkspacemember) - Update member role
- [`workspacesCreateWorkspace`](docs/sdks/workspaces/README.md#createworkspace) - Create workspace
- [`workspacesDeleteWorkspace`](docs/sdks/workspaces/README.md#deleteworkspace) - Delete workspace
- [`workspacesGetWorkspace`](docs/sdks/workspaces/README.md#getworkspace) - Get workspace
- [`workspacesListWorkspaces`](docs/sdks/workspaces/README.md#listworkspaces) - List workspaces
- [`workspacesSetDefaultWorkspace`](docs/sdks/workspaces/README.md#setdefaultworkspace) - Set default workspace
- [`workspacesUpdateWorkspace`](docs/sdks/workspaces/README.md#updateworkspace) - Update workspace

</details>
<!-- End Standalone functions [standalone-funcs] -->

<!-- Start Pagination [pagination] -->
## Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the [`for await...of`][for-await-of]
syntax.

[for-await-of]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

Here's an example of one such pagination call:

```typescript
import { Mutagent } from "@mutagent/sdk";

const mutagent = new Mutagent({
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  const result = await mutagent.agents.listAgents({
    limit: 0,
    offset: 0,
    isPublic: false,
  });

  for await (const page of result) {
    console.log(page);
  }
}

run();

```
<!-- End Pagination [pagination] -->

<!-- Start Retries [retries] -->
## Retries

Some of the endpoints in this SDK support retries.  If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API.  However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
```typescript
import { Mutagent } from "@mutagent/sdk";

const mutagent = new Mutagent({
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  const result = await mutagent.userProfile.getProfile({
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  console.log(result);
}

run();

```

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
```typescript
import { Mutagent } from "@mutagent/sdk";

const mutagent = new Mutagent({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  const result = await mutagent.userProfile.getProfile();

  console.log(result);
}

run();

```
<!-- End Retries [retries] -->

<!-- Start Error Handling [errors] -->
## Error Handling

[`MutagentError`](./src/models/errors/mutagent-error.ts) is the base class for all HTTP error responses. It has the following properties:

| Property            | Type       | Description                                                                             |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| `error.message`     | `string`   | Error message                                                                           |
| `error.statusCode`  | `number`   | HTTP response status code eg `404`                                                      |
| `error.headers`     | `Headers`  | HTTP response headers                                                                   |
| `error.body`        | `string`   | HTTP body. Can be empty string if no body is returned.                                  |
| `error.rawResponse` | `Response` | Raw HTTP response                                                                       |
| `error.data$`       |            | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). |

### Example
```typescript
import { Mutagent } from "@mutagent/sdk";
import * as errors from "@mutagent/sdk/models/errors";

const mutagent = new Mutagent({
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  try {
    const result = await mutagent.userProfile.getProfile();

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.MutagentError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);

      // Depending on the method different errors may be thrown
      if (error instanceof errors.ErrorMessage) {
        console.log(error.data$.error); // string
        console.log(error.data$.message); // string
      }
    }
  }
}

run();

```

### Error Classes
**Primary error:**
* [`MutagentError`](./src/models/errors/mutagent-error.ts): The base class for HTTP error responses.

<details><summary>Less common errors (12)</summary>

<br />

**Network errors:**
* [`ConnectionError`](./src/models/errors/http-client-errors.ts): HTTP client was unable to make a request to a server.
* [`RequestTimeoutError`](./src/models/errors/http-client-errors.ts): HTTP request timed out due to an AbortSignal signal.
* [`RequestAbortedError`](./src/models/errors/http-client-errors.ts): HTTP request was aborted by the client.
* [`InvalidRequestError`](./src/models/errors/http-client-errors.ts): Any input used to create a request is invalid.
* [`UnexpectedClientError`](./src/models/errors/http-client-errors.ts): Unrecognised or unexpected error.


**Inherit from [`MutagentError`](./src/models/errors/mutagent-error.ts)**:
* [`ErrorMessage`](./src/models/errors/error-message.ts): Applicable to 34 of 48 methods.*
* [`ErrorMessageStatusCode`](./src/models/errors/error-message-status-code.ts): Applicable to 21 of 48 methods.*
* [`ProviderError`](./src/models/errors/provider-error.ts): Standard error response. Applicable to 8 of 48 methods.*
* [`WsError`](./src/models/errors/ws-error.ts): Standard error response. Applicable to 6 of 48 methods.*
* [`TestConnectionResultError`](./src/models/errors/test-connection-result-error.ts): Provider connection test result. Applicable to 1 of 48 methods.*
* [`WorkspaceModelListingError`](./src/models/errors/workspace-model-listing-error.ts): A provider configuration's models, with this workspace's enablement applied. Status code `404`. Applicable to 1 of 48 methods.*
* [`ResponseValidationError`](./src/models/errors/response-validation-error.ts): Type mismatch between the data returned from the server and the structure expected by the SDK. See `error.rawValue` for the raw value and `error.pretty()` for a nicely formatted multi-line string.

</details>

\* Check [the method documentation](#available-resources-and-operations) to see if the error is applicable.
<!-- End Error Handling [errors] -->

<!-- Start Server Selection [server] -->
## Server Selection

### Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the `serverURL: string` optional parameter when initializing the SDK client instance. For example:
```typescript
import { Mutagent } from "@mutagent/sdk";

const mutagent = new Mutagent({
  serverURL: "http://localhost:3003",
  security: {
    apiKey: process.env["MUTAGENT_API_KEY"] ?? "",
  },
});

async function run() {
  const result = await mutagent.userProfile.getProfile();

  console.log(result);
}

run();

```
<!-- End Server Selection [server] -->

<!-- Start Custom HTTP Client [http-client] -->
## Custom HTTP Client

The TypeScript SDK makes API calls using an `HTTPClient` that wraps the native
[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). This
client is a thin wrapper around `fetch` and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.

The `HTTPClient` constructor takes an optional `fetcher` argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.

The following example shows how to:
- route requests through a proxy server using [undici](https://www.npmjs.com/package/undici)'s ProxyAgent
- use the `"beforeRequest"` hook to add a custom header and a timeout to requests
- use the `"requestError"` hook to log errors

```typescript
import { Mutagent } from "@mutagent/sdk";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@mutagent/sdk/lib/http";

const dispatcher = new ProxyAgent("http://proxy.example.com:8080");

const httpClient = new HTTPClient({
  // 'fetcher' takes a function that has the same signature as native 'fetch'.
  fetcher: (input, init) =>
    // 'dispatcher' is specific to undici and not part of the standard Fetch API.
    fetch(input, { ...init, dispatcher } as RequestInit),
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000)
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Mutagent({ httpClient: httpClient });
```
<!-- End Custom HTTP Client [http-client] -->

<!-- Start Debugging [debug] -->
## Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches `console`'s interface as an SDK option.

> [!WARNING]
> Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

```typescript
import { Mutagent } from "@mutagent/sdk";

const sdk = new Mutagent({ debugLogger: console });
```

You can also enable a default debug logger by setting an environment variable `MUTAGENT_DEBUG` to true.
<!-- End Debugging [debug] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->
