Tulip Logo IconTulip
Concepts

Services

Run agents, save chats and serve MCP apps with Agents, Chat and Mcp, three services that check every tool call the same way.

The AI package has three server services. Each is set up once with init, has its own tables, and can be used without the others:

ServiceOwnsNeeds
Agentsstarting agents and recording their runs, approvals that wait for a person, and what each agent may donothing
Chatthe saved chats and their streamed responsesAgents
Mcpserving the tools to MCP apps, and what each app may do for its usernothing

Chat takes the Agents instance, because a chat turn is a run of an agent. Mcp only takes tools. What the three share is the tool base: how a permission is checked, how a proof is verified, and what a tool gets as context. So none of the services is configured with authorization.

The app keeps its tables, auth, queue and history. The services read and write the tables through database adapters, like History does.

Entry points

import { Agents } from "@tulip-systems/ai/agents/server";
import { Chat } from "@tulip-systems/ai/chat/server";
import { Mcp } from "@tulip-systems/ai/mcp/server";
// The Drizzle adapters and the column types of their tables
import {
  aiAgentsDrizzleAdapter,
  aiChatDrizzleAdapter,
  aiMcpDrizzleAdapter,
} from "@tulip-systems/ai/drizzle";
// The policy tables and the shared types, also for client code
import { type AgentPolicy, agentPolicyOptions } from "@tulip-systems/ai/types";

All but the last are server-only. The Drizzle adapters need drizzle-orm, and @tulip-systems/ai/mcp/server needs @modelcontextprotocol/server; both are optional peer dependencies.

Set up the tables

The app owns the tables and their migrations, and passes them to each service's adapter under these keys. The names of the tables themselves are yours. Create only the tables of the services you use.

ServiceKeyOne row per
AgentsaiAgentStatesactivated agent: whether it is on and what it may do per tool
AgentsaiRunsrun of an agent
AgentsaiApprovalstool call of a run outside the chat that waits for a person
ChataiChatssaved chat, with the tools approved for the whole chat
ChataiMessagesAI SDK UI message of a chat
McpaiMcpAppSettingsMCP app per user: whether it is on and what it may do
export const aiRuns = pgTable(
  "ai_runs",
  (t) => ({
    ...baseColumns,
    agent: t.text().notNull(),
    principalType: t.text().notNull(),
    principalId: t.text().notNull(),
    principal: t.jsonb().$type<AiPrincipal>().notNull(),
    triggerType: t.text().notNull(),
    trigger: t.jsonb().$type<AiTrigger>().notNull(),
    status: t.text().$type<AiRunStatus>().notNull(),
    threadId: t.uuid(),
    parentRunId: t.uuid(),
    depth: t.integer().notNull().default(0),
    input: t.jsonb(),
    output: t.jsonb(),
    messages: t.jsonb().$type<ModelMessage[]>(),
    error: t.text(),
    finishedAt: t.timestamp({ withTimezone: true }),
  }),
  (t) => [index().on(t.threadId), index().on(t.principalId, t.createdAt)],
);

export const aiApprovals = pgTable(
  "ai_approvals",
  (t) => ({
    id: t.text().primaryKey(),
    runId: t.uuid().notNull().references(() => aiRuns.id, { onDelete: "cascade" }),
    agent: t.text().notNull(),
    tool: t.text().notNull(),
    confirmation: t.text().$type<ToolConfirmation>().notNull(),
    toolCallId: t.text().notNull(),
    input: t.jsonb(),
    summary: t.jsonb().$type<ToolSummaryField[]>(),
    approverIds: t.jsonb().$type<string[]>().notNull(),
    status: t.text().$type<AiApprovalStatus>().notNull(),
    reason: t.text(),
    decidedBy: t.text(),
    decidedAt: t.timestamp({ withTimezone: true }),
    expiresAt: t.timestamp({ withTimezone: true }).notNull(),
    createdAt: t.timestamp({ withTimezone: true }).notNull(),
  }),
  (t) => [index().on(t.runId), index().on(t.status, t.expiresAt)],
);

export const aiAgentStates = pgTable("ai_agent_states", (t) => ({
  agent: t.text().primaryKey(),
  enabled: t.boolean().notNull(),
  policies: t.jsonb().$type<Record<string, AgentPolicy>>().notNull().default({}),
  updatedAt: t.timestamp({ withTimezone: true }).notNull().defaultNow(),
}));

