Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions DOCS_UPDATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Objective
I want to update our documentation to show how agents can be built that support web search and support MCP.

# Task
1. Create a new page called "Agent with web search"
2. Create a new page called "Agent with MCP"

In the Agent with web search, explain how how to build an AI-SDK agent that supports web search, how pricing works, and how web search works. Also explain what that looks like in Open Chat widget

In Agent with MCP, explain how to build an AI-SDK agent that is connected to an MCP server. Use MCPJam SDK.

I created a working example of web search and MCP at sdk/sandbox. Use that project to get context.

# Where
Our Mintlify documentation lives in docs
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,16 @@ Open Chat Widget lets you drop in a AI chat client right in your product. You ju

### Why Open Chat Widget

I'll be honest, there's a TON of chatbot frameworks out there, why use us? You came here because you want a working chat, not a new framework to learn. Open Chat Widget gives you a prod ready chat out of the box. We're opinionated about design and UX so you can skip the decisions and focus on what matters, building your agent.
You came here because you want a working chat bot, not a new framework to learn. Open Chat Widget gives you a prod ready chat out of the box. We're opinionated about design and UX so you can skip the decisions and focus on what matters: building your agent.

- **Plug and play** - A single component you drop in to your website. You get access to feature rich AI chat with text streaming, web search, tool use, etc. out of the box. Set up is a few lines of code.

