Skip to main content
What you’ll learn:
  • How to install the Metorial SDK
  • Available AI providers and integrations
  • How to create sessions and use tools
  • OAuth flow for authenticated services
  • Streaming and session management
Before you begin:References:

Prerequisites

  1. Metorial API key: Get one from app.metorial.com
  2. Server deployment ID: Deploy a server (e.g., Exa for search)
  3. AI provider API key: OpenAI, Anthropic, Google, etc.

Installation

The Metorial SDK consists of two parts: the core SDK (which handles sessions and tool management) and a provider package (which integrates with your chosen AI model). Install both to get started.
# Install the core SDK
npm install metorial

# Install a provider package (choose one or more)
npm install @metorial/ai-sdk      # Vercel AI SDK (recommended)
npm install @metorial/anthropic   # Anthropic Claude
npm install @metorial/openai      # OpenAI
npm install @metorial/google      # Google Gemini
npm install @metorial/mistral     # Mistral
npm install @metorial/deepseek    # DeepSeek
We support OpenAI, Anthropic, Google, Mistral, DeepSeek, and any OpenAI-compatible API. See the TypeScript SDK and Python SDK repos for all available providers.

Your First AI Agent

This example shows how to create an AI agent that can use tools from your deployed MCP servers. The agent will have access to any tools provided by your server deployment (like search, file operations, or API calls). What this code does:
  1. Initializes the Metorial SDK with your API key
  2. Creates a session connected to your server deployment
  3. Passes the available tools to your AI model
  4. Streams the AI’s response back in real-time
  5. Automatically closes the session when complete
import { Metorial } from 'metorial';
import { metorialAiSdk } from '@metorial/ai-sdk';
import { anthropic } from '@ai-sdk/anthropic';
import { streamText } from 'ai';

// Initialize the Metorial SDK with your API key
let metorial = new Metorial({
    apiKey: process.env.METORIAL_API_KEY
});

// Create a session and pass tools to your AI model
await metorial.withProviderSession(
    metorialAiSdk,  // Use Vercel AI SDK provider
    {
        serverDeployments: [{ serverDeploymentId: 'your-deployment-id' }],
        streaming: true  // Enable streaming for real-time responses
    },
    async ({ tools, closeSession }) => {
        // Call your AI model with the tools from Metorial
        let result = streamText({
            model: anthropic('claude-sonnet-4-5'),
            prompt: 'Search for the latest AI research',
            tools,  // Tools from your server deployment
            onFinish: async () => {
                await closeSession();  // Clean up when done
            }
        });

        // Stream the response to your user
        for await (let textPart of result.textStream) {
            process.stdout.write(textPart);
        }
    }
);

OAuth Flow

For services requiring user authentication (like Slack, GitHub, or Google Calendar), you need to use OAuth sessions. This allows your users to authorize access to their accounts. The OAuth flow works in 4 steps:
  1. Create OAuth sessions for each service that needs authentication
  2. Send the authorization URLs to your users (they’ll approve access in their browser)
  3. Wait for the user to complete the OAuth flow
  4. Use the authenticated sessions to create tool-enabled AI agents
import { Metorial } from 'metorial';
import { metorialAnthropic } from '@metorial/anthropic';

let metorial = new Metorial({
    apiKey: process.env.METORIAL_API_KEY
});

// 1. Create OAuth sessions for each service
let slackOAuth = await metorial.oauth.sessions.create({
    serverDeploymentId: 'your-slack-deployment-id',
    callbackUrl: 'https://yourapp.com/oauth/callback'
});

let calendarOAuth = await metorial.oauth.sessions.create({
    serverDeploymentId: 'your-google-cal-deployment-id',
    callbackUrl: 'https://yourapp.com/oauth/callback'
});

// 2. Send OAuth URLs to your user
console.log('Authorize Slack:', slackOAuth.url);
console.log('Authorize Calendar:', calendarOAuth.url);

// 3. Wait for user to complete OAuth
await metorial.oauth.waitForCompletion([slackOAuth.id, calendarOAuth.id]);

// 4. Use authenticated sessions
await metorial.withProviderSession(
    metorialAnthropic,
    {
        serverDeployments: [
            {
                serverDeploymentId: 'your-slack-deployment-id',
                oauthSessionId: slackOAuth.id
            },
            {
                serverDeploymentId: 'your-google-cal-deployment-id',
                oauthSessionId: calendarOAuth.id
            },
            {
                serverDeploymentId: 'your-exa-deployment-id' // No OAuth needed
            }
        ]
    },
    async ({ tools, closeSession }) => {
        // Use tools from all three services
        await closeSession();
    }
);

Session Options

Streaming Mode

When your AI model streams responses back to users in real-time, you need to enable streaming mode in Metorial. This ensures that tool calls work correctly with streamed responses.
await metorial.withProviderSession(
    metorialAiSdk,
    {
        serverDeployments: ['your-deployment-id'],
        streaming: true // Required for streaming with tool calls
    },
    async ({ tools, closeSession }) => {
        // Your streaming code
        await closeSession();
    }
);

Closing Sessions

Sessions maintain an active connection to your MCP servers. Always close your session when you’re done to free up resources and ensure clean disconnection from your deployments.
async ({ tools, closeSession }) => {
    // Use tools...

    // For streaming, close in onFinish callback:
    let result = streamText({
        tools,
        onFinish: async () => {
            await closeSession();
        }
    });

    // Or close directly when done:
    await closeSession();
}

Error Handling

The Metorial SDK provides specific error types to help you handle different failure scenarios. Catch MetorialAPIError for API-related issues like authentication failures, rate limits, or invalid deployment IDs.
import { MetorialAPIError } from 'metorial';

try {
    await metorial.withProviderSession(/* ... */);
} catch (error) {
    if (error instanceof MetorialAPIError) {
        console.error(`API Error: ${error.message} (Status: ${error.status})`);
    } else {
        console.error('Unexpected error:', error);
    }
}

What’s Next?