tools-and-context

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tools and Context

工具与上下文

Gives Tambo access to data and capabilities through tools, MCP servers, and context.
让Tambo能够通过工具、MCP服务器和上下文获取数据与功能。

Quick Start

快速开始

tsx
// Custom tool Tambo can call
const fetchUserTool = defineTool({
  name: "fetchUser",
  description: "Fetch user by ID",
  inputSchema: z.object({ userId: z.string() }),
  tool: async ({ userId }) => fetchUser(userId),
});

<TamboProvider tools={[fetchUserTool]}>
  <App />
</TamboProvider>;
tsx
// Custom tool Tambo can call
const fetchUserTool = defineTool({
  name: "fetchUser",
  description: "Fetch user by ID",
  inputSchema: z.object({ userId: z.string() }),
  tool: async ({ userId }) => fetchUser(userId),
});

<TamboProvider tools={[fetchUserTool]}>
  <App />
</TamboProvider>;

Custom Tools

自定义工具

Register JavaScript functions Tambo can call:
tsx
import { defineTool, TamboProvider } from "@tambo-ai/react";
import { z } from "zod";

const fetchUserTool = defineTool({
  name: "fetchUser",
  description: "Fetch a user by ID",
  inputSchema: z.object({
    userId: z.string().describe("The user ID to fetch"),
  }),
  outputSchema: z.object({
    name: z.string(),
    email: z.string(),
  }),
  tool: async ({ userId }) => {
    const user = await fetchUser(userId);
    return user;
  },
});

<TamboProvider tools={[fetchUserTool]} components={components}>
  <App />
</TamboProvider>;
注册Tambo可调用的JavaScript函数:
tsx
import { defineTool, TamboProvider } from "@tambo-ai/react";
import { z } from "zod";

const fetchUserTool = defineTool({
  name: "fetchUser",
  description: "Fetch a user by ID",
  inputSchema: z.object({
    userId: z.string().describe("The user ID to fetch"),
  }),
  outputSchema: z.object({
    name: z.string(),
    email: z.string(),
  }),
  tool: async ({ userId }) => {
    const user = await fetchUser(userId);
    return user;
  },
});

<TamboProvider tools={[fetchUserTool]} components={components}>
  <App />
</TamboProvider>;

Tool Key Points

工具关键点

  • inputSchema: Zod object for parameters, use
    .describe()
    on fields
  • outputSchema: Zod schema for return value (optional)
  • tool: Function receives single object with input params
  • transformToContent: Enable rich content responses (images, formatted text)
  • inputSchema: 用于参数校验的Zod对象,可对字段使用
    .describe()
    方法
  • outputSchema: 返回值的Zod schema(可选)
  • tool: 接收包含输入参数的单个对象的函数
  • transformToContent: 启用富内容响应(图片、格式化文本)

MCP Servers

MCP服务器

Connect to external MCP servers for tools, resources, prompts:
FeatureServer-sideClient-side
PerformanceFast (direct)Slower (browser proxies)
AuthOAuth + API keysBrowser session only
Local serversNoYes (localhost)
ConfigTambo dashboardReact code
连接外部MCP服务器以获取工具、资源和提示词:
特性服务端客户端
性能快速(直接连接)较慢(浏览器代理)
认证OAuth + API密钥仅浏览器会话
本地服务器不支持支持(localhost)
配置Tambo控制台React代码

Server-Side Setup

服务端设置

  1. Go to project dashboard
  2. Click "Add MCP Server"
  3. Enter URL and server type (StreamableHTTP or SSE)
  4. Complete OAuth if required
  1. 访问项目控制台
  2. 点击“Add MCP Server”
  3. 输入URL和服务器类型(StreamableHTTP或SSE)
  4. 如需完成OAuth认证

Client-Side Setup

客户端设置

bash
npm install @modelcontextprotocol/sdk@^1.24.0 zod@^4.0.0 zod-to-json-schema@^3.25.0
tsx
import { TamboProvider } from "@tambo-ai/react";
import { MCPTransport } from "@tambo-ai/react/mcp";

<TamboProvider
  mcpServers={[
    {
      url: "http://localhost:8123/",
      serverKey: "local",
      transport: MCPTransport.HTTP,
    },
  ]}
>
  <App />
</TamboProvider>;
bash
npm install @modelcontextprotocol/sdk@^1.24.0 zod@^4.0.0 zod-to-json-schema@^3.25.0
tsx
import { TamboProvider } from "@tambo-ai/react";
import { MCPTransport } from "@tambo-ai/react/mcp";

<TamboProvider
  mcpServers={[
    {
      url: "http://localhost:8123/",
      serverKey: "local",
      transport: MCPTransport.HTTP,
    },
  ]}
>
  <App />
</TamboProvider>;

Context Helpers

上下文助手

Provide dynamic context on every message:
tsx
<TamboProvider
  contextHelpers={{
    currentPage: () => ({ url: window.location.href }),
    currentTime: () => ({ time: new Date().toISOString() }),
    selectedItems: () => selectedItems.map((i) => i.name),
  }}
>
  <App />
