Skip to main content
What you’ll learn:
  • What sessions are and how they work
  • How to create and close sessions
  • Streaming mode for real-time responses
  • Using OAuth with sessions

What is a Session?

A session is an active connection to one or more MCP server deployments. During a session, your AI application can:
  • Discover available tools
  • Execute tool calls
  • Handle OAuth-authenticated requests

Creating Sessions

import { Metorial } from 'metorial';
import { metorialAiSdk } from '@metorial/ai-sdk';

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

await metorial.withProviderSession(
    metorialAiSdk,
    {
        serverDeployments: [
            { serverDeploymentId: 'your-deployment-id' }
        ]
    },
    async ({ tools, callTools, closeSession }) => {
        // tools: Array of tools formatted for your provider
        // callTools: Function to execute tool calls
        // closeSession: Function to close the session

        await closeSession();
    }
);

Session Options

Streaming Mode

Enable streaming for real-time AI responses:
import { Metorial } from 'metorial';
import { metorialAiSdk } from '@metorial/ai-sdk';
import { anthropic } from '@ai-sdk/anthropic';
import { streamText } from 'ai';

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

await metorial.withProviderSession(
    metorialAiSdk,
    {
        serverDeployments: [
            { serverDeploymentId: 'your-deployment-id' }
        ],
        streaming: true
    },
    async ({ tools, closeSession }) => {
        let result = streamText({
            model: anthropic('claude-sonnet-4-5'),
            prompt: 'Your prompt',
            tools: tools,
            onFinish: async () => await closeSession()
        });

        for await (let text of result.textStream) {
            process.stdout.write(text);
        }
    }
);

With OAuth

Include OAuth session for authenticated integrations:
{
    serverDeployments: [
        {
            serverDeploymentId: 'slack-deployment',
            oauthSessionId: 'oauth_abc123'
        }
    ]
}

Multiple Deployments

Combine tools from multiple deployments in one session:
{
    serverDeployments: [
        { serverDeploymentId: 'github-deployment' },
        { serverDeploymentId: 'slack-deployment' },
        { serverDeploymentId: 'exa-deployment' }
    ]
}

Closing Sessions

Always close your session when done to free up resources:
async ({ tools, closeSession }) => {
    try {
        // Your code
    } finally {
        await closeSession(); // Always called
    }
}

What’s Next?