The chats, messages and MCP app settings tables are in the doc comments of their column types (AiChatsDrizzleTable, AiMessagesDrizzleTable, AiMcpAppSettingsDrizzleTable). baseColumns stands for the app's id, createdAt and updatedAt columns.

Agents

// server/ai/init.ts
export const agents = Agents.init({
  agents: [assistantAgent, triageAgent],
  database: aiAgentsDrizzleAdapter({ db, schema: { aiAgentStates, aiRuns, aiApprovals } }),
  enqueueRun: async (runId) => {
    await queue.enqueue(agentRunTask, { runId });
  },
  approvals: { notify: notifyApprovers },
});
OptionWhat it does
agentsThe app's agents (defineAgent). Runs are started by an agent's name, which must be unique.
databaseThe adapter for agent states, runs and approvals (AiAgentsDatabase).
enqueueRunHands a run to the background, for example a queue job that calls agents.runs.execute(runId).
approvalsexpiresIn (milliseconds, default a day) and notify(approval) for approvals outside the chat.
generateIdGenerates ids for runs and messages. Defaults to crypto.randomUUID().
labelsdeniedByPolicy and allowedByPolicy: the reasons the chat shows for a call the workspace's setting decided, to translate them.
APIFor
agents.runRun an agent and wait for its text or typed output. See Runs.
agents.streamRun an agent and stream its response, for example into a form.
agents.startStart a run in the background and return its id.
agents.runsget, list, count and execute runs.
agents.approvalslist, count, get, decide and expire approvals. See Approvals.
agents.list, get, setActive, setPolicyThe agents, whether they are active and what they may do. See Agents.

Chat

export const chat = Chat.init({
  agents,
  database: aiChatDrizzleAdapter({ db, schema: { aiChats, aiMessages } }),
  onEvent: recordChatApproval,
  labels: { approvedForChat: "Approved for this chat" },
});
OptionWhat it does
agentsThe Agents instance. A chat turn runs one of its agents and is recorded as a run.
databaseThe adapter for chats and messages (AiChatDatabase).
onEventReceives changes made inside the chat: chat.approval.granted and chat.approval.revoked.
labelsapprovedForChat: the reason the chat shows for a call the user approved for the whole chat.

chat has list, get, rename, delete, waitsFor, approvals, revokeApproval and send. See Chat.

Mcp

export const mcp = Mcp.init({
  tools: [searchProspects, createProspect],
  database: aiMcpDrizzleAdapter({ db, schema: { aiMcpAppSettings } }),
});
OptionWhat it does
toolsThe tools MCP apps can use. Agents bring their own tools.
databaseThe adapter for the MCP app settings (AiMcpDatabase). Optional: without it every app has the default settings, and they cannot be changed.
contentFormats a tool's output for the client, by tool name. See MCP.

mcp.apps keeps what each MCP app may do for the user who connected it: "allow" or "deny" per tool, and whether the app is on. MCP apps cannot show an approval in the app, so they never get "ask first" and never run tools that need a passkey.

MethodReturns
mcp.apps.get(userId, app){ enabled, tools }: every tool with its policy and options.
mcp.apps.setPolicy(userId, app, tool, policy){ before, after }, or null when nothing changed.
mcp.apps.setEnabled(userId, app, enabled){ before, after }, or null when nothing changed.
mcp.server({ user, client, name, version })The MCP server for one request of the app, with every tool registered for the user.
mcp.call(user, client)The tool call of a request of the app, for when you build the server yourself.

What every call is checked for

Every tool call runs with a tool call the service builds: who it acts for, and its decisions on the tool. On top of the tool's own permission check:

  • Active. The agent is activated for the workspace. A new or turned off agent does not run.
  • Permission. For a user, the tool base's authorize checks the tool's permission. For an agent running as itself, only its identity.grants count.
  • Setting. The workspace's setting for the agent and tool, or for an MCP app the user's setting. A tool that is not allowed is refused with a reason the model passes on.
  • Confirmation. A tool that is allowed runs; one that asks first waits for an approval, in the chat or outside it; one the user approved for the chat runs again without asking.
  • Proof. A tool with confirmation: "passkey" always asks, and its approval only counts when the tool base's verifyProof accepts the proof.

Guidance

  • Create each service once, in server/ai/init.ts, and keep procedures thin over it.
  • Pass the signed-in user from the session, never from the client.
  • Check who may call agents.setActive and agents.setPolicy like any admin action.
  • Set verifyProof on the tool base before giving any tool confirmation: "passkey".

On this page