# Metorial + Vercel AI SDK (v5/v6)

Uses the [Vercel AI SDK](https://sdk.vercel.ai/) with OpenAI to stream AI responses with MCP tool calls via [Metorial](https://metorial.com). Works with both AI SDK v5 and v6 (same `inputSchema` tool format). Includes commented-out OAuth code you can enable to add providers like GitHub or Slack.

## Environment variables

- `METORIAL_API_KEY` — get one at [platform.metorial.com](https://platform.metorial.com)
- `OPENAI_API_KEY` — from [platform.openai.com](https://platform.openai.com)

## Run

```bash
bun install
bun start
```

## How it works

```typescript
import { openai } from '@ai-sdk/openai';
import { metorialAiSdk } from '@metorial/ai-sdk';
import { Metorial } from 'metorial';
import { streamText, stepCountIs } from 'ai';

// Initialize clients and create a deployment for the built-in Metorial Search provider.
let metorial = new Metorial({ apiKey: process.env.METORIAL_API_KEY! });

let deployment = await metorial.providerDeployments.create({
  name: 'Metorial Search',
  providerId: 'metorial-search'
});

// To use a provider that requires OAuth (like GitHub or Slack), you'd create a setup session
// first. This is commented out in the code — uncomment it to try:
// let setupSession = await metorial.providerDeployments.setupSessions.create({
//   providerId: oauthProviderId,
//   providerAuthMethodId: oauthAuthMethodId
// });
// console.log('Complete OAuth at:', setupSession.url);
// let [completedSession] = await metorial.providerDeployments.setupSessions.waitForCompletion([setupSession]);

// Open a session. `metorialAiSdk()` is the adapter that formats MCP tools for the Vercel AI SDK.
// You can pass multiple providers in the `providers` array — here we just use Metorial Search,
// but the commented-out block shows adding an OAuth provider alongside it.
let session = await metorial.connect({
  adapter: metorialAiSdk(),
  providers: [
    { providerDeploymentId: deployment.id }
    // { providerDeploymentId: oauthProviderDeploymentId, providerAuthConfigId: completedSession.authConfig!.id }
  ]
});

// `streamText()` handles the tool call loop automatically. When the model wants to use a tool,
// the AI SDK calls it and feeds the result back. `onStepFinish` logs which tools were called
// at each step.
let result = streamText({
  model: openai('gpt-4o-mini'),
  prompt:
    'Search the web for the latest news about AI agents and summarize the top 3 stories.',
  stopWhen: stepCountIs(10),
  tools: session.tools(),
  onStepFinish: step => {
    if (step.toolCalls?.length) {
      console.log(`\n🔧 ${step.toolCalls.map(tc => tc.toolName).join(', ')}\n`);
    }
  }
});

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