</TamboProvider>
为每条消息提供动态上下文:
tsx
<TamboProvider
  contextHelpers={{
    currentPage: () => ({ url: window.location.href }),
    currentTime: () => ({ time: new Date().toISOString() }),
    selectedItems: () => selectedItems.map((i) => i.name),
  }}
>
  <App />
</TamboProvider>

Dynamic Context Helpers

动态上下文助手

Add/remove helpers at runtime:
tsx
const { addContextHelper, removeContextHelper } = useTamboContextHelpers();

useEffect(() => {
  addContextHelper("project", () => ({ projectId, projectName }));
  return () => removeContextHelper("project");
}, [projectId, projectName, addContextHelper, removeContextHelper]);
在运行时添加/移除助手:
tsx
const { addContextHelper, removeContextHelper } = useTamboContextHelpers();

useEffect(() => {
  addContextHelper("project", () => ({ projectId, projectName }));
  return () => removeContextHelper("project");
}, [projectId, projectName, addContextHelper, removeContextHelper]);

Context Attachments

上下文附件

One-time context for the next message (cleared after sending):
tsx
const { addContextAttachment, attachments, removeContextAttachment } =
  useTamboContextAttachment();

function handleSelectFile(file) {
  addContextAttachment({
    context: file.content,
    displayName: file.name,
    type: "file",
  });
}
为下一条消息提供一次性上下文(发送后自动清除):
tsx
const { addContextAttachment, attachments, removeContextAttachment } =
  useTamboContextAttachment();

function handleSelectFile(file) {
  addContextAttachment({
    context: file.content,
    displayName: file.name,
    type: "file",
  });
}

Local Resources

本地资源

Register @ mentionable resources users can reference in messages:
注册用户可在消息中@提及的资源:

Static Resources

静态资源

tsx
import { TamboProvider, ListResourceItem } from "@tambo-ai/react";

const resources: ListResourceItem[] = [
  { uri: "docs://api", name: "API Reference", mimeType: "text/plain" },
  { uri: "docs://faq", name: "FAQ", mimeType: "text/plain" },
];

const getResource = async (uri: string) => {
  const content = await fetchDoc(uri);
  return { contents: [{ uri, mimeType: "text/plain", text: content }] };
};

<TamboProvider resources={resources} getResource={getResource}>
  <App />
</TamboProvider>;
tsx
import { TamboProvider, ListResourceItem } from "@tambo-ai/react";

const resources: ListResourceItem[] = [
  { uri: "docs://api", name: "API Reference", mimeType: "text/plain" },
  { uri: "docs://faq", name: "FAQ", mimeType: "text/plain" },
];

const getResource = async (uri: string) => {
  const content = await fetchDoc(uri);
  return { contents: [{ uri, mimeType: "text/plain", text: content }] };
};

<TamboProvider resources={resources} getResource={getResource}>
  <App />
</TamboProvider>;

Dynamic Resources

动态资源

tsx
const listResources = async (search?: string) => {
  const docs = await fetchDocs();
  return docs
    .filter((d) => !search || d.name.includes(search))
    .map((d) => ({
      uri: `docs://${d.id}`,
      name: d.title,
      mimeType: "text/plain",
    }));
};

const getResource = async (uri: string) => {
  const doc = await fetchDocument(uri);
  return { contents: [{ uri, mimeType: "text/plain", text: doc.content }] };
};

// Both listResources and getResource must be provided together
<TamboProvider listResources={listResources} getResource={getResource}>
  <App />
</TamboProvider>;
tsx
const listResources = async (search?: string) => {
  const docs = await fetchDocs();
  return docs
    .filter((d) => !search || d.name.includes(search))
    .map((d) => ({
      uri: `docs://${d.id}`,
      name: d.title,
      mimeType: "text/plain",
    }));
};

const getResource = async (uri: string) => {
  const doc = await fetchDocument(uri);
  return { contents: [{ uri, mimeType: "text/plain", text: doc.content }] };
};

// Both listResources and getResource must be provided together
<TamboProvider listResources={listResources} getResource={getResource}>
  <App />
</TamboProvider>;

Programmatic Registration

程序化注册

tsx
const { registerResource, registerResources } = useTamboRegistry();

// Single resource
registerResource({
  uri: "user://file.txt",
  name: "File",
  mimeType: "text/plain",
});

// Batch registration
registerResources(
  docs.map((d) => ({
    uri: `docs://${d.id}`,
    name: d.title,
    mimeType: "text/plain",
  })),
);
tsx
const { registerResource, registerResources } = useTamboRegistry();

// Single resource
registerResource({
  uri: "user://file.txt",
  name: "File",
  mimeType: "text/plain",
});

// Batch registration
registerResources(
  docs.map((d) => ({
    uri: `docs://${d.id}`,
    name: d.title,
    mimeType: "text/plain",
  })),
);

Context Types Summary

上下文类型汇总

TypeWhen CalledUse Case
Context HelpersEvery messageAmbient state (current page, time)
Context AttachmentsNext message onlyUser-selected files, selections
ResourcesWhen @ mentionedDocumentation, searchable data
类型调用时机使用场景
上下文助手每条消息发送时环境状态(当前页面、时间)
上下文附件仅下一条消息用户选择的文件、选中内容
资源被@提及时文档、可搜索数据