- **Works with AI SDK** — Build custom agents with [Vercel AI SDK](https://ai-sdk.dev/). Use any LLM model and create custom workflows. Works directly with existing AI-SDK endpoints.

- **Framework-agnostic** — Plugs in to any web framework or website platform: React, Next.js, Vue, WordPress, Shopify, Wix.

- **Support for MCP** - Compatible with MCP servers. Connect to MCP servers and use its tools. Support for MCP apps (MCP-UI) coming soon.

- **Open source** — MIT licensed. Free forever. You own your data and infrastructure.

<div align="center">
Expand Down
88 changes: 88 additions & 0 deletions docs/agent-with-mcp.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
title: "Agent with MCP"
description: "Build an AI SDK agent connected to an MCP server"
---

You can build an AI SDK agent connected to an MCP server and expose it through one streaming endpoint.

## Install and configure

Install `@mcpjam/sdk` first. It provides `MCPClientManager`, which connects your agent to an MCP server and exposes MCP tools to AI SDK.

```bash
npm i @mcpjam/sdk
```

## Build the agent

Use `MCPClientManager` to connect to your MCP server, fetch AI SDK-compatible tools, and pass them directly into `streamText` in your `/api/chat` handler.

```ts
import { MCPClientManager } from "@mcpjam/sdk";
import {
convertWidgetMessagesToModelMessages,
createOpenAI,
stepCountIs,
streamText,
type UIMessage,
} from "@openchatwidget/sdk";

app.post("/api/chat", async (request, response) => {
const { messages } = request.body as { messages: UIMessage[] };

const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

const manager = new MCPClientManager();
await manager.connectToServer("workspace", {
url: "https://mcp.notion.com/mcp",
requestInit: {
headers: {
Authorization: `Bearer ${process.env.NOTION_TOKEN}`,
},
},
});

const mcpTools = await manager.getToolsForAiSdk(["workspace"]);

const result = streamText({
model: openai("gpt-4o-mini"),
system: "Use MCP tools when needed.",
messages: await convertWidgetMessagesToModelMessages(messages),
stopWhen: stepCountIs(10),
tools: { ...mcpTools },
onFinish: async () => {
await manager.disconnectAllServers();
},
onAbort: async () => {
await manager.disconnectAllServers();
},
onError: async () => {
await manager.disconnectAllServers();
},
});

result.pipeUIMessageStreamToResponse(response);
});
```

Then point your widget at the same endpoint:

```tsx
<OpenChatWidget url="http://localhost:8787/api/chat" />
```

## How this appears in Open Chat Widget

The widget displays MCP tool execution as normal AI SDK tool parts:

- Tool cards show each tool call and status (running, complete, denied, error).
- Approval-required tools can be approved or denied in the chat UI.
- Responses keep streaming while tools are called in agent steps.

Because this is standard AI SDK tool streaming, MCP and non-MCP tools can be mixed in one agent.

### Example

![MCP example in Open Chat Widget](/images/mcp-example.png)
85 changes: 85 additions & 0 deletions docs/agent-with-web-search.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
---
title: "Agent with web search"
description: "Build an AI SDK agent with native web search"
---

Use web search when your agent needs fresh information from the internet, such as news, product launches, docs updates, or recent events. You can give your agent web search capabilities with a couple of changes on the backend.

## Build an AI SDK agent with web search

Add web search directly in your `/api/chat` streaming handler:

```ts
import {
convertWidgetMessagesToModelMessages,
createOpenAI,
stepCountIs,
streamText,
type UIMessage,
} from "@openchatwidget/sdk";

app.post("/api/chat", async (request, response) => {
const { messages } = request.body as { messages: UIMessage[] };

const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

const result = streamText({
model: openai("gpt-5-mini"),
system:
"You are an assistant. Use web_search for current events or up-to-date information.",
messages: await convertWidgetMessagesToModelMessages(messages),
stopWhen: stepCountIs(5),
tools: {
web_search: openai.tools.webSearch({
externalWebAccess: true,
searchContextSize: "medium",
}),
},
});

result.pipeUIMessageStreamToResponse(response);
});
```

The important part is the `tools.web_search` registration. Once this is present, the model can call web search during generation.

## How web search works

At runtime, the model decides when to call `web_search` based on your prompt and the user question.

Typical flow:

1. User asks a question that likely needs current information.
2. Model triggers `web_search`.
3. Tool returns web context to the model.
4. Model uses that context to generate a final answer.
5. The full response is streamed back to Open Chat Widget.

Use system prompt instructions to control when search is used. For example, you can require search for time-sensitive topics and avoid search for evergreen topics.

## Pricing for web search

Web search usually adds cost in two ways:

1. Model token usage:
The request still consumes input/output tokens.
2. Tool usage:
Provider-specific web search calls may have additional per-call or usage-based charges.

Check your model provider pricing page for exact rates and web search pricing details. Costs can change over time.

## What this looks like in Open Chat Widget

Open Chat Widget renders tool activity and reasoning as streamed message parts:

- When the model is thinking, users see a collapsible reasoning panel.
- When a tool runs, users see a tool card (for example `Web Search`), with status like running, complete, denied, or failed.
- If a tool requires approval, the widget shows Approve/Reject controls and resumes automatically after the response.

This behavior is built in. You only need to stream AI SDK UI messages from your backend.

### Example

![Web search example in Open Chat Widget](/images/web-search-example.png)
2 changes: 2 additions & 0 deletions docs/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"group": "Building agents",
"pages": [
"agent-use-cases",
"agent-with-web-search",
"agent-with-mcp",
"compatibility"
]
},
Expand Down
Binary file added docs/images/mcp-example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/web-search-example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Use it to build customer service agents (free Intercom Fin alternative), knowled
- **Plug and play** - A single component you drop in to your website. You get access to feature rich AI chat with text streaming, web search, tool use, etc. out of the box. Set up is a few lines of code.
- **Build any AI agent** — Build custom agents with [Vercel AI SDK](https://ai-sdk.dev/). Use any LLM model and create custom workflows. Works directly with existing AI-SDK endpoints.
- **Framework-agnostic** — Plugs in to any web framework or website platform: React, Next.js, Vue, WordPress, Shopify, Wix.
- **Support for MCP** - Compatible with MCP servers. Connect to MCP servers and use its tools. Support for MCP apps (MCP-UI) coming soon.
- **Open source** — MIT licensed. Free forever. You own your data and infrastructure.

<Frame>
Expand Down
4 changes: 2 additions & 2 deletions sdk/sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Set at least:

```bash
OPENAI_API_KEY=...
ASANA_TOKEN=...
NOTION_TOKEN=...
```

3. Start both the frontend and backend:
Expand All @@ -35,7 +35,7 @@ npm run dev
Frontend: `http://localhost:5173`
API info: `http://localhost:8787/api/chat`
Chat endpoint: `http://localhost:8787/api/chat/default`
Asana endpoint: `http://localhost:8787/api/chat/asana`
Notion endpoint: `http://localhost:8787/api/chat/notion`

The landing page mounts `<OpenChatWidget />`, and the widget streams responses
from the Hono sandbox API, including AI SDK `reasoning` parts.
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,39 @@ import {
type UIMessage,
} from "../../../widget/src/index";

function getAsanaConfig() {
const asanaToken = process.env.ASANA_TOKEN || process.env.ASANA_MCP_ACCESS_TOKEN;
const serverUrl = process.env.ASANA_MCP_SERVER_URL || "https://mcp.asana.com/sse";
function getNotionConfig() {
const notionToken = process.env.NOTION_TOKEN;
const serverUrl = process.env.NOTION_MCP_SERVER_URL || "https://mcp.notion.com/mcp";

if (!asanaToken) {
if (!notionToken) {
throw new Error(
"Missing ASANA_TOKEN. Add it to sdk/sandbox/.env to enable the Asana agent.",
"Missing NOTION_TOKEN. Add it to sdk/sandbox/.env to enable the Notion agent.",
);
}

return { asanaToken, serverUrl };
return { notionToken, serverUrl };
}

export async function runAsanaAgent(messages: UIMessage[]) {
export async function runNotionAgent(messages: UIMessage[]) {
const modelId = "gpt-4o-mini";
const baseSystemPrompt =
process.env.OPENCHAT_PROMPT ||
"You are the OpenChatWidget Asana assistant. Keep answers concise and useful.";
const { asanaToken, serverUrl } = getAsanaConfig();
"You are the OpenChatWidget Notion assistant. Keep answers concise and useful.";
const { notionToken, serverUrl } = getNotionConfig();

const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

const manager = new MCPClientManager();
await manager.connectToServer("asana", {
await manager.connectToServer("notion", {
url: serverUrl,
requestInit: {
headers: { Authorization: `Bearer ${asanaToken}` },
headers: { Authorization: `Bearer ${notionToken}` },
},
});

const asanaTools = await manager.getToolsForAiSdk(["asana"]);
const notionTools = await manager.getToolsForAiSdk(["notion"]);
let isClosed = false;

const closeManager = async () => {
Expand All @@ -52,13 +52,13 @@ export async function runAsanaAgent(messages: UIMessage[]) {
model: openai(modelId),
system:
`${baseSystemPrompt} ` +
"You can use Asana MCP tools for Asana operations. " +
"You can use Notion MCP tools for Notion operations. " +
"Use the native web_search tool for current events or up-to-date web information. " +
"If a tool execution is denied or fails, explain what happened and suggest the next action.",
messages: await convertWidgetMessagesToModelMessages(messages),
stopWhen: stepCountIs(10),
tools: {
...asanaTools,
...notionTools,
web_search: openai.tools.webSearch({
externalWebAccess: true,
searchContextSize: "medium",
Expand Down
12 changes: 6 additions & 6 deletions sdk/sandbox/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { Hono } from "hono";
import { cors } from "hono/cors";
import { config as loadEnv } from "dotenv";
import type { UIMessage } from "../../widget/src/index";
import { runAsanaAgent } from "./agents/asana";
import { runDefaultAgent } from "./agents/default";
import { runNotionAgent } from "./agents/notion";

const sandboxEnvLocal = fileURLToPath(new URL("../.env.local", import.meta.url));
const sandboxEnv = fileURLToPath(new URL("../.env", import.meta.url));
Expand All @@ -29,7 +29,7 @@ app.get("/api/chat", (c) =>
defaultAgentId: "default",
routes: {
default: "/api/chat/default",
asana: "/api/chat/asana",
notion: "/api/chat/notion",
},
}),
);
Expand All @@ -44,12 +44,12 @@ app.post("/api/chat/default", async (c) => {
});
});

app.post("/api/chat/asana", async (c) => {
app.post("/api/chat/notion", async (c) => {
const body = (await c.req.json()) as { messages?: UIMessage[] };
const messages = body.messages ?? [];

try {
const result = await runAsanaAgent(messages);
const result = await runNotionAgent(messages);

return result.toUIMessageStreamResponse({
sendReasoning: true,
Expand All @@ -58,7 +58,7 @@ app.post("/api/chat/asana", async (c) => {
const message =
error instanceof Error
? error.message
: "Failed to start Asana agent. Check ASANA_MCP_ACCESS_TOKEN.";
: "Failed to start Notion agent. Check NOTION_TOKEN.";
return c.json({ error: message }, 500);
}
});
Expand All @@ -71,7 +71,7 @@ serve(
(info) => {
console.log(`Hono agent listening on http://localhost:${info.port}`);
console.log(
"Available chat routes: GET /api/chat, POST /api/chat/default, POST /api/chat/asana",
"Available chat routes: GET /api/chat, POST /api/chat/default, POST /api/chat/notion",
);
},
);
2 changes: 1 addition & 1 deletion sdk/sandbox/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { OpenChatWidget } from "../../widget/src";

const chatApiUrl =
import.meta.env.VITE_CHAT_API_URL ?? "http://localhost:8787/api/chat/asana";
import.meta.env.VITE_CHAT_API_URL ?? "http://localhost:8787/api/chat/notion";

export default function App() {
return (
Expand Down
